From 1ec9379999488d8ec8907440b3e7976334094b65 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 11:04:46 +0100 Subject: [PATCH 01/28] Update everything to 1.3.0 This breaks Cannon.js examples. --- examples/ammo.html | 2 +- examples/cannon.html | 2 +- examples/compound.html | 2 +- examples/constraints-ammo.html | 2 +- examples/constraints.html | 2 +- examples/materials.html | 2 +- examples/spring.html | 2 +- examples/stress.html | 2 +- examples/sweeper.html | 2 +- examples/ttl.html | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/ammo.html b/examples/ammo.html index 2491c54..8102669 100644 --- a/examples/ammo.html +++ b/examples/ammo.html @@ -3,7 +3,7 @@ Examples • AmmoDriver - + + + diff --git a/examples/constraints-ammo.html b/examples/constraints-ammo.html index db2b158..a1bd6b5 100644 --- a/examples/constraints-ammo.html +++ b/examples/constraints-ammo.html @@ -5,7 +5,7 @@ Examples • Constraints • AmmoDriver - + diff --git a/examples/constraints.html b/examples/constraints.html index 79fd209..66416fd 100644 --- a/examples/constraints.html +++ b/examples/constraints.html @@ -5,7 +5,7 @@ Examples • Constraints - + diff --git a/examples/materials.html b/examples/materials.html index 47f4257..d1b733d 100644 --- a/examples/materials.html +++ b/examples/materials.html @@ -4,7 +4,7 @@ Examples • Materials - + diff --git a/examples/spring.html b/examples/spring.html index 2697bb2..823d72b 100644 --- a/examples/spring.html +++ b/examples/spring.html @@ -4,7 +4,7 @@ Examples • Spring - + diff --git a/examples/stress.html b/examples/stress.html index be6259c..f245c4e 100644 --- a/examples/stress.html +++ b/examples/stress.html @@ -4,7 +4,7 @@ Examples • Stress Test - + diff --git a/examples/sweeper.html b/examples/sweeper.html index 347a8f9..8c12e60 100644 --- a/examples/sweeper.html +++ b/examples/sweeper.html @@ -4,7 +4,7 @@ Examples • Sweeper - + diff --git a/examples/ttl.html b/examples/ttl.html index fcd6337..f0896ee 100644 --- a/examples/ttl.html +++ b/examples/ttl.html @@ -3,7 +3,7 @@ Examples • TTL - + - + From d5a11cae6e5aee7bb2d4e563c45464ea1163447b Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 14:30:25 +0100 Subject: [PATCH 04/28] Move Geometry to Buffer Geometry. Haven't tested this yet... --- lib/CANNON-shape2mesh.js | 47 +++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/lib/CANNON-shape2mesh.js b/lib/CANNON-shape2mesh.js index bf6eacb..6f4f728 100644 --- a/lib/CANNON-shape2mesh.js +++ b/lib/CANNON-shape2mesh.js @@ -9,6 +9,15 @@ var CANNON = require('cannon-es'); CANNON.shape2mesh = function(body){ var obj = new THREE.Object3D(); + function createBufferGeometry(vertices, faces) { + + var geometry = new THREE.BufferGeometry(); + geometry.setFromPoints(vertices); + geometry.setIndex(faces); + geometry.computeBoundingSphere(); + return geometry; + } + for (var l = 0; l < body.shapes.length; l++) { var shape = body.shapes[l]; @@ -49,14 +58,15 @@ CANNON.shape2mesh = function(body){ break; case CANNON.Shape.types.CONVEXPOLYHEDRON: - var geo = new THREE.Geometry(); - + // Add vertices + var vertices = [] for (var i = 0; i < shape.vertices.length; i++) { var v = shape.vertices[i]; - geo.vertices.push(new THREE.Vector3(v.x, v.y, v.z)); + vertices.push(new THREE.Vector3(v.x, v.y, v.z)); } + var faces = [] for(var i=0; i < shape.faces.length; i++){ var face = shape.faces[i]; @@ -65,20 +75,21 @@ CANNON.shape2mesh = function(body){ for (var j = 1; j < face.length - 1; j++) { var b = face[j]; var c = face[j + 1]; - geo.faces.push(new THREE.Face3(a, b, c)); + faces.push(a, b, c); } } - geo.computeBoundingSphere(); - geo.computeFaceNormals(); + + var geo = createBufferGeometry(vertices, faces); mesh = new THREE.Mesh( geo, this.currentMaterial ); break; case CANNON.Shape.types.HEIGHTFIELD: - var geometry = new THREE.Geometry(); var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); + var vertices = []; + var faces = []; for (var xi = 0; xi < shape.data.length - 1; xi++) { for (var yi = 0; yi < shape.data[xi].length - 1; yi++) { for (var k = 0; k < 2; k++) { @@ -89,39 +100,39 @@ CANNON.shape2mesh = function(body){ v0.vadd(shape.pillarOffset, v0); v1.vadd(shape.pillarOffset, v1); v2.vadd(shape.pillarOffset, v2); - geometry.vertices.push( + vertices.push( new THREE.Vector3(v0.x, v0.y, v0.z), new THREE.Vector3(v1.x, v1.y, v1.z), new THREE.Vector3(v2.x, v2.y, v2.z) ); - var i = geometry.vertices.length - 3; - geometry.faces.push(new THREE.Face3(i, i+1, i+2)); + var i = vertices.length - 3; + faces.push(i, i+1, i+2); } } } - geometry.computeBoundingSphere(); - geometry.computeFaceNormals(); + var geometry = createBufferGeometry(vertices, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; case CANNON.Shape.types.TRIMESH: - var geometry = new THREE.Geometry(); + var geometry = new THREE.BufferGeometry(); var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); + var vertices = []; + var faces = []; for (var i = 0; i < shape.indices.length / 3; i++) { shape.getTriangleVertices(i, v0, v1, v2); - geometry.vertices.push( + vertices.push( new THREE.Vector3(v0.x, v0.y, v0.z), new THREE.Vector3(v1.x, v1.y, v1.z), new THREE.Vector3(v2.x, v2.y, v2.z) ); - var j = geometry.vertices.length - 3; - geometry.faces.push(new THREE.Face3(j, j+1, j+2)); + var j = vertices.length - 3; + faces.push(j, j+1, j+2); } - geometry.computeBoundingSphere(); - geometry.computeFaceNormals(); + var geometry = createBufferGeometry(vertices, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; From 7ab95ae335fe99ee2df2c871b4e06cd1a92c755e Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 14:34:10 +0100 Subject: [PATCH 05/28] Use latest sphere collider --- examples/compound.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/compound.html b/examples/compound.html index ffb5471..af7d60c 100644 --- a/examples/compound.html +++ b/examples/compound.html @@ -6,7 +6,7 @@ Examples • Compound - + From 5ba0ff9b845ed949c8e1ed26d804d7881fcd87a7 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 14:34:19 +0100 Subject: [PATCH 06/28] Updated builds --- dist/aframe-physics-system.js | 47 +++++++++++++++++++------------ dist/aframe-physics-system.min.js | 2 +- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index 4d0c6b5..9283101 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -34,6 +34,15 @@ var CANNON = require('cannon-es'); CANNON.shape2mesh = function(body){ var obj = new THREE.Object3D(); + function createBufferGeometry(vertices, faces) { + + var geometry = new THREE.BufferGeometry(); + geometry.setFromPoints(vertices); + geometry.setIndex(faces); + geometry.computeBoundingSphere(); + return geometry; + } + for (var l = 0; l < body.shapes.length; l++) { var shape = body.shapes[l]; @@ -74,14 +83,15 @@ CANNON.shape2mesh = function(body){ break; case CANNON.Shape.types.CONVEXPOLYHEDRON: - var geo = new THREE.Geometry(); - + // Add vertices + var vertices = [] for (var i = 0; i < shape.vertices.length; i++) { var v = shape.vertices[i]; - geo.vertices.push(new THREE.Vector3(v.x, v.y, v.z)); + vertices.push(new THREE.Vector3(v.x, v.y, v.z)); } + var faces = [] for(var i=0; i < shape.faces.length; i++){ var face = shape.faces[i]; @@ -90,20 +100,21 @@ CANNON.shape2mesh = function(body){ for (var j = 1; j < face.length - 1; j++) { var b = face[j]; var c = face[j + 1]; - geo.faces.push(new THREE.Face3(a, b, c)); + faces.push(a, b, c); } } - geo.computeBoundingSphere(); - geo.computeFaceNormals(); + + var geo = createBufferGeometry(vertices, faces); mesh = new THREE.Mesh( geo, this.currentMaterial ); break; case CANNON.Shape.types.HEIGHTFIELD: - var geometry = new THREE.Geometry(); var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); + var vertices = []; + var faces = []; for (var xi = 0; xi < shape.data.length - 1; xi++) { for (var yi = 0; yi < shape.data[xi].length - 1; yi++) { for (var k = 0; k < 2; k++) { @@ -114,39 +125,39 @@ CANNON.shape2mesh = function(body){ v0.vadd(shape.pillarOffset, v0); v1.vadd(shape.pillarOffset, v1); v2.vadd(shape.pillarOffset, v2); - geometry.vertices.push( + vertices.push( new THREE.Vector3(v0.x, v0.y, v0.z), new THREE.Vector3(v1.x, v1.y, v1.z), new THREE.Vector3(v2.x, v2.y, v2.z) ); - var i = geometry.vertices.length - 3; - geometry.faces.push(new THREE.Face3(i, i+1, i+2)); + var i = vertices.length - 3; + faces.push(i, i+1, i+2); } } } - geometry.computeBoundingSphere(); - geometry.computeFaceNormals(); + var geometry = createBufferGeometry(vertices, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; case CANNON.Shape.types.TRIMESH: - var geometry = new THREE.Geometry(); + var geometry = new THREE.BufferGeometry(); var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); + var vertices = []; + var faces = []; for (var i = 0; i < shape.indices.length / 3; i++) { shape.getTriangleVertices(i, v0, v1, v2); - geometry.vertices.push( + vertices.push( new THREE.Vector3(v0.x, v0.y, v0.z), new THREE.Vector3(v1.x, v1.y, v1.z), new THREE.Vector3(v2.x, v2.y, v2.z) ); - var j = geometry.vertices.length - 3; - geometry.faces.push(new THREE.Face3(j, j+1, j+2)); + var j = vertices.length - 3; + faces.push(j, j+1, j+2); } - geometry.computeBoundingSphere(); - geometry.computeFaceNormals(); + var geometry = createBufferGeometry(vertices, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index 8e65993..fdeab57 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file From 910da381edb96632411e8bfda964e0ec97bc138b Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 14:42:34 +0100 Subject: [PATCH 07/28] Update components --- examples/constraints-ammo.html | 2 +- examples/constraints.html | 2 +- examples/materials.html | 4 ++-- examples/stress.html | 4 ++-- examples/sweeper.html | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/constraints-ammo.html b/examples/constraints-ammo.html index a1bd6b5..88e5b15 100644 --- a/examples/constraints-ammo.html +++ b/examples/constraints-ammo.html @@ -7,7 +7,7 @@ Examples • Constraints • AmmoDriver - + diff --git a/examples/constraints.html b/examples/constraints.html index 66416fd..84f1bec 100644 --- a/examples/constraints.html +++ b/examples/constraints.html @@ -6,7 +6,7 @@ Examples • Constraints - + diff --git a/examples/materials.html b/examples/materials.html index d1b733d..4d536b9 100644 --- a/examples/materials.html +++ b/examples/materials.html @@ -5,8 +5,8 @@ Examples • Materials - - + + diff --git a/examples/stress.html b/examples/stress.html index f245c4e..99c3fe3 100644 --- a/examples/stress.html +++ b/examples/stress.html @@ -5,8 +5,8 @@ Examples • Stress Test - - + + diff --git a/examples/sweeper.html b/examples/sweeper.html index 8c12e60..7fc7bf5 100644 --- a/examples/sweeper.html +++ b/examples/sweeper.html @@ -5,8 +5,8 @@ Examples • Sweeper - - + + From edf7ea0210eb210047374c32b62bb2647232a53e Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 14:44:38 +0100 Subject: [PATCH 08/28] Update to latest sphere collider --- examples/constraints.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/constraints.html b/examples/constraints.html index 84f1bec..b4e6c68 100644 --- a/examples/constraints.html +++ b/examples/constraints.html @@ -8,7 +8,7 @@ - + From 429f10de0ab176f6ae4fb764ceb9a7a44ebdf5a8 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 14:55:24 +0100 Subject: [PATCH 09/28] invert -> inverse --- dist/aframe-physics-system.js | 6 +++--- dist/aframe-physics-system.min.js | 2 +- src/components/ammo-constraint.js | 2 +- src/components/body/ammo-body.js | 2 +- src/components/body/body.js | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index 9283101..b2c8b6a 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -15821,7 +15821,7 @@ module.exports = AFRAME.registerComponent("ammo-constraint", { const bodyTransform = body .getCenterOfMassTransform() - .invert() + .inverse() .op_mul(targetBody.getWorldTransform()); const targetTransform = new Ammo.btTransform(); targetTransform.setIdentity(); @@ -16347,7 +16347,7 @@ let AmmoBody = { } else { q1.set(quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w()); parentEl.object3D.getWorldQuaternion(q2); - q1.multiply(q2.invert()); + q1.multiply(q2.inverse()); el.object3D.quaternion.copy(q1); v.set(position.x(), position.y(), position.z()); @@ -16756,7 +16756,7 @@ var Body = { } else { q1.copy(body.quaternion); parentEl.object3D.getWorldQuaternion(q2); - q1.premultiply(q2.invert()); + q1.premultiply(q2.inverse()); el.object3D.quaternion.copy(q1); v.copy(body.position); diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index fdeab57..2b7c292 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file diff --git a/src/components/ammo-constraint.js b/src/components/ammo-constraint.js index 5ac1a94..c9e7ecc 100644 --- a/src/components/ammo-constraint.js +++ b/src/components/ammo-constraint.js @@ -69,7 +69,7 @@ module.exports = AFRAME.registerComponent("ammo-constraint", { const bodyTransform = body .getCenterOfMassTransform() - .invert() + .inverse() .op_mul(targetBody.getWorldTransform()); const targetTransform = new Ammo.btTransform(); targetTransform.setIdentity(); diff --git a/src/components/body/ammo-body.js b/src/components/body/ammo-body.js index 958b417..0eb561f 100644 --- a/src/components/body/ammo-body.js +++ b/src/components/body/ammo-body.js @@ -436,7 +436,7 @@ let AmmoBody = { } else { q1.set(quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w()); parentEl.object3D.getWorldQuaternion(q2); - q1.multiply(q2.invert()); + q1.multiply(q2.inverse()); el.object3D.quaternion.copy(q1); v.set(position.x(), position.y(), position.z()); diff --git a/src/components/body/body.js b/src/components/body/body.js index 0238a46..c9fcb3f 100644 --- a/src/components/body/body.js +++ b/src/components/body/body.js @@ -334,7 +334,7 @@ var Body = { } else { q1.copy(body.quaternion); parentEl.object3D.getWorldQuaternion(q2); - q1.premultiply(q2.invert()); + q1.premultiply(q2.inverse()); el.object3D.quaternion.copy(q1); v.copy(body.position); From f2437856478d6f7c4d7ac464f088c21865751014 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 15:46:14 +0100 Subject: [PATCH 10/28] Use correct offset & orientation from three-to-cannon --- dist/aframe-physics-system.js | 8 +++++--- dist/aframe-physics-system.min.js | 2 +- src/components/body/body.js | 8 +++++--- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index b2c8b6a..679169e 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -16422,10 +16422,12 @@ module.exports.Component = AFRAME.registerComponent("ammo-body", AmmoBody); },{"../../constants":19,"ammo-debug-drawer":3,"three-to-ammo":5}],10:[function(require,module,exports){ var CANNON = require('cannon-es'); const { threeToCannon, ShapeType } = require('three-to-cannon'); +const identityQuaternion = new THREE.Quaternion() function mesh2shape (object, options) { + const result = threeToCannon(object, options); - return result.shape; + return result; } require('../../../lib/CANNON-shape2mesh'); @@ -16491,13 +16493,13 @@ var Body = { type: ShapeType[data.shape.toUpperCase()] }); - var shape = mesh2shape(this.el.object3D, options); + var { shape, offset, orientation } = mesh2shape(this.el.object3D, options); if (!shape) { el.addEventListener('object3dset', this.initBody.bind(this)); return; } - this.body.addShape(shape, shape.offset, shape.orientation); + this.body.addShape(shape, offset, orientation); // Show wireframe if (this.system.debug) { diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index 2b7c292..a31aa4b 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file diff --git a/src/components/body/body.js b/src/components/body/body.js index c9fcb3f..945bec4 100644 --- a/src/components/body/body.js +++ b/src/components/body/body.js @@ -1,9 +1,11 @@ var CANNON = require('cannon-es'); const { threeToCannon, ShapeType } = require('three-to-cannon'); +const identityQuaternion = new THREE.Quaternion() function mesh2shape (object, options) { + const result = threeToCannon(object, options); - return result.shape; + return result; } require('../../../lib/CANNON-shape2mesh'); @@ -69,13 +71,13 @@ var Body = { type: ShapeType[data.shape.toUpperCase()] }); - var shape = mesh2shape(this.el.object3D, options); + var { shape, offset, orientation } = mesh2shape(this.el.object3D, options); if (!shape) { el.addEventListener('object3dset', this.initBody.bind(this)); return; } - this.body.addShape(shape, shape.offset, shape.orientation); + this.body.addShape(shape, offset, orientation); // Show wireframe if (this.system.debug) { From c175eb373946747b514eaa5f1577323967a48cec Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 15:46:33 +0100 Subject: [PATCH 11/28] Show debug info in example --- examples/cannon.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/cannon.html b/examples/cannon.html index ec6b71c..e970311 100644 --- a/examples/cannon.html +++ b/examples/cannon.html @@ -30,7 +30,7 @@ - + From b5df39bf73eec191c9976eca00b7a11bc18ff98b Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 16:02:49 +0100 Subject: [PATCH 12/28] Focus cursor on pushable entities. --- examples/compound.html | 2 ++ examples/stress.html | 1 + 2 files changed, 3 insertions(+) diff --git a/examples/compound.html b/examples/compound.html index af7d60c..c130aa8 100644 --- a/examples/compound.html +++ b/examples/compound.html @@ -15,6 +15,7 @@ @@ -35,6 +36,7 @@ shape__handle="shape: box; halfExtents: 0.15 0.18 0.04; offset: 0.4 0 0;" + force-pushable > diff --git a/examples/stress.html b/examples/stress.html index 99c3fe3..d2e9cce 100644 --- a/examples/stress.html +++ b/examples/stress.html @@ -17,6 +17,7 @@ From 04f82069c2f47912a1a354471c51010edbe032d2 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 16:06:40 +0100 Subject: [PATCH 13/28] Focus cursor on pushable entities. --- examples/materials.html | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/materials.html b/examples/materials.html index 4d536b9..0e4a2f0 100644 --- a/examples/materials.html +++ b/examples/materials.html @@ -17,6 +17,7 @@ From 78a18c0951f5d2b952782a4cc024436ddded5b1c Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 16:11:36 +0100 Subject: [PATCH 14/28] replace camera userHeight with position --- examples/compound.html | 2 +- examples/materials.html | 2 +- examples/sweeper.html | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/compound.html b/examples/compound.html index c130aa8..a77d5b7 100644 --- a/examples/compound.html +++ b/examples/compound.html @@ -13,7 +13,7 @@ - + - + - + Date: Sat, 1 Oct 2022 16:13:48 +0100 Subject: [PATCH 15/28] Add interactivity via cursor --- examples/constraints.html | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/examples/constraints.html b/examples/constraints.html index b4e6c68..e712fd8 100644 --- a/examples/constraints.html +++ b/examples/constraints.html @@ -11,18 +11,28 @@ + + + + + @@ -83,6 +95,7 @@ position="0.125 0.875 0" scale="0.25 0.25 0.25" dynamic-body + force-pushable constraint="type: pointToPoint; target: #pointtopoint-target; pivot: -0.125 -0.125 0.125; @@ -103,6 +116,7 @@ radius="0.125" position="0 1.2 0" dynamic-body + force-pushable constraint="type: distance; target: #distance-target; distance: 0.5; From cdf364640d22fc76d9eb39fc76bd8488c53e896e Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sat, 1 Oct 2022 16:37:14 +0100 Subject: [PATCH 16/28] Disabled "driver: worker" in examples as it's not working. --- examples/materials.html | 4 +++- examples/sweeper.html | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/materials.html b/examples/materials.html index ecbe9e4..c36510c 100644 --- a/examples/materials.html +++ b/examples/materials.html @@ -13,7 +13,9 @@ + physics="restitution: 1"> + + physics> + Date: Sun, 2 Oct 2022 10:32:53 +0100 Subject: [PATCH 17/28] Add commentary and code links to each example. --- examples/ammo.html | 10 +++++++++ examples/cannon.html | 10 +++++++++ examples/compound.html | 10 +++++++++ examples/constraints-ammo.html | 10 +++++++++ examples/constraints.html | 11 ++++++++++ examples/materials.html | 10 +++++++++ examples/spring.html | 10 +++++++++ examples/stress.html | 10 +++++++++ examples/styles.css | 39 ++++++++++++++++++++++++++++++++++ examples/sweeper.html | 9 ++++++++ examples/ttl.html | 9 ++++++++ 11 files changed, 138 insertions(+) create mode 100644 examples/styles.css diff --git a/examples/ammo.html b/examples/ammo.html index 8102669..f68a96a 100644 --- a/examples/ammo.html +++ b/examples/ammo.html @@ -6,6 +6,7 @@ + +
+

Demonstration of many Ammo driver features in a single example.

+

The cone is a kinematic object, and the purple box has a constraint attaching it to the cone.

+
+ + view code + + +
+

Demonstration of many Cannon driver features in a single example.

+

The cone is a kinematic object, and the purple box has a constraint attaching it to the cone.

+
+ + view code + diff --git a/examples/compound.html b/examples/compound.html index a77d5b7..a25491e 100644 --- a/examples/compound.html +++ b/examples/compound.html @@ -9,8 +9,18 @@ + +
+

Compund shape, using the Cannon driver.

+

Click when the red reticle is over the sphere to apply a force to it.

+
+ + view code + diff --git a/examples/constraints-ammo.html b/examples/constraints-ammo.html index 88e5b15..fc83bb3 100644 --- a/examples/constraints-ammo.html +++ b/examples/constraints-ammo.html @@ -10,8 +10,18 @@ + +
+

Demonstration of many Ammo driver constraints including cone + twist, hinge, lock, point to point, and slider constraints.

+
+ + view code + diff --git a/examples/constraints.html b/examples/constraints.html index e712fd8..4d457de 100644 --- a/examples/constraints.html +++ b/examples/constraints.html @@ -12,8 +12,19 @@ + +
+

Demonstration of many Cannon driver constraints including cone twist, + hinge, lock, point to point, and distance constraints.

+

Click when the red reticle is over a red object to apply a force to it.

+
+ + view code + diff --git a/examples/materials.html b/examples/materials.html index c36510c..05345d8 100644 --- a/examples/materials.html +++ b/examples/materials.html @@ -9,8 +9,18 @@ + +
+

Bounce simulation with restitution (bounciness) of 1 using the Cannon driver.

+

Click when the red reticle points at the ball to apply a force to it (if you are having trouble with timing, position yourself beneath it using WASD).

+
+ + view code + diff --git a/examples/spring.html b/examples/spring.html index 823d72b..e49e086 100644 --- a/examples/spring.html +++ b/examples/spring.html @@ -6,8 +6,18 @@ Examples • Spring + +
+

Four vertical springs each between two boxes with an + assortment of damping and stiffness values using the Cannon driver.

+
+ + view code + diff --git a/examples/stress.html b/examples/stress.html index d2e9cce..1841718 100644 --- a/examples/stress.html +++ b/examples/stress.html @@ -9,8 +9,18 @@ + +
+

Point the red reticle at a block, and click the mouse to apply a strong force to it.

+

Use mouse and WASD to look and move around.

+
+ + view code + diff --git a/examples/styles.css b/examples/styles.css new file mode 100644 index 0000000..c24a498 --- /dev/null +++ b/examples/styles.css @@ -0,0 +1,39 @@ + +.code-link { + position: fixed; + right: 50px; + top: 50px; + width: 70px; + height: 70px; + border-radius: 50%; + display: flex; + background: white; + justify-content: center; + align-items: center; + font-size: 20px; + text-decoration: none; + text-align: center; + color: black; + font-family: courier; + font-weight: bold; + z-index: 10; +} + +.text-overlay { + background: black; + color: white; + width: 40%; + position: absolute; + bottom: 10px; + left: 30%; + z-index: 10; + font-size: 20px; + font-family: arial; + display: flex; + flex-direction: column; + align-items: left; +} + +.text-overlay p { + margin: 0.2em 1em; +} diff --git a/examples/sweeper.html b/examples/sweeper.html index 95a4ba8..2a40b08 100644 --- a/examples/sweeper.html +++ b/examples/sweeper.html @@ -11,8 +11,17 @@ + +
+

Blocks fall at random from teh sky. The sweeper wall sweeps them away.

+
+ + view code + diff --git a/examples/ttl.html b/examples/ttl.html index f0896ee..5971cdf 100644 --- a/examples/ttl.html +++ b/examples/ttl.html @@ -5,6 +5,7 @@ + +
+

The box disappears after 100 frames.

+
+ + view code + From 0eb9c92dcc83f7d9699df34aa9410111467811a6 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sun, 2 Oct 2022 11:45:54 +0100 Subject: [PATCH 18/28] Change dev dependencies to fix `npm run test` error --- package-lock.json | 226 +++++++++++++--------------------------------- package.json | 4 +- 2 files changed, 65 insertions(+), 165 deletions(-) diff --git a/package-lock.json b/package-lock.json index 84b9962..ee5e660 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,7 @@ "webworkify": "^1.4.0" }, "devDependencies": { - "aframe": "^1.2.0", + "aframe": "^1.1.0", "browserify": "^16.5.1", "browserify-css": "^0.15.0", "browserify-shim": "^3.8.14", @@ -37,7 +37,7 @@ "replace": "^1.2.0", "sinon": "^2.4.1", "sinon-chai": "^2.14.0", - "three": "^0.125.0", + "three": ">=0.125.0", "uglify-es": "^3.3.9" }, "peerDependencies": { @@ -135,9 +135,9 @@ } }, "node_modules/aframe": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/aframe/-/aframe-1.3.0.tgz", - "integrity": "sha512-f6OQaDf49SzdSxVskJPvPWldOwHpYMsGttmQHhU6FRiASsnyULKG1nqZom9pDuS3fFYEzQVqRMakQ2AhXeLkFg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/aframe/-/aframe-1.1.0.tgz", + "integrity": "sha512-/8Lk7DsnSdy0ZnjDvC/0sQ4aALfp7P+EiOO5y9BGBngk9QCXdWPT1onLNwJixWrJNntLTfU5ULxFrkRZb561Hg==", "dev": true, "dependencies": { "custom-event-polyfill": "^1.0.6", @@ -149,13 +149,13 @@ "present": "0.0.6", "promise-polyfill": "^3.1.0", "super-animejs": "^3.1.0", - "super-three": "^0.137.0", - "three-bmfont-text": "github:dmarcos/three-bmfont-text#21d017046216e318362c48abd1a48bddfb6e0733", + "super-three": "^0.123.1", + "three-bmfont-text": "github:dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e", "webvr-polyfill": "^0.10.12" }, "engines": { "node": ">= 4.6.0", - "npm": ">= 2.15.9" + "npm": "^2.15.9" } }, "node_modules/aframe/node_modules/debug": { @@ -189,7 +189,7 @@ "node_modules/an-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/an-array/-/an-array-1.0.0.tgz", - "integrity": "sha512-M175GYI7RmsYu24Ok383yZQa3eveDfNnmhTe3OQ3bm70bEovz2gWenH+ST/n32M8lrwLWk74hcPds5CDRPe2wg==", + "integrity": "sha1-wSWlu4JXd4419LT2qpx9D6nkJmU=", "dev": true }, "node_modules/ansi-colors": { @@ -286,7 +286,7 @@ "node_modules/array-shuffle": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/array-shuffle/-/array-shuffle-1.0.1.tgz", - "integrity": "sha512-PBqgo1Y2XWSksBzq3GFPEb798ZrW2snAcmr4drbVeF/6MT/5aBlkGJEvu5A/CzXHf4EjbHOj/ZowatjlIiVidA==", + "integrity": "sha1-fqSIKjVrS8pfVF4LblLq9tlxVXo=", "dev": true, "engines": { "node": ">=0.10.0" @@ -310,7 +310,7 @@ "node_modules/as-number": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/as-number/-/as-number-1.0.0.tgz", - "integrity": "sha512-HkI/zLo2AbSRO4fqVkmyf3hms0bJDs3iboHqTrNuwTiCRvdYXM7HFhfhB6Dk51anV2LM/IMB83mtK9mHw4FlAg==", + "integrity": "sha1-rLJ+NPj52KsNqeN287iVmGD4CmY=", "dev": true }, "node_modules/asn1.js": { @@ -531,16 +531,6 @@ "node": ">=0.10.0" } }, - "node_modules/bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "dev": true, - "optional": true, - "dependencies": { - "file-uri-to-path": "1.0.0" - } - }, "node_modules/blob": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz", @@ -1001,7 +991,7 @@ "node_modules/buffer-to-arraybuffer": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/buffer-to-arraybuffer/-/buffer-to-arraybuffer-0.0.5.tgz", - "integrity": "sha512-3dthu5CYiVB1DEJp61FtApNnNndTckcqe4pFcLdvHtrpG+kcyekCJKg4MRiDcFW7A6AODnXB9U4dwQiCW5kzJQ==", + "integrity": "sha1-YGSkD6dutDxyOrqe+PbhIW0QURo=", "dev": true }, "node_modules/buffer-xor": { @@ -1619,7 +1609,7 @@ "node_modules/decompress-response": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha512-BzRPQuY1ip+qDonAOz42gRm/pg9F768C+npV/4JOsxRC2sq+Rlk+Q4ZCAsOhnIaMrgarILY+RMUIvMmmX1qAEA==", + "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", "dev": true, "dependencies": { "mimic-response": "^1.0.0" @@ -1894,7 +1884,7 @@ "node_modules/dtype": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/dtype/-/dtype-2.0.0.tgz", - "integrity": "sha512-s2YVcLKdFGS0hpFqJaTwscsyt0E8nNFdmo73Ocd81xNPj4URI4rj6D60A+vFMIw7BXWlb4yRkEwfBqcZzPGiZg==", + "integrity": "sha1-zQUjI84GFETs0uj1dI9popvihDQ=", "dev": true, "engines": { "node": ">= 0.8.0" @@ -2504,13 +2494,6 @@ "integrity": "sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA==", "dev": true }, - "node_modules/file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "dev": true, - "optional": true - }, "node_modules/fill-range": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", @@ -2755,25 +2738,6 @@ "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, - "node_modules/fsevents": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz", - "integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==", - "deprecated": "fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "bindings": "^1.5.0", - "nan": "^2.12.1" - }, - "engines": { - "node": ">= 4.0" - } - }, "node_modules/function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", @@ -4041,21 +4005,6 @@ "node": ">=8" } }, - "node_modules/karma/node_modules/fsevents": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz", - "integrity": "sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ==", - "deprecated": "\"Please update to latest v2.3 or v2.2\"", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, "node_modules/karma/node_modules/glob-parent": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", @@ -4156,7 +4105,7 @@ "node_modules/layout-bmfont-text": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/layout-bmfont-text/-/layout-bmfont-text-1.3.4.tgz", - "integrity": "sha512-mceomHZ8W7pSKQhTdLvOe1Im4n37u8xa5Gr0J3KPCHRMO/9o7+goWIOzZcUUd+Xgzy3+22bvoIQ0OaN3LRtgaw==", + "integrity": "sha1-8g8sVGR3T0jabOipl/vObUaUW4E=", "dev": true, "dependencies": { "as-number": "^1.0.0", @@ -4684,13 +4633,6 @@ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, - "node_modules/nan": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.1.tgz", - "integrity": "sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw==", - "dev": true, - "optional": true - }, "node_modules/nanomatch": { "version": "1.2.13", "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", @@ -4731,13 +4673,13 @@ "node_modules/new-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/new-array/-/new-array-1.0.0.tgz", - "integrity": "sha512-K5AyFYbuHZ4e/ti52y7k18q8UHsS78FlRd85w2Fmsd6AkuLipDihPflKC0p3PN5i8II7+uHxo+CtkLiJDfmS5A==", + "integrity": "sha1-XbxjnZYerH8an7wacUbsEvKST78=", "dev": true }, "node_modules/nice-color-palettes": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/nice-color-palettes/-/nice-color-palettes-1.0.1.tgz", - "integrity": "sha512-aHEFYKuGiaga8LqMi0Ttarqzn4tKS7BaIE2MeD9SDjv6yVc7DMIu/Eax4RvUgwR7vS0hXAUEIUx9P0/54O1W0g==", + "integrity": "sha1-h16gHchu+uf1leBmqLJmDnIGBT4=", "dev": true, "dependencies": { "map-limit": "0.0.1", @@ -5458,7 +5400,7 @@ "node_modules/quad-indices": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/quad-indices/-/quad-indices-2.0.1.tgz", - "integrity": "sha512-6jtmCsEbGAh5npThXrBaubbTjPcF0rMbn57XCJVI7LkW8PUT56V+uIrRCCWCn85PSgJC9v8Pm5tnJDwmOBewvA==", + "integrity": "sha1-ppQdiaE9Y+7WwdSlpiGgRjYXqBQ=", "dev": true, "dependencies": { "an-array": "^1.0.0", @@ -6293,9 +6235,9 @@ "dev": true }, "node_modules/simple-get": { - "version": "2.8.2", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.2.tgz", - "integrity": "sha512-Ijd/rV5o+mSBBs4F/x9oDPtTx9Zb6X9brmnXvMW4J7IR15ngi9q5xxqWBKU744jTZiaXtxaPL7uHG6vtN8kUkw==", + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.1.tgz", + "integrity": "sha512-lSSHRSw3mQNUGPAYRqo7xy9dhKmxFXIjLjp4KHpf99GEH2VH7C3AM+Qfx6du6jhfUi6Vm7XnbEVEf7Wb6N8jRw==", "dev": true, "dependencies": { "decompress-response": "^3.3.0", @@ -7002,9 +6944,9 @@ "dev": true }, "node_modules/super-three": { - "version": "0.137.0", - "resolved": "https://registry.npmjs.org/super-three/-/super-three-0.137.0.tgz", - "integrity": "sha512-8jM8DiYiXQoalUoeFRxKWbW6KFQo3GFwgw+3vE2y6SJU/einw+JvuvgK+WhbIYRfz4LQV68nyOQ2eEZqAuouGw==", + "version": "0.123.1", + "resolved": "https://registry.npmjs.org/super-three/-/super-three-0.123.1.tgz", + "integrity": "sha512-5P71owlReO9HmKG5OxSSb1qKBuEWVhvGIb59gZkIoqRX5WgmBfZPo7x0OZOYEd7r9nG87cRv+OyeHJCO1Qh0CA==", "dev": true }, "node_modules/supports-color": { @@ -7073,14 +7015,14 @@ "dev": true }, "node_modules/three": { - "version": "0.125.2", - "resolved": "https://registry.npmjs.org/three/-/three-0.125.2.tgz", - "integrity": "sha512-7rIRO23jVKWcAPFdW/HREU2NZMGWPBZ4XwEMt0Ak0jwLUKVJhcKM55eCBWyGZq/KiQbeo1IeuAoo/9l2dzhTXA==" + "version": "0.145.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.145.0.tgz", + "integrity": "sha512-EKoHQEtEJ4CB6b2BGMBgLZrfwLjXcSUfoI/MiIXUuRpeYsfK5aPWbYhdtIVWOH+x6X0TouldHKHBuc/LAiFzAw==" }, "node_modules/three-bmfont-text": { - "version": "2.4.0", - "resolved": "git+ssh://git@github.com/dmarcos/three-bmfont-text.git#21d017046216e318362c48abd1a48bddfb6e0733", - "integrity": "sha512-lIMa1n+QKNU1f/LZgtS1oUGpoop3MuVXrUr5ybZOUR3+Jk//zjqScnQpHml6MWyvZzL8A5/1Hd8Tsqd3M1kudA==", + "version": "2.3.0", + "resolved": "git+ssh://git@github.com/dmarcos/three-bmfont-text.git#1babdf8507c731a18f8af3b807292e2b9740955e", + "integrity": "sha512-1ACVhQynOX5fUHx9WY0leDApaQ8fa12wdU+z1iVRCiMDq5bZGw67kqUgEBrbK1BQ5awTZL3+VG3LX5xg+ty89Q==", "dev": true, "license": "MIT", "dependencies": { @@ -7139,7 +7081,7 @@ "node_modules/timed-out": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", - "integrity": "sha512-G7r3AhovYtr5YKOWQkta8RKAPb+J9IsO4uVmzjl8AZwfhs8UcUwTiD6gcJYSgOtzyjvQKrKYn41syHbUWMkafA==", + "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", "dev": true, "engines": { "node": ">=0.10.0" @@ -7480,7 +7422,7 @@ "node_modules/url-set-query": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/url-set-query/-/url-set-query-1.0.0.tgz", - "integrity": "sha512-3AChu4NiXquPfeckE5R5cGdiHCMWJx1dwCWOmWIL4KHAziJNOFIYJlpGFeKDvwLPHovZRCxK3cYlwzqI9Vp+Gg==", + "integrity": "sha1-AW6M/Xwg7gXK/neV6JK9BwL6ozk=", "dev": true }, "node_modules/url-trim": { @@ -7644,7 +7586,7 @@ "node_modules/word-wrapper": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/word-wrapper/-/word-wrapper-1.0.7.tgz", - "integrity": "sha512-VOPBFCm9b6FyYKQYfn9AVn2dQvdR/YOVFV6IBRA1TBMJWKffvhEX1af6FMGrttILs2Q9ikCRhLqkbY2weW6dOQ==", + "integrity": "sha1-HxSv6/Zt/fD+9V79NxhO+9CMKLY=", "dev": true }, "node_modules/wordwrap": { @@ -7982,9 +7924,9 @@ "dev": true }, "aframe": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/aframe/-/aframe-1.3.0.tgz", - "integrity": "sha512-f6OQaDf49SzdSxVskJPvPWldOwHpYMsGttmQHhU6FRiASsnyULKG1nqZom9pDuS3fFYEzQVqRMakQ2AhXeLkFg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/aframe/-/aframe-1.1.0.tgz", + "integrity": "sha512-/8Lk7DsnSdy0ZnjDvC/0sQ4aALfp7P+EiOO5y9BGBngk9QCXdWPT1onLNwJixWrJNntLTfU5ULxFrkRZb561Hg==", "dev": true, "requires": { "custom-event-polyfill": "^1.0.6", @@ -7996,8 +7938,8 @@ "present": "0.0.6", "promise-polyfill": "^3.1.0", "super-animejs": "^3.1.0", - "super-three": "^0.137.0", - "three-bmfont-text": "github:dmarcos/three-bmfont-text#21d017046216e318362c48abd1a48bddfb6e0733", + "super-three": "^0.123.1", + "three-bmfont-text": "github:dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e", "webvr-polyfill": "^0.10.12" }, "dependencies": { @@ -8030,7 +7972,7 @@ "an-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/an-array/-/an-array-1.0.0.tgz", - "integrity": "sha512-M175GYI7RmsYu24Ok383yZQa3eveDfNnmhTe3OQ3bm70bEovz2gWenH+ST/n32M8lrwLWk74hcPds5CDRPe2wg==", + "integrity": "sha1-wSWlu4JXd4419LT2qpx9D6nkJmU=", "dev": true }, "ansi-colors": { @@ -8108,7 +8050,7 @@ "array-shuffle": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/array-shuffle/-/array-shuffle-1.0.1.tgz", - "integrity": "sha512-PBqgo1Y2XWSksBzq3GFPEb798ZrW2snAcmr4drbVeF/6MT/5aBlkGJEvu5A/CzXHf4EjbHOj/ZowatjlIiVidA==", + "integrity": "sha1-fqSIKjVrS8pfVF4LblLq9tlxVXo=", "dev": true }, "array-unique": { @@ -8126,7 +8068,7 @@ "as-number": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/as-number/-/as-number-1.0.0.tgz", - "integrity": "sha512-HkI/zLo2AbSRO4fqVkmyf3hms0bJDs3iboHqTrNuwTiCRvdYXM7HFhfhB6Dk51anV2LM/IMB83mtK9mHw4FlAg==", + "integrity": "sha1-rLJ+NPj52KsNqeN287iVmGD4CmY=", "dev": true }, "asn1.js": { @@ -8314,16 +8256,6 @@ "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==", "dev": true }, - "bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "dev": true, - "optional": true, - "requires": { - "file-uri-to-path": "1.0.0" - } - }, "blob": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz", @@ -8761,7 +8693,7 @@ "buffer-to-arraybuffer": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/buffer-to-arraybuffer/-/buffer-to-arraybuffer-0.0.5.tgz", - "integrity": "sha512-3dthu5CYiVB1DEJp61FtApNnNndTckcqe4pFcLdvHtrpG+kcyekCJKg4MRiDcFW7A6AODnXB9U4dwQiCW5kzJQ==", + "integrity": "sha1-YGSkD6dutDxyOrqe+PbhIW0QURo=", "dev": true }, "buffer-xor": { @@ -9292,7 +9224,7 @@ "decompress-response": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha512-BzRPQuY1ip+qDonAOz42gRm/pg9F768C+npV/4JOsxRC2sq+Rlk+Q4ZCAsOhnIaMrgarILY+RMUIvMmmX1qAEA==", + "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", "dev": true, "requires": { "mimic-response": "^1.0.0" @@ -9511,7 +9443,7 @@ "dtype": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/dtype/-/dtype-2.0.0.tgz", - "integrity": "sha512-s2YVcLKdFGS0hpFqJaTwscsyt0E8nNFdmo73Ocd81xNPj4URI4rj6D60A+vFMIw7BXWlb4yRkEwfBqcZzPGiZg==", + "integrity": "sha1-zQUjI84GFETs0uj1dI9popvihDQ=", "dev": true }, "duplexer2": { @@ -10033,13 +9965,6 @@ "integrity": "sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA==", "dev": true }, - "file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "dev": true, - "optional": true - }, "fill-range": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", @@ -10248,17 +10173,6 @@ "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, - "fsevents": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz", - "integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==", - "dev": true, - "optional": true, - "requires": { - "bindings": "^1.5.0", - "nan": "^2.12.1" - } - }, "function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", @@ -11129,13 +11043,6 @@ "to-regex-range": "^5.0.1" } }, - "fsevents": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz", - "integrity": "sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ==", - "dev": true, - "optional": true - }, "glob-parent": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", @@ -11340,7 +11247,7 @@ "layout-bmfont-text": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/layout-bmfont-text/-/layout-bmfont-text-1.3.4.tgz", - "integrity": "sha512-mceomHZ8W7pSKQhTdLvOe1Im4n37u8xa5Gr0J3KPCHRMO/9o7+goWIOzZcUUd+Xgzy3+22bvoIQ0OaN3LRtgaw==", + "integrity": "sha1-8g8sVGR3T0jabOipl/vObUaUW4E=", "dev": true, "requires": { "as-number": "^1.0.0", @@ -11794,13 +11701,6 @@ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, - "nan": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.1.tgz", - "integrity": "sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw==", - "dev": true, - "optional": true - }, "nanomatch": { "version": "1.2.13", "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", @@ -11835,13 +11735,13 @@ "new-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/new-array/-/new-array-1.0.0.tgz", - "integrity": "sha512-K5AyFYbuHZ4e/ti52y7k18q8UHsS78FlRd85w2Fmsd6AkuLipDihPflKC0p3PN5i8II7+uHxo+CtkLiJDfmS5A==", + "integrity": "sha1-XbxjnZYerH8an7wacUbsEvKST78=", "dev": true }, "nice-color-palettes": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/nice-color-palettes/-/nice-color-palettes-1.0.1.tgz", - "integrity": "sha512-aHEFYKuGiaga8LqMi0Ttarqzn4tKS7BaIE2MeD9SDjv6yVc7DMIu/Eax4RvUgwR7vS0hXAUEIUx9P0/54O1W0g==", + "integrity": "sha1-h16gHchu+uf1leBmqLJmDnIGBT4=", "dev": true, "requires": { "map-limit": "0.0.1", @@ -12428,7 +12328,7 @@ "quad-indices": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/quad-indices/-/quad-indices-2.0.1.tgz", - "integrity": "sha512-6jtmCsEbGAh5npThXrBaubbTjPcF0rMbn57XCJVI7LkW8PUT56V+uIrRCCWCn85PSgJC9v8Pm5tnJDwmOBewvA==", + "integrity": "sha1-ppQdiaE9Y+7WwdSlpiGgRjYXqBQ=", "dev": true, "requires": { "an-array": "^1.0.0", @@ -13129,9 +13029,9 @@ "dev": true }, "simple-get": { - "version": "2.8.2", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.2.tgz", - "integrity": "sha512-Ijd/rV5o+mSBBs4F/x9oDPtTx9Zb6X9brmnXvMW4J7IR15ngi9q5xxqWBKU744jTZiaXtxaPL7uHG6vtN8kUkw==", + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.1.tgz", + "integrity": "sha512-lSSHRSw3mQNUGPAYRqo7xy9dhKmxFXIjLjp4KHpf99GEH2VH7C3AM+Qfx6du6jhfUi6Vm7XnbEVEf7Wb6N8jRw==", "dev": true, "requires": { "decompress-response": "^3.3.0", @@ -13752,9 +13652,9 @@ "dev": true }, "super-three": { - "version": "0.137.0", - "resolved": "https://registry.npmjs.org/super-three/-/super-three-0.137.0.tgz", - "integrity": "sha512-8jM8DiYiXQoalUoeFRxKWbW6KFQo3GFwgw+3vE2y6SJU/einw+JvuvgK+WhbIYRfz4LQV68nyOQ2eEZqAuouGw==", + "version": "0.123.1", + "resolved": "https://registry.npmjs.org/super-three/-/super-three-0.123.1.tgz", + "integrity": "sha512-5P71owlReO9HmKG5OxSSb1qKBuEWVhvGIb59gZkIoqRX5WgmBfZPo7x0OZOYEd7r9nG87cRv+OyeHJCO1Qh0CA==", "dev": true }, "supports-color": { @@ -13809,15 +13709,15 @@ "dev": true }, "three": { - "version": "0.125.2", - "resolved": "https://registry.npmjs.org/three/-/three-0.125.2.tgz", - "integrity": "sha512-7rIRO23jVKWcAPFdW/HREU2NZMGWPBZ4XwEMt0Ak0jwLUKVJhcKM55eCBWyGZq/KiQbeo1IeuAoo/9l2dzhTXA==" + "version": "0.145.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.145.0.tgz", + "integrity": "sha512-EKoHQEtEJ4CB6b2BGMBgLZrfwLjXcSUfoI/MiIXUuRpeYsfK5aPWbYhdtIVWOH+x6X0TouldHKHBuc/LAiFzAw==" }, "three-bmfont-text": { - "version": "git+ssh://git@github.com/dmarcos/three-bmfont-text.git#21d017046216e318362c48abd1a48bddfb6e0733", - "integrity": "sha512-lIMa1n+QKNU1f/LZgtS1oUGpoop3MuVXrUr5ybZOUR3+Jk//zjqScnQpHml6MWyvZzL8A5/1Hd8Tsqd3M1kudA==", + "version": "git+ssh://git@github.com/dmarcos/three-bmfont-text.git#1babdf8507c731a18f8af3b807292e2b9740955e", + "integrity": "sha512-1ACVhQynOX5fUHx9WY0leDApaQ8fa12wdU+z1iVRCiMDq5bZGw67kqUgEBrbK1BQ5awTZL3+VG3LX5xg+ty89Q==", "dev": true, - "from": "three-bmfont-text@github:dmarcos/three-bmfont-text#21d017046216e318362c48abd1a48bddfb6e0733", + "from": "three-bmfont-text@github:dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e", "requires": { "array-shuffle": "^1.0.1", "inherits": "^2.0.1", @@ -13869,7 +13769,7 @@ "timed-out": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", - "integrity": "sha512-G7r3AhovYtr5YKOWQkta8RKAPb+J9IsO4uVmzjl8AZwfhs8UcUwTiD6gcJYSgOtzyjvQKrKYn41syHbUWMkafA==", + "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", "dev": true }, "timers-browserify": { @@ -14155,7 +14055,7 @@ "url-set-query": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/url-set-query/-/url-set-query-1.0.0.tgz", - "integrity": "sha512-3AChu4NiXquPfeckE5R5cGdiHCMWJx1dwCWOmWIL4KHAziJNOFIYJlpGFeKDvwLPHovZRCxK3cYlwzqI9Vp+Gg==", + "integrity": "sha1-AW6M/Xwg7gXK/neV6JK9BwL6ozk=", "dev": true }, "url-trim": { @@ -14297,7 +14197,7 @@ "word-wrapper": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/word-wrapper/-/word-wrapper-1.0.7.tgz", - "integrity": "sha512-VOPBFCm9b6FyYKQYfn9AVn2dQvdR/YOVFV6IBRA1TBMJWKffvhEX1af6FMGrttILs2Q9ikCRhLqkbY2weW6dOQ==", + "integrity": "sha1-HxSv6/Zt/fD+9V79NxhO+9CMKLY=", "dev": true }, "wordwrap": { diff --git a/package.json b/package.json index 81b0255..4ce651e 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "aframe": ">=0.5.0" }, "devDependencies": { - "aframe": "^1.2.0", + "aframe": "^1.1.0", "browserify": "^16.5.1", "browserify-css": "^0.15.0", "browserify-shim": "^3.8.14", @@ -71,7 +71,7 @@ "replace": "^1.2.0", "sinon": "^2.4.1", "sinon-chai": "^2.14.0", - "three": "^0.125.0", + "three": ">=0.125.0", "uglify-es": "^3.3.9" } } From f8d4b751aa55314390cb0ff6e0827495cd05df94 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sun, 2 Oct 2022 11:57:15 +0100 Subject: [PATCH 19/28] Don't allow a-frame past 1.1.0 in test environment as it causes test failures. --- package-lock.json | 66 +++++++++++++++++++++++------------------------ package.json | 2 +- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/package-lock.json b/package-lock.json index ee5e660..675991b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,7 @@ "webworkify": "^1.4.0" }, "devDependencies": { - "aframe": "^1.1.0", + "aframe": "~1.1.0", "browserify": "^16.5.1", "browserify-css": "^0.15.0", "browserify-shim": "^3.8.14", @@ -189,7 +189,7 @@ "node_modules/an-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/an-array/-/an-array-1.0.0.tgz", - "integrity": "sha1-wSWlu4JXd4419LT2qpx9D6nkJmU=", + "integrity": "sha512-M175GYI7RmsYu24Ok383yZQa3eveDfNnmhTe3OQ3bm70bEovz2gWenH+ST/n32M8lrwLWk74hcPds5CDRPe2wg==", "dev": true }, "node_modules/ansi-colors": { @@ -286,7 +286,7 @@ "node_modules/array-shuffle": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/array-shuffle/-/array-shuffle-1.0.1.tgz", - "integrity": "sha1-fqSIKjVrS8pfVF4LblLq9tlxVXo=", + "integrity": "sha512-PBqgo1Y2XWSksBzq3GFPEb798ZrW2snAcmr4drbVeF/6MT/5aBlkGJEvu5A/CzXHf4EjbHOj/ZowatjlIiVidA==", "dev": true, "engines": { "node": ">=0.10.0" @@ -310,7 +310,7 @@ "node_modules/as-number": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/as-number/-/as-number-1.0.0.tgz", - "integrity": "sha1-rLJ+NPj52KsNqeN287iVmGD4CmY=", + "integrity": "sha512-HkI/zLo2AbSRO4fqVkmyf3hms0bJDs3iboHqTrNuwTiCRvdYXM7HFhfhB6Dk51anV2LM/IMB83mtK9mHw4FlAg==", "dev": true }, "node_modules/asn1.js": { @@ -991,7 +991,7 @@ "node_modules/buffer-to-arraybuffer": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/buffer-to-arraybuffer/-/buffer-to-arraybuffer-0.0.5.tgz", - "integrity": "sha1-YGSkD6dutDxyOrqe+PbhIW0QURo=", + "integrity": "sha512-3dthu5CYiVB1DEJp61FtApNnNndTckcqe4pFcLdvHtrpG+kcyekCJKg4MRiDcFW7A6AODnXB9U4dwQiCW5kzJQ==", "dev": true }, "node_modules/buffer-xor": { @@ -1609,7 +1609,7 @@ "node_modules/decompress-response": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "integrity": "sha512-BzRPQuY1ip+qDonAOz42gRm/pg9F768C+npV/4JOsxRC2sq+Rlk+Q4ZCAsOhnIaMrgarILY+RMUIvMmmX1qAEA==", "dev": true, "dependencies": { "mimic-response": "^1.0.0" @@ -1884,7 +1884,7 @@ "node_modules/dtype": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/dtype/-/dtype-2.0.0.tgz", - "integrity": "sha1-zQUjI84GFETs0uj1dI9popvihDQ=", + "integrity": "sha512-s2YVcLKdFGS0hpFqJaTwscsyt0E8nNFdmo73Ocd81xNPj4URI4rj6D60A+vFMIw7BXWlb4yRkEwfBqcZzPGiZg==", "dev": true, "engines": { "node": ">= 0.8.0" @@ -4105,7 +4105,7 @@ "node_modules/layout-bmfont-text": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/layout-bmfont-text/-/layout-bmfont-text-1.3.4.tgz", - "integrity": "sha1-8g8sVGR3T0jabOipl/vObUaUW4E=", + "integrity": "sha512-mceomHZ8W7pSKQhTdLvOe1Im4n37u8xa5Gr0J3KPCHRMO/9o7+goWIOzZcUUd+Xgzy3+22bvoIQ0OaN3LRtgaw==", "dev": true, "dependencies": { "as-number": "^1.0.0", @@ -4673,13 +4673,13 @@ "node_modules/new-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/new-array/-/new-array-1.0.0.tgz", - "integrity": "sha1-XbxjnZYerH8an7wacUbsEvKST78=", + "integrity": "sha512-K5AyFYbuHZ4e/ti52y7k18q8UHsS78FlRd85w2Fmsd6AkuLipDihPflKC0p3PN5i8II7+uHxo+CtkLiJDfmS5A==", "dev": true }, "node_modules/nice-color-palettes": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/nice-color-palettes/-/nice-color-palettes-1.0.1.tgz", - "integrity": "sha1-h16gHchu+uf1leBmqLJmDnIGBT4=", + "integrity": "sha512-aHEFYKuGiaga8LqMi0Ttarqzn4tKS7BaIE2MeD9SDjv6yVc7DMIu/Eax4RvUgwR7vS0hXAUEIUx9P0/54O1W0g==", "dev": true, "dependencies": { "map-limit": "0.0.1", @@ -5400,7 +5400,7 @@ "node_modules/quad-indices": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/quad-indices/-/quad-indices-2.0.1.tgz", - "integrity": "sha1-ppQdiaE9Y+7WwdSlpiGgRjYXqBQ=", + "integrity": "sha512-6jtmCsEbGAh5npThXrBaubbTjPcF0rMbn57XCJVI7LkW8PUT56V+uIrRCCWCn85PSgJC9v8Pm5tnJDwmOBewvA==", "dev": true, "dependencies": { "an-array": "^1.0.0", @@ -6235,9 +6235,9 @@ "dev": true }, "node_modules/simple-get": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.1.tgz", - "integrity": "sha512-lSSHRSw3mQNUGPAYRqo7xy9dhKmxFXIjLjp4KHpf99GEH2VH7C3AM+Qfx6du6jhfUi6Vm7XnbEVEf7Wb6N8jRw==", + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.2.tgz", + "integrity": "sha512-Ijd/rV5o+mSBBs4F/x9oDPtTx9Zb6X9brmnXvMW4J7IR15ngi9q5xxqWBKU744jTZiaXtxaPL7uHG6vtN8kUkw==", "dev": true, "dependencies": { "decompress-response": "^3.3.0", @@ -7081,7 +7081,7 @@ "node_modules/timed-out": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", - "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", + "integrity": "sha512-G7r3AhovYtr5YKOWQkta8RKAPb+J9IsO4uVmzjl8AZwfhs8UcUwTiD6gcJYSgOtzyjvQKrKYn41syHbUWMkafA==", "dev": true, "engines": { "node": ">=0.10.0" @@ -7422,7 +7422,7 @@ "node_modules/url-set-query": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/url-set-query/-/url-set-query-1.0.0.tgz", - "integrity": "sha1-AW6M/Xwg7gXK/neV6JK9BwL6ozk=", + "integrity": "sha512-3AChu4NiXquPfeckE5R5cGdiHCMWJx1dwCWOmWIL4KHAziJNOFIYJlpGFeKDvwLPHovZRCxK3cYlwzqI9Vp+Gg==", "dev": true }, "node_modules/url-trim": { @@ -7586,7 +7586,7 @@ "node_modules/word-wrapper": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/word-wrapper/-/word-wrapper-1.0.7.tgz", - "integrity": "sha1-HxSv6/Zt/fD+9V79NxhO+9CMKLY=", + "integrity": "sha512-VOPBFCm9b6FyYKQYfn9AVn2dQvdR/YOVFV6IBRA1TBMJWKffvhEX1af6FMGrttILs2Q9ikCRhLqkbY2weW6dOQ==", "dev": true }, "node_modules/wordwrap": { @@ -7972,7 +7972,7 @@ "an-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/an-array/-/an-array-1.0.0.tgz", - "integrity": "sha1-wSWlu4JXd4419LT2qpx9D6nkJmU=", + "integrity": "sha512-M175GYI7RmsYu24Ok383yZQa3eveDfNnmhTe3OQ3bm70bEovz2gWenH+ST/n32M8lrwLWk74hcPds5CDRPe2wg==", "dev": true }, "ansi-colors": { @@ -8050,7 +8050,7 @@ "array-shuffle": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/array-shuffle/-/array-shuffle-1.0.1.tgz", - "integrity": "sha1-fqSIKjVrS8pfVF4LblLq9tlxVXo=", + "integrity": "sha512-PBqgo1Y2XWSksBzq3GFPEb798ZrW2snAcmr4drbVeF/6MT/5aBlkGJEvu5A/CzXHf4EjbHOj/ZowatjlIiVidA==", "dev": true }, "array-unique": { @@ -8068,7 +8068,7 @@ "as-number": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/as-number/-/as-number-1.0.0.tgz", - "integrity": "sha1-rLJ+NPj52KsNqeN287iVmGD4CmY=", + "integrity": "sha512-HkI/zLo2AbSRO4fqVkmyf3hms0bJDs3iboHqTrNuwTiCRvdYXM7HFhfhB6Dk51anV2LM/IMB83mtK9mHw4FlAg==", "dev": true }, "asn1.js": { @@ -8693,7 +8693,7 @@ "buffer-to-arraybuffer": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/buffer-to-arraybuffer/-/buffer-to-arraybuffer-0.0.5.tgz", - "integrity": "sha1-YGSkD6dutDxyOrqe+PbhIW0QURo=", + "integrity": "sha512-3dthu5CYiVB1DEJp61FtApNnNndTckcqe4pFcLdvHtrpG+kcyekCJKg4MRiDcFW7A6AODnXB9U4dwQiCW5kzJQ==", "dev": true }, "buffer-xor": { @@ -9224,7 +9224,7 @@ "decompress-response": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "integrity": "sha512-BzRPQuY1ip+qDonAOz42gRm/pg9F768C+npV/4JOsxRC2sq+Rlk+Q4ZCAsOhnIaMrgarILY+RMUIvMmmX1qAEA==", "dev": true, "requires": { "mimic-response": "^1.0.0" @@ -9443,7 +9443,7 @@ "dtype": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/dtype/-/dtype-2.0.0.tgz", - "integrity": "sha1-zQUjI84GFETs0uj1dI9popvihDQ=", + "integrity": "sha512-s2YVcLKdFGS0hpFqJaTwscsyt0E8nNFdmo73Ocd81xNPj4URI4rj6D60A+vFMIw7BXWlb4yRkEwfBqcZzPGiZg==", "dev": true }, "duplexer2": { @@ -11247,7 +11247,7 @@ "layout-bmfont-text": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/layout-bmfont-text/-/layout-bmfont-text-1.3.4.tgz", - "integrity": "sha1-8g8sVGR3T0jabOipl/vObUaUW4E=", + "integrity": "sha512-mceomHZ8W7pSKQhTdLvOe1Im4n37u8xa5Gr0J3KPCHRMO/9o7+goWIOzZcUUd+Xgzy3+22bvoIQ0OaN3LRtgaw==", "dev": true, "requires": { "as-number": "^1.0.0", @@ -11735,13 +11735,13 @@ "new-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/new-array/-/new-array-1.0.0.tgz", - "integrity": "sha1-XbxjnZYerH8an7wacUbsEvKST78=", + "integrity": "sha512-K5AyFYbuHZ4e/ti52y7k18q8UHsS78FlRd85w2Fmsd6AkuLipDihPflKC0p3PN5i8II7+uHxo+CtkLiJDfmS5A==", "dev": true }, "nice-color-palettes": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/nice-color-palettes/-/nice-color-palettes-1.0.1.tgz", - "integrity": "sha1-h16gHchu+uf1leBmqLJmDnIGBT4=", + "integrity": "sha512-aHEFYKuGiaga8LqMi0Ttarqzn4tKS7BaIE2MeD9SDjv6yVc7DMIu/Eax4RvUgwR7vS0hXAUEIUx9P0/54O1W0g==", "dev": true, "requires": { "map-limit": "0.0.1", @@ -12328,7 +12328,7 @@ "quad-indices": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/quad-indices/-/quad-indices-2.0.1.tgz", - "integrity": "sha1-ppQdiaE9Y+7WwdSlpiGgRjYXqBQ=", + "integrity": "sha512-6jtmCsEbGAh5npThXrBaubbTjPcF0rMbn57XCJVI7LkW8PUT56V+uIrRCCWCn85PSgJC9v8Pm5tnJDwmOBewvA==", "dev": true, "requires": { "an-array": "^1.0.0", @@ -13029,9 +13029,9 @@ "dev": true }, "simple-get": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.1.tgz", - "integrity": "sha512-lSSHRSw3mQNUGPAYRqo7xy9dhKmxFXIjLjp4KHpf99GEH2VH7C3AM+Qfx6du6jhfUi6Vm7XnbEVEf7Wb6N8jRw==", + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.2.tgz", + "integrity": "sha512-Ijd/rV5o+mSBBs4F/x9oDPtTx9Zb6X9brmnXvMW4J7IR15ngi9q5xxqWBKU744jTZiaXtxaPL7uHG6vtN8kUkw==", "dev": true, "requires": { "decompress-response": "^3.3.0", @@ -13769,7 +13769,7 @@ "timed-out": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", - "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", + "integrity": "sha512-G7r3AhovYtr5YKOWQkta8RKAPb+J9IsO4uVmzjl8AZwfhs8UcUwTiD6gcJYSgOtzyjvQKrKYn41syHbUWMkafA==", "dev": true }, "timers-browserify": { @@ -14055,7 +14055,7 @@ "url-set-query": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/url-set-query/-/url-set-query-1.0.0.tgz", - "integrity": "sha1-AW6M/Xwg7gXK/neV6JK9BwL6ozk=", + "integrity": "sha512-3AChu4NiXquPfeckE5R5cGdiHCMWJx1dwCWOmWIL4KHAziJNOFIYJlpGFeKDvwLPHovZRCxK3cYlwzqI9Vp+Gg==", "dev": true }, "url-trim": { @@ -14197,7 +14197,7 @@ "word-wrapper": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/word-wrapper/-/word-wrapper-1.0.7.tgz", - "integrity": "sha1-HxSv6/Zt/fD+9V79NxhO+9CMKLY=", + "integrity": "sha512-VOPBFCm9b6FyYKQYfn9AVn2dQvdR/YOVFV6IBRA1TBMJWKffvhEX1af6FMGrttILs2Q9ikCRhLqkbY2weW6dOQ==", "dev": true }, "wordwrap": { diff --git a/package.json b/package.json index 4ce651e..fcfd996 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "aframe": ">=0.5.0" }, "devDependencies": { - "aframe": "^1.1.0", + "aframe": "~1.1.0", "browserify": "^16.5.1", "browserify-css": "^0.15.0", "browserify-shim": "^3.8.14", From 96137c2654573661a20b49e8e0911c527c51c788 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sun, 2 Oct 2022 11:58:32 +0100 Subject: [PATCH 20/28] invert() is correct after THREE r125 --- dist/aframe-physics-system.js | 6 +++--- dist/aframe-physics-system.min.js | 2 +- src/components/ammo-constraint.js | 2 +- src/components/body/ammo-body.js | 2 +- src/components/body/body.js | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index 679169e..a2bec6e 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -15821,7 +15821,7 @@ module.exports = AFRAME.registerComponent("ammo-constraint", { const bodyTransform = body .getCenterOfMassTransform() - .inverse() + .invert() .op_mul(targetBody.getWorldTransform()); const targetTransform = new Ammo.btTransform(); targetTransform.setIdentity(); @@ -16347,7 +16347,7 @@ let AmmoBody = { } else { q1.set(quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w()); parentEl.object3D.getWorldQuaternion(q2); - q1.multiply(q2.inverse()); + q1.multiply(q2.invert()); el.object3D.quaternion.copy(q1); v.set(position.x(), position.y(), position.z()); @@ -16758,7 +16758,7 @@ var Body = { } else { q1.copy(body.quaternion); parentEl.object3D.getWorldQuaternion(q2); - q1.premultiply(q2.inverse()); + q1.premultiply(q2.invert()); el.object3D.quaternion.copy(q1); v.copy(body.position); diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index a31aa4b..5bd2d10 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file diff --git a/src/components/ammo-constraint.js b/src/components/ammo-constraint.js index c9e7ecc..5ac1a94 100644 --- a/src/components/ammo-constraint.js +++ b/src/components/ammo-constraint.js @@ -69,7 +69,7 @@ module.exports = AFRAME.registerComponent("ammo-constraint", { const bodyTransform = body .getCenterOfMassTransform() - .inverse() + .invert() .op_mul(targetBody.getWorldTransform()); const targetTransform = new Ammo.btTransform(); targetTransform.setIdentity(); diff --git a/src/components/body/ammo-body.js b/src/components/body/ammo-body.js index 0eb561f..958b417 100644 --- a/src/components/body/ammo-body.js +++ b/src/components/body/ammo-body.js @@ -436,7 +436,7 @@ let AmmoBody = { } else { q1.set(quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w()); parentEl.object3D.getWorldQuaternion(q2); - q1.multiply(q2.inverse()); + q1.multiply(q2.invert()); el.object3D.quaternion.copy(q1); v.set(position.x(), position.y(), position.z()); diff --git a/src/components/body/body.js b/src/components/body/body.js index 945bec4..50b0da6 100644 --- a/src/components/body/body.js +++ b/src/components/body/body.js @@ -336,7 +336,7 @@ var Body = { } else { q1.copy(body.quaternion); parentEl.object3D.getWorldQuaternion(q2); - q1.premultiply(q2.inverse()); + q1.premultiply(q2.invert()); el.object3D.quaternion.copy(q1); v.copy(body.position); From 0421e33a69e886f4662dfba19a3a51e9eb545145 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Sun, 2 Oct 2022 12:18:10 +0100 Subject: [PATCH 21/28] Replace rawgit URLs with jsdelivr --- examples/compound.html | 2 +- examples/constraints-ammo.html | 2 +- examples/constraints.html | 4 ++-- examples/materials.html | 2 +- examples/stress.html | 2 +- examples/sweeper.html | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/compound.html b/examples/compound.html index a25491e..9a6ea6e 100644 --- a/examples/compound.html +++ b/examples/compound.html @@ -6,7 +6,7 @@ Examples • Compound - + diff --git a/examples/constraints-ammo.html b/examples/constraints-ammo.html index fc83bb3..9ab3c23 100644 --- a/examples/constraints-ammo.html +++ b/examples/constraints-ammo.html @@ -8,7 +8,7 @@ - + diff --git a/examples/constraints.html b/examples/constraints.html index 4d457de..18270d1 100644 --- a/examples/constraints.html +++ b/examples/constraints.html @@ -7,8 +7,8 @@ Examples • Constraints - - + + diff --git a/examples/materials.html b/examples/materials.html index 05345d8..53f387e 100644 --- a/examples/materials.html +++ b/examples/materials.html @@ -6,7 +6,7 @@ Examples • Materials - + diff --git a/examples/stress.html b/examples/stress.html index 1841718..d119056 100644 --- a/examples/stress.html +++ b/examples/stress.html @@ -6,7 +6,7 @@ Examples • Stress Test - + diff --git a/examples/sweeper.html b/examples/sweeper.html index 2a40b08..5b0d106 100644 --- a/examples/sweeper.html +++ b/examples/sweeper.html @@ -6,7 +6,7 @@ Examples • Sweeper - + From 597682a3ca37b8c63b80d0b9e72b8e367da0e538 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Thu, 6 Oct 2022 15:54:04 +0100 Subject: [PATCH 22/28] Revert change that shouldn't be on this branch --- dist/aframe-physics-system.js | 1332 +---------------------------- dist/aframe-physics-system.min.js | 2 +- src/components/body/ammo-body.js | 7 +- 3 files changed, 6 insertions(+), 1335 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index a2bec6e..fa47235 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -14339,1330 +14339,7 @@ const _computeBounds = (function() { },{}],6:[function(require,module,exports){ (function (global){ -var cannonEs = require('cannon-es'); -var three = (typeof window !== "undefined" ? window['THREE'] : typeof global !== "undefined" ? global['THREE'] : null); - -/** - * Ported from: https://github.com/maurizzzio/quickhull3d/ by Mauricio Poppe (https://github.com/maurizzzio) - */ - -var ConvexHull = function () { - var Visible = 0; - var Deleted = 1; - var v1 = new three.Vector3(); - - function ConvexHull() { - this.tolerance = -1; - this.faces = []; // the generated faces of the convex hull - - this.newFaces = []; // this array holds the faces that are generated within a single iteration - // the vertex lists work as follows: - // - // let 'a' and 'b' be 'Face' instances - // let 'v' be points wrapped as instance of 'Vertex' - // - // [v, v, ..., v, v, v, ...] - // ^ ^ - // | | - // a.outside b.outside - // - - this.assigned = new VertexList(); - this.unassigned = new VertexList(); - this.vertices = []; // vertices of the hull (internal representation of given geometry data) - } - - Object.assign(ConvexHull.prototype, { - setFromPoints: function (points) { - if (Array.isArray(points) !== true) { - console.error('THREE.ConvexHull: Points parameter is not an array.'); - } - - if (points.length < 4) { - console.error('THREE.ConvexHull: The algorithm needs at least four points.'); - } - - this.makeEmpty(); - - for (var i = 0, l = points.length; i < l; i++) { - this.vertices.push(new VertexNode(points[i])); - } - - this.compute(); - return this; - }, - setFromObject: function (object) { - var points = []; - object.updateMatrixWorld(true); - object.traverse(function (node) { - var i, l, point; - var geometry = node.geometry; - if (geometry === undefined) return; - - if (geometry.isGeometry) { - geometry = geometry.toBufferGeometry ? geometry.toBufferGeometry() : new three.BufferGeometry().fromGeometry(geometry); - } - - if (geometry.isBufferGeometry) { - var attribute = geometry.attributes.position; - - if (attribute !== undefined) { - for (i = 0, l = attribute.count; i < l; i++) { - point = new three.Vector3(); - point.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld); - points.push(point); - } - } - } - }); - return this.setFromPoints(points); - }, - containsPoint: function (point) { - var faces = this.faces; - - for (var i = 0, l = faces.length; i < l; i++) { - var face = faces[i]; // compute signed distance and check on what half space the point lies - - if (face.distanceToPoint(point) > this.tolerance) return false; - } - - return true; - }, - intersectRay: function (ray, target) { - // based on "Fast Ray-Convex Polyhedron Intersection" by Eric Haines, GRAPHICS GEMS II - var faces = this.faces; - var tNear = -Infinity; - var tFar = Infinity; - - for (var i = 0, l = faces.length; i < l; i++) { - var face = faces[i]; // interpret faces as planes for the further computation - - var vN = face.distanceToPoint(ray.origin); - var vD = face.normal.dot(ray.direction); // if the origin is on the positive side of a plane (so the plane can "see" the origin) and - // the ray is turned away or parallel to the plane, there is no intersection - - if (vN > 0 && vD >= 0) return null; // compute the distance from the ray’s origin to the intersection with the plane - - var t = vD !== 0 ? -vN / vD : 0; // only proceed if the distance is positive. a negative distance means the intersection point - // lies "behind" the origin - - if (t <= 0) continue; // now categorized plane as front-facing or back-facing - - if (vD > 0) { - // plane faces away from the ray, so this plane is a back-face - tFar = Math.min(t, tFar); - } else { - // front-face - tNear = Math.max(t, tNear); - } - - if (tNear > tFar) { - // if tNear ever is greater than tFar, the ray must miss the convex hull - return null; - } - } // evaluate intersection point - // always try tNear first since its the closer intersection point - - - if (tNear !== -Infinity) { - ray.at(tNear, target); - } else { - ray.at(tFar, target); - } - - return target; - }, - intersectsRay: function (ray) { - return this.intersectRay(ray, v1) !== null; - }, - makeEmpty: function () { - this.faces = []; - this.vertices = []; - return this; - }, - // Adds a vertex to the 'assigned' list of vertices and assigns it to the given face - addVertexToFace: function (vertex, face) { - vertex.face = face; - - if (face.outside === null) { - this.assigned.append(vertex); - } else { - this.assigned.insertBefore(face.outside, vertex); - } - - face.outside = vertex; - return this; - }, - // Removes a vertex from the 'assigned' list of vertices and from the given face - removeVertexFromFace: function (vertex, face) { - if (vertex === face.outside) { - // fix face.outside link - if (vertex.next !== null && vertex.next.face === face) { - // face has at least 2 outside vertices, move the 'outside' reference - face.outside = vertex.next; - } else { - // vertex was the only outside vertex that face had - face.outside = null; - } - } - - this.assigned.remove(vertex); - return this; - }, - // Removes all the visible vertices that a given face is able to see which are stored in the 'assigned' vertext list - removeAllVerticesFromFace: function (face) { - if (face.outside !== null) { - // reference to the first and last vertex of this face - var start = face.outside; - var end = face.outside; - - while (end.next !== null && end.next.face === face) { - end = end.next; - } - - this.assigned.removeSubList(start, end); // fix references - - start.prev = end.next = null; - face.outside = null; - return start; - } - }, - // Removes all the visible vertices that 'face' is able to see - deleteFaceVertices: function (face, absorbingFace) { - var faceVertices = this.removeAllVerticesFromFace(face); - - if (faceVertices !== undefined) { - if (absorbingFace === undefined) { - // mark the vertices to be reassigned to some other face - this.unassigned.appendChain(faceVertices); - } else { - // if there's an absorbing face try to assign as many vertices as possible to it - var vertex = faceVertices; - - do { - // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference - // will be changed by upcoming method calls - var nextVertex = vertex.next; - var distance = absorbingFace.distanceToPoint(vertex.point); // check if 'vertex' is able to see 'absorbingFace' - - if (distance > this.tolerance) { - this.addVertexToFace(vertex, absorbingFace); - } else { - this.unassigned.append(vertex); - } // now assign next vertex - - - vertex = nextVertex; - } while (vertex !== null); - } - } - - return this; - }, - // Reassigns as many vertices as possible from the unassigned list to the new faces - resolveUnassignedPoints: function (newFaces) { - if (this.unassigned.isEmpty() === false) { - var vertex = this.unassigned.first(); - - do { - // buffer 'next' reference, see .deleteFaceVertices() - var nextVertex = vertex.next; - var maxDistance = this.tolerance; - var maxFace = null; - - for (var i = 0; i < newFaces.length; i++) { - var face = newFaces[i]; - - if (face.mark === Visible) { - var distance = face.distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - maxFace = face; - } - - if (maxDistance > 1000 * this.tolerance) break; - } - } // 'maxFace' can be null e.g. if there are identical vertices - - - if (maxFace !== null) { - this.addVertexToFace(vertex, maxFace); - } - - vertex = nextVertex; - } while (vertex !== null); - } - - return this; - }, - // Computes the extremes of a simplex which will be the initial hull - computeExtremes: function () { - var min = new three.Vector3(); - var max = new three.Vector3(); - var minVertices = []; - var maxVertices = []; - var i, l, j; // initially assume that the first vertex is the min/max - - for (i = 0; i < 3; i++) { - minVertices[i] = maxVertices[i] = this.vertices[0]; - } - - min.copy(this.vertices[0].point); - max.copy(this.vertices[0].point); // compute the min/max vertex on all six directions - - for (i = 0, l = this.vertices.length; i < l; i++) { - var vertex = this.vertices[i]; - var point = vertex.point; // update the min coordinates - - for (j = 0; j < 3; j++) { - if (point.getComponent(j) < min.getComponent(j)) { - min.setComponent(j, point.getComponent(j)); - minVertices[j] = vertex; - } - } // update the max coordinates - - - for (j = 0; j < 3; j++) { - if (point.getComponent(j) > max.getComponent(j)) { - max.setComponent(j, point.getComponent(j)); - maxVertices[j] = vertex; - } - } - } // use min/max vectors to compute an optimal epsilon - - - this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max.x)) + Math.max(Math.abs(min.y), Math.abs(max.y)) + Math.max(Math.abs(min.z), Math.abs(max.z))); - return { - min: minVertices, - max: maxVertices - }; - }, - // Computes the initial simplex assigning to its faces all the points - // that are candidates to form part of the hull - computeInitialHull: function () { - var line3, plane, closestPoint; - return function computeInitialHull() { - if (line3 === undefined) { - line3 = new three.Line3(); - plane = new three.Plane(); - closestPoint = new three.Vector3(); - } - - var vertex, - vertices = this.vertices; - var extremes = this.computeExtremes(); - var min = extremes.min; - var max = extremes.max; - var v0, v1, v2, v3; - var i, l, j; // 1. Find the two vertices 'v0' and 'v1' with the greatest 1d separation - // (max.x - min.x) - // (max.y - min.y) - // (max.z - min.z) - - var distance, - maxDistance = 0; - var index = 0; - - for (i = 0; i < 3; i++) { - distance = max[i].point.getComponent(i) - min[i].point.getComponent(i); - - if (distance > maxDistance) { - maxDistance = distance; - index = i; - } - } - - v0 = min[index]; - v1 = max[index]; // 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1' - - maxDistance = 0; - line3.set(v0.point, v1.point); - - for (i = 0, l = this.vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1) { - line3.closestPointToPoint(vertex.point, true, closestPoint); - distance = closestPoint.distanceToSquared(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - v2 = vertex; - } - } - } // 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2' - - - maxDistance = -1; - plane.setFromCoplanarPoints(v0.point, v1.point, v2.point); - - for (i = 0, l = this.vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1 && vertex !== v2) { - distance = Math.abs(plane.distanceToPoint(vertex.point)); - - if (distance > maxDistance) { - maxDistance = distance; - v3 = vertex; - } - } - } - - var faces = []; - - if (plane.distanceToPoint(v3.point) < 0) { - // the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron - faces.push(Face.create(v0, v1, v2), Face.create(v3, v1, v0), Face.create(v3, v2, v1), Face.create(v3, v0, v2)); // set the twin edge - - for (i = 0; i < 3; i++) { - j = (i + 1) % 3; // join face[ i ] i > 0, with the first face - - faces[i + 1].getEdge(2).setTwin(faces[0].getEdge(j)); // join face[ i ] with face[ i + 1 ], 1 <= i <= 3 - - faces[i + 1].getEdge(1).setTwin(faces[j + 1].getEdge(0)); - } - } else { - // the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron - faces.push(Face.create(v0, v2, v1), Face.create(v3, v0, v1), Face.create(v3, v1, v2), Face.create(v3, v2, v0)); // set the twin edge - - for (i = 0; i < 3; i++) { - j = (i + 1) % 3; // join face[ i ] i > 0, with the first face - - faces[i + 1].getEdge(2).setTwin(faces[0].getEdge((3 - i) % 3)); // join face[ i ] with face[ i + 1 ] - - faces[i + 1].getEdge(0).setTwin(faces[j + 1].getEdge(1)); - } - } // the initial hull is the tetrahedron - - - for (i = 0; i < 4; i++) { - this.faces.push(faces[i]); - } // initial assignment of vertices to the faces of the tetrahedron - - - for (i = 0, l = vertices.length; i < l; i++) { - vertex = vertices[i]; - - if (vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3) { - maxDistance = this.tolerance; - var maxFace = null; - - for (j = 0; j < 4; j++) { - distance = this.faces[j].distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - maxFace = this.faces[j]; - } - } - - if (maxFace !== null) { - this.addVertexToFace(vertex, maxFace); - } - } - } - - return this; - }; - }(), - // Removes inactive faces - reindexFaces: function () { - var activeFaces = []; - - for (var i = 0; i < this.faces.length; i++) { - var face = this.faces[i]; - - if (face.mark === Visible) { - activeFaces.push(face); - } - } - - this.faces = activeFaces; - return this; - }, - // Finds the next vertex to create faces with the current hull - nextVertexToAdd: function () { - // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined' - if (this.assigned.isEmpty() === false) { - var eyeVertex, - maxDistance = 0; // grap the first available face and start with the first visible vertex of that face - - var eyeFace = this.assigned.first().face; - var vertex = eyeFace.outside; // now calculate the farthest vertex that face can see - - do { - var distance = eyeFace.distanceToPoint(vertex.point); - - if (distance > maxDistance) { - maxDistance = distance; - eyeVertex = vertex; - } - - vertex = vertex.next; - } while (vertex !== null && vertex.face === eyeFace); - - return eyeVertex; - } - }, - // Computes a chain of half edges in CCW order called the 'horizon'. - // For an edge to be part of the horizon it must join a face that can see - // 'eyePoint' and a face that cannot see 'eyePoint'. - computeHorizon: function (eyePoint, crossEdge, face, horizon) { - // moves face's vertices to the 'unassigned' vertex list - this.deleteFaceVertices(face); - face.mark = Deleted; - var edge; - - if (crossEdge === null) { - edge = crossEdge = face.getEdge(0); - } else { - // start from the next edge since 'crossEdge' was already analyzed - // (actually 'crossEdge.twin' was the edge who called this method recursively) - edge = crossEdge.next; - } - - do { - var twinEdge = edge.twin; - var oppositeFace = twinEdge.face; - - if (oppositeFace.mark === Visible) { - if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) { - // the opposite face can see the vertex, so proceed with next edge - this.computeHorizon(eyePoint, twinEdge, oppositeFace, horizon); - } else { - // the opposite face can't see the vertex, so this edge is part of the horizon - horizon.push(edge); - } - } - - edge = edge.next; - } while (edge !== crossEdge); - - return this; - }, - // Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head' in CCW order - addAdjoiningFace: function (eyeVertex, horizonEdge) { - // all the half edges are created in ccw order thus the face is always pointing outside the hull - var face = Face.create(eyeVertex, horizonEdge.tail(), horizonEdge.head()); - this.faces.push(face); // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 ) - - face.getEdge(-1).setTwin(horizonEdge.twin); - return face.getEdge(0); // the half edge whose vertex is the eyeVertex - }, - // Adds 'horizon.length' faces to the hull, each face will be linked with the - // horizon opposite face and the face on the left/right - addNewFaces: function (eyeVertex, horizon) { - this.newFaces = []; - var firstSideEdge = null; - var previousSideEdge = null; - - for (var i = 0; i < horizon.length; i++) { - var horizonEdge = horizon[i]; // returns the right side edge - - var sideEdge = this.addAdjoiningFace(eyeVertex, horizonEdge); - - if (firstSideEdge === null) { - firstSideEdge = sideEdge; - } else { - // joins face.getEdge( 1 ) with previousFace.getEdge( 0 ) - sideEdge.next.setTwin(previousSideEdge); - } - - this.newFaces.push(sideEdge.face); - previousSideEdge = sideEdge; - } // perform final join of new faces - - - firstSideEdge.next.setTwin(previousSideEdge); - return this; - }, - // Adds a vertex to the hull - addVertexToHull: function (eyeVertex) { - var horizon = []; - this.unassigned.clear(); // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list - - this.removeVertexFromFace(eyeVertex, eyeVertex.face); - this.computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon); - this.addNewFaces(eyeVertex, horizon); // reassign 'unassigned' vertices to the new faces - - this.resolveUnassignedPoints(this.newFaces); - return this; - }, - cleanup: function () { - this.assigned.clear(); - this.unassigned.clear(); - this.newFaces = []; - return this; - }, - compute: function () { - var vertex; - this.computeInitialHull(); // add all available vertices gradually to the hull - - while ((vertex = this.nextVertexToAdd()) !== undefined) { - this.addVertexToHull(vertex); - } - - this.reindexFaces(); - this.cleanup(); - return this; - } - }); // - - function Face() { - this.normal = new three.Vector3(); - this.midpoint = new three.Vector3(); - this.area = 0; - this.constant = 0; // signed distance from face to the origin - - this.outside = null; // reference to a vertex in a vertex list this face can see - - this.mark = Visible; - this.edge = null; - } - - Object.assign(Face, { - create: function (a, b, c) { - var face = new Face(); - var e0 = new HalfEdge(a, face); - var e1 = new HalfEdge(b, face); - var e2 = new HalfEdge(c, face); // join edges - - e0.next = e2.prev = e1; - e1.next = e0.prev = e2; - e2.next = e1.prev = e0; // main half edge reference - - face.edge = e0; - return face.compute(); - } - }); - Object.assign(Face.prototype, { - getEdge: function (i) { - var edge = this.edge; - - while (i > 0) { - edge = edge.next; - i--; - } - - while (i < 0) { - edge = edge.prev; - i++; - } - - return edge; - }, - compute: function () { - var triangle; - return function compute() { - if (triangle === undefined) triangle = new three.Triangle(); - var a = this.edge.tail(); - var b = this.edge.head(); - var c = this.edge.next.head(); - triangle.set(a.point, b.point, c.point); - triangle.getNormal(this.normal); - triangle.getMidpoint(this.midpoint); - this.area = triangle.getArea(); - this.constant = this.normal.dot(this.midpoint); - return this; - }; - }(), - distanceToPoint: function (point) { - return this.normal.dot(point) - this.constant; - } - }); // Entity for a Doubly-Connected Edge List (DCEL). - - function HalfEdge(vertex, face) { - this.vertex = vertex; - this.prev = null; - this.next = null; - this.twin = null; - this.face = face; - } - - Object.assign(HalfEdge.prototype, { - head: function () { - return this.vertex; - }, - tail: function () { - return this.prev ? this.prev.vertex : null; - }, - length: function () { - var head = this.head(); - var tail = this.tail(); - - if (tail !== null) { - return tail.point.distanceTo(head.point); - } - - return -1; - }, - lengthSquared: function () { - var head = this.head(); - var tail = this.tail(); - - if (tail !== null) { - return tail.point.distanceToSquared(head.point); - } - - return -1; - }, - setTwin: function (edge) { - this.twin = edge; - edge.twin = this; - return this; - } - }); // A vertex as a double linked list node. - - function VertexNode(point) { - this.point = point; - this.prev = null; - this.next = null; - this.face = null; // the face that is able to see this vertex - } // A double linked list that contains vertex nodes. - - - function VertexList() { - this.head = null; - this.tail = null; - } - - Object.assign(VertexList.prototype, { - first: function () { - return this.head; - }, - last: function () { - return this.tail; - }, - clear: function () { - this.head = this.tail = null; - return this; - }, - // Inserts a vertex before the target vertex - insertBefore: function (target, vertex) { - vertex.prev = target.prev; - vertex.next = target; - - if (vertex.prev === null) { - this.head = vertex; - } else { - vertex.prev.next = vertex; - } - - target.prev = vertex; - return this; - }, - // Inserts a vertex after the target vertex - insertAfter: function (target, vertex) { - vertex.prev = target; - vertex.next = target.next; - - if (vertex.next === null) { - this.tail = vertex; - } else { - vertex.next.prev = vertex; - } - - target.next = vertex; - return this; - }, - // Appends a vertex to the end of the linked list - append: function (vertex) { - if (this.head === null) { - this.head = vertex; - } else { - this.tail.next = vertex; - } - - vertex.prev = this.tail; - vertex.next = null; // the tail has no subsequent vertex - - this.tail = vertex; - return this; - }, - // Appends a chain of vertices where 'vertex' is the head. - appendChain: function (vertex) { - if (this.head === null) { - this.head = vertex; - } else { - this.tail.next = vertex; - } - - vertex.prev = this.tail; // ensure that the 'tail' reference points to the last vertex of the chain - - while (vertex.next !== null) { - vertex = vertex.next; - } - - this.tail = vertex; - return this; - }, - // Removes a vertex from the linked list - remove: function (vertex) { - if (vertex.prev === null) { - this.head = vertex.next; - } else { - vertex.prev.next = vertex.next; - } - - if (vertex.next === null) { - this.tail = vertex.prev; - } else { - vertex.next.prev = vertex.prev; - } - - return this; - }, - // Removes a list of vertices whose 'head' is 'a' and whose 'tail' is b - removeSubList: function (a, b) { - if (a.prev === null) { - this.head = b.next; - } else { - a.prev.next = b.next; - } - - if (b.next === null) { - this.tail = a.prev; - } else { - b.next.prev = a.prev; - } - - return this; - }, - isEmpty: function () { - return this.head === null; - } - }); - return ConvexHull; -}(); - -const _v1 = new three.Vector3(); - -const _v2 = new three.Vector3(); - -const _q1 = new three.Quaternion(); -/** -* Returns a single geometry for the given object. If the object is compound, -* its geometries are automatically merged. Bake world scale into each -* geometry, because we can't easily apply that to the cannonjs shapes later. -*/ - - -function getGeometry(object) { - const meshes = getMeshes(object); - if (meshes.length === 0) return null; // Single mesh. Return, preserving original type. - - if (meshes.length === 1) { - return normalizeGeometry(meshes[0]); - } // Multiple meshes. Merge and return. - - - let mesh; - const geometries = []; - - while (mesh = meshes.pop()) { - geometries.push(simplifyGeometry(normalizeGeometry(mesh))); - } - - return mergeBufferGeometries(geometries); -} - -function normalizeGeometry(mesh) { - let geometry = mesh.geometry; - - if (geometry.toBufferGeometry) { - geometry = geometry.toBufferGeometry(); - } else { - // Preserve original type, e.g. CylinderBufferGeometry. - geometry = geometry.clone(); - } - - mesh.updateMatrixWorld(); - mesh.matrixWorld.decompose(_v1, _q1, _v2); - geometry.scale(_v2.x, _v2.y, _v2.z); - return geometry; -} -/** - * Greatly simplified version of BufferGeometryUtils.mergeBufferGeometries. - * Because we only care about the vertex positions, and not the indices or - * other attributes, we throw everything else away. - */ - - -function mergeBufferGeometries(geometries) { - let vertexCount = 0; - - for (let i = 0; i < geometries.length; i++) { - const position = geometries[i].attributes.position; - - if (position && position.itemSize === 3) { - vertexCount += position.count; - } - } - - const positionArray = new Float32Array(vertexCount * 3); - let positionOffset = 0; - - for (let i = 0; i < geometries.length; i++) { - const position = geometries[i].attributes.position; - - if (position && position.itemSize === 3) { - for (let j = 0; j < position.count; j++) { - positionArray[positionOffset++] = position.getX(j); - positionArray[positionOffset++] = position.getY(j); - positionArray[positionOffset++] = position.getZ(j); - } - } - } - - return new three.BufferGeometry().setAttribute('position', new three.BufferAttribute(positionArray, 3)); -} - -function getVertices(geometry) { - const position = geometry.attributes.position; - const vertices = new Float32Array(position.count * 3); - - for (let i = 0; i < position.count; i++) { - vertices[i * 3] = position.getX(i); - vertices[i * 3 + 1] = position.getY(i); - vertices[i * 3 + 2] = position.getZ(i); - } - - return vertices; -} -/** -* Returns a flat array of THREE.Mesh instances from the given object. If -* nested transformations are found, they are applied to child meshes -* as mesh.userData.matrix, so that each mesh has its position/rotation/scale -* independently of all of its parents except the top-level object. -*/ - -function getMeshes(object) { - const meshes = []; - object.traverse(function (o) { - if (o.isMesh) { - meshes.push(o); - } - }); - return meshes; -} - -function getComponent(v, component) { - switch (component) { - case 'x': - return v.x; - - case 'y': - return v.y; - - case 'z': - return v.z; - } - - throw new Error("Unexpected component " + component); -} -/** -* Modified version of BufferGeometryUtils.mergeVertices, ignoring vertex -* attributes other than position. -* -* @param {THREE.BufferGeometry} geometry -* @param {number} tolerance -* @return {THREE.BufferGeometry>} -*/ - -function simplifyGeometry(geometry, tolerance = 1e-4) { - tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it - // if it's already available. - - const hashToIndex = {}; - const indices = geometry.getIndex(); - const positions = geometry.getAttribute('position'); - const vertexCount = indices ? indices.count : positions.count; // Next value for triangle indices. - - let nextIndex = 0; - const newIndices = []; - const newPositions = []; // Convert the error tolerance to an amount of decimal places to truncate to. - - const decimalShift = Math.log10(1 / tolerance); - const shiftMultiplier = Math.pow(10, decimalShift); - - for (let i = 0; i < vertexCount; i++) { - const index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'. - - let hash = ''; // Double tilde truncates the decimal value. - - hash += ~~(positions.getX(index) * shiftMultiplier) + ","; - hash += ~~(positions.getY(index) * shiftMultiplier) + ","; - hash += ~~(positions.getZ(index) * shiftMultiplier) + ","; // Add another reference to the vertex if it's already - // used by another index. - - if (hash in hashToIndex) { - newIndices.push(hashToIndex[hash]); - } else { - newPositions.push(positions.getX(index)); - newPositions.push(positions.getY(index)); - newPositions.push(positions.getZ(index)); - hashToIndex[hash] = nextIndex; - newIndices.push(nextIndex); - nextIndex++; - } - } // Construct merged BufferGeometry. - - - const positionAttribute = new three.BufferAttribute(new Float32Array(newPositions), positions.itemSize, positions.normalized); - const result = new three.BufferGeometry(); - result.setAttribute('position', positionAttribute); - result.setIndex(newIndices); - return result; -} - -const PI_2 = Math.PI / 2; -exports.ShapeType = void 0; - -(function (ShapeType) { - ShapeType["BOX"] = "Box"; - ShapeType["CYLINDER"] = "Cylinder"; - ShapeType["SPHERE"] = "Sphere"; - ShapeType["HULL"] = "ConvexPolyhedron"; - ShapeType["MESH"] = "Trimesh"; -})(exports.ShapeType || (exports.ShapeType = {})); -/** - * Given a THREE.Object3D instance, creates parameters for a CANNON shape. - */ - - -const getShapeParameters = function (object, options = {}) { - let geometry; - - if (options.type === exports.ShapeType.BOX) { - return getBoundingBoxParameters(object); - } else if (options.type === exports.ShapeType.CYLINDER) { - return getBoundingCylinderParameters(object, options); - } else if (options.type === exports.ShapeType.SPHERE) { - return getBoundingSphereParameters(object, options); - } else if (options.type === exports.ShapeType.HULL) { - return getConvexPolyhedronParameters(object); - } else if (options.type === exports.ShapeType.MESH) { - geometry = getGeometry(object); - return geometry ? getTrimeshParameters(geometry) : null; - } else if (options.type) { - throw new Error("[CANNON.getShapeParameters] Invalid type \"" + options.type + "\"."); - } - - geometry = getGeometry(object); - if (!geometry) return null; - - switch (geometry.type) { - case 'BoxGeometry': - case 'BoxBufferGeometry': - return getBoxParameters(geometry); - - case 'CylinderGeometry': - case 'CylinderBufferGeometry': - return getCylinderParameters(geometry); - - case 'PlaneGeometry': - case 'PlaneBufferGeometry': - return getPlaneParameters(geometry); - - case 'SphereGeometry': - case 'SphereBufferGeometry': - return getSphereParameters(geometry); - - case 'TubeGeometry': - case 'BufferGeometry': - return getBoundingBoxParameters(object); - - default: - console.warn('Unrecognized geometry: "%s". Using bounding box as shape.', geometry.type); - return getBoxParameters(geometry); - } -}; -/** - * Given a THREE.Object3D instance, creates a corresponding CANNON shape. - */ - -const threeToCannon = function (object, options = {}) { - const shapeParameters = getShapeParameters(object, options); - - if (!shapeParameters) { - return null; - } - - const { - type, - params, - offset, - orientation - } = shapeParameters; - let shape; - - if (type === exports.ShapeType.BOX) { - shape = createBox(params); - } else if (type === exports.ShapeType.CYLINDER) { - shape = createCylinder(params); - } else if (type === exports.ShapeType.SPHERE) { - shape = createSphere(params); - } else if (type === exports.ShapeType.HULL) { - shape = createConvexPolyhedron(params); - } else { - shape = createTrimesh(params); - } - - return { - shape, - offset, - orientation - }; -}; -/****************************************************************************** - * Shape construction - */ - -function createBox(params) { - const { - x, - y, - z - } = params; - const shape = new cannonEs.Box(new cannonEs.Vec3(x, y, z)); - return shape; -} - -function createCylinder(params) { - const { - radiusTop, - radiusBottom, - height, - segments - } = params; - const shape = new cannonEs.Cylinder(radiusTop, radiusBottom, height, segments); // Include metadata for serialization. - // TODO(cleanup): Is this still necessary? - - shape.radiusTop = radiusBottom; - shape.radiusBottom = radiusBottom; - shape.height = height; - shape.numSegments = segments; - return shape; -} - -function createSphere(params) { - const shape = new cannonEs.Sphere(params.radius); - return shape; -} - -function createConvexPolyhedron(params) { - const { - faces, - vertices: verticesArray - } = params; - const vertices = []; - - for (let i = 0; i < verticesArray.length; i += 3) { - vertices.push(new cannonEs.Vec3(verticesArray[i], verticesArray[i + 1], verticesArray[i + 2])); - } - - const shape = new cannonEs.ConvexPolyhedron({ - faces, - vertices - }); - return shape; -} - -function createTrimesh(params) { - const { - vertices, - indices - } = params; - const shape = new cannonEs.Trimesh(vertices, indices); - return shape; -} -/****************************************************************************** - * Shape parameters - */ - - -function getBoxParameters(geometry) { - const vertices = getVertices(geometry); - if (!vertices.length) return null; - geometry.computeBoundingBox(); - const box = geometry.boundingBox; - return { - type: exports.ShapeType.BOX, - params: { - x: (box.max.x - box.min.x) / 2, - y: (box.max.y - box.min.y) / 2, - z: (box.max.z - box.min.z) / 2 - } - }; -} -/** Bounding box needs to be computed with the entire subtree, not just geometry. */ - - -function getBoundingBoxParameters(object) { - const clone = object.clone(); - clone.quaternion.set(0, 0, 0, 1); - clone.updateMatrixWorld(); - const box = new three.Box3().setFromObject(clone); - if (!isFinite(box.min.lengthSq())) return null; - const localPosition = box.translate(clone.position.negate()).getCenter(new three.Vector3()); - return { - type: exports.ShapeType.BOX, - params: { - x: (box.max.x - box.min.x) / 2, - y: (box.max.y - box.min.y) / 2, - z: (box.max.z - box.min.z) / 2 - }, - offset: localPosition.lengthSq() ? new cannonEs.Vec3(localPosition.x, localPosition.y, localPosition.z) : undefined - }; -} -/** Computes 3D convex hull as a CANNON.ConvexPolyhedron. */ - - -function getConvexPolyhedronParameters(object) { - const geometry = getGeometry(object); - if (!geometry) return null; // Perturb. - - const eps = 1e-4; - - for (let i = 0; i < geometry.attributes.position.count; i++) { - geometry.attributes.position.setXYZ(i, geometry.attributes.position.getX(i) + (Math.random() - 0.5) * eps, geometry.attributes.position.getY(i) + (Math.random() - 0.5) * eps, geometry.attributes.position.getZ(i) + (Math.random() - 0.5) * eps); - } // Compute the 3D convex hull. - - - const hull = new ConvexHull().setFromObject(new three.Mesh(geometry)); - const hullFaces = hull.faces; - const vertices = []; - const faces = []; - let currentFaceVertex = 0; - - for (let i = 0; i < hullFaces.length; i++) { - const hullFace = hullFaces[i]; - const face = []; - faces.push(face); - let edge = hullFace.edge; - - do { - const point = edge.head().point; - vertices.push(point.x, point.y, point.z); - face.push(currentFaceVertex); - currentFaceVertex++; - edge = edge.next; - } while (edge !== hullFace.edge); - } - - const verticesTypedArray = new Float32Array(vertices.length); - verticesTypedArray.set(vertices); - return { - type: exports.ShapeType.HULL, - params: { - vertices: verticesTypedArray, - faces - } - }; -} - -function getCylinderParameters(geometry) { - const params = geometry.parameters; - return { - type: exports.ShapeType.CYLINDER, - params: { - radiusTop: params.radiusTop, - radiusBottom: params.radiusBottom, - height: params.height, - segments: params.radialSegments - }, - orientation: new cannonEs.Quaternion().setFromEuler(three.MathUtils.degToRad(-90), 0, 0, 'XYZ').normalize() - }; -} - -function getBoundingCylinderParameters(object, options) { - const axes = ['x', 'y', 'z']; - const majorAxis = options.cylinderAxis || 'y'; - const minorAxes = axes.splice(axes.indexOf(majorAxis), 1) && axes; - const box = new three.Box3().setFromObject(object); - if (!isFinite(box.min.lengthSq())) return null; // Compute cylinder dimensions. - - const height = box.max[majorAxis] - box.min[majorAxis]; - const radius = 0.5 * Math.max(getComponent(box.max, minorAxes[0]) - getComponent(box.min, minorAxes[0]), getComponent(box.max, minorAxes[1]) - getComponent(box.min, minorAxes[1])); - const eulerX = majorAxis === 'y' ? PI_2 : 0; - const eulerY = majorAxis === 'z' ? PI_2 : 0; - return { - type: exports.ShapeType.CYLINDER, - params: { - radiusTop: radius, - radiusBottom: radius, - height, - segments: 12 - }, - orientation: new cannonEs.Quaternion().setFromEuler(eulerX, eulerY, 0, 'XYZ').normalize() - }; -} - -function getPlaneParameters(geometry) { - geometry.computeBoundingBox(); - const box = geometry.boundingBox; - return { - type: exports.ShapeType.BOX, - params: { - x: (box.max.x - box.min.x) / 2 || 0.1, - y: (box.max.y - box.min.y) / 2 || 0.1, - z: (box.max.z - box.min.z) / 2 || 0.1 - } - }; -} - -function getSphereParameters(geometry) { - return { - type: exports.ShapeType.SPHERE, - params: { - radius: geometry.parameters.radius - } - }; -} - -function getBoundingSphereParameters(object, options) { - if (options.sphereRadius) { - return { - type: exports.ShapeType.SPHERE, - params: { - radius: options.sphereRadius - } - }; - } - - const geometry = getGeometry(object); - if (!geometry) return null; - geometry.computeBoundingSphere(); - return { - type: exports.ShapeType.SPHERE, - params: { - radius: geometry.boundingSphere.radius - } - }; -} - -function getTrimeshParameters(geometry) { - const vertices = getVertices(geometry); - if (!vertices.length) return null; - const indices = new Uint32Array(vertices.length); - - for (let i = 0; i < vertices.length; i++) { - indices[i] = i; - } - - return { - type: exports.ShapeType.MESH, - params: { - vertices, - indices - } - }; -} - -exports.getShapeParameters = getShapeParameters; -exports.threeToCannon = threeToCannon; +var e=require("cannon-es"),t=(typeof window !== "undefined" ? window['THREE'] : typeof global !== "undefined" ? global['THREE'] : null),n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-Infinity,i=Infinity,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-Infinity!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) @@ -16014,7 +14691,6 @@ let AmmoBody = { data = this.data; this.localScaling = new Ammo.btVector3(); - this.scaleVector = new THREE.Vector3(); const obj = this.el.object3D; obj.getWorldPosition(pos); @@ -16084,10 +14760,8 @@ let AmmoBody = { let updated = false; const obj = this.el.object3D; - - obj.getWorldScale(this.scaleVector); - if (this.data.scaleAutoUpdate && this.prevScale && !almostEqualsVector3(0.001, this.scaleVector, this.prevScale)) { - this.prevScale.copy(this.scaleVector); + if (this.data.scaleAutoUpdate && this.prevScale && !almostEqualsVector3(0.001, obj.scale, this.prevScale)) { + this.prevScale.copy(obj.scale); updated = true; this.localScaling.setValue(this.prevScale.x, this.prevScale.y, this.prevScale.z); diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index 5bd2d10..14f8c11 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3,this.scaleVector=new THREE.Vector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;if(this.el.object3D.getWorldScale(this.scaleVector),this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,this.scaleVector,this.prevScale)&&(this.prevScale.copy(this.scaleVector),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var e=require("cannon-es"),t="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-1/0,i=1/0,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-1/0!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"cannon-es":4}],7:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;const obj=this.el.object3D;if(this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,obj.scale,this.prevScale)&&(this.prevScale.copy(obj.scale),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file diff --git a/src/components/body/ammo-body.js b/src/components/body/ammo-body.js index 958b417..02352fc 100644 --- a/src/components/body/ammo-body.js +++ b/src/components/body/ammo-body.js @@ -103,7 +103,6 @@ let AmmoBody = { data = this.data; this.localScaling = new Ammo.btVector3(); - this.scaleVector = new THREE.Vector3(); const obj = this.el.object3D; obj.getWorldPosition(pos); @@ -173,10 +172,8 @@ let AmmoBody = { let updated = false; const obj = this.el.object3D; - - obj.getWorldScale(this.scaleVector); - if (this.data.scaleAutoUpdate && this.prevScale && !almostEqualsVector3(0.001, this.scaleVector, this.prevScale)) { - this.prevScale.copy(this.scaleVector); + if (this.data.scaleAutoUpdate && this.prevScale && !almostEqualsVector3(0.001, obj.scale, this.prevScale)) { + this.prevScale.copy(obj.scale); updated = true; this.localScaling.setValue(this.prevScale.x, this.prevScale.y, this.prevScale.z); From 48a1db4a5d36d74d4b813ecfd320629ea58150c1 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Thu, 6 Oct 2022 15:56:48 +0100 Subject: [PATCH 23/28] Revert change that shouldn't have been on this branch --- dist/aframe-physics-system.js | 2 +- dist/aframe-physics-system.min.js | 2 +- src/components/body/ammo-body.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index fa47235..9976595 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -15009,8 +15009,8 @@ let AmmoBody = { const quaternion = this.msTransform.getRotation(); const el = this.el, + parentEl = el.parentEl, body = this.body; - parentEl = el.object3D.parent.el ? el.object3D.parent.el : el.parentEl; if (!body) return; if (!parentEl) return; diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index 14f8c11..5bdc22c 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var e=require("cannon-es"),t="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-1/0,i=1/0,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-1/0!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"cannon-es":4}],7:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;const obj=this.el.object3D;if(this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,obj.scale,this.prevScale)&&(this.prevScale.copy(obj.scale),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var e=require("cannon-es"),t="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-1/0,i=1/0,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-1/0!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"cannon-es":4}],7:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;const obj=this.el.object3D;if(this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,obj.scale,this.prevScale)&&(this.prevScale.copy(obj.scale),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file diff --git a/src/components/body/ammo-body.js b/src/components/body/ammo-body.js index 02352fc..8e5b479 100644 --- a/src/components/body/ammo-body.js +++ b/src/components/body/ammo-body.js @@ -421,8 +421,8 @@ let AmmoBody = { const quaternion = this.msTransform.getRotation(); const el = this.el, + parentEl = el.parentEl, body = this.body; - parentEl = el.object3D.parent.el ? el.object3D.parent.el : el.parentEl; if (!body) return; if (!parentEl) return; From 33c702fadfdc4ef5ce13b095f01e39ccb7acb43f Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Thu, 6 Oct 2022 15:58:02 +0100 Subject: [PATCH 24/28] Revert change that shouldn't have been on this branch --- dist/aframe-physics-system.js | 3 +-- dist/aframe-physics-system.min.js | 2 +- src/components/body/ammo-body.js | 3 +-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index 9976595..2960826 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -14779,8 +14779,7 @@ let AmmoBody = { const collisionShapes = shapeComponent.getShapes(); for (let j = 0; j < collisionShapes.length; j++) { const collisionShape = collisionShapes[j]; - if (collisionShape && - !collisionShape.added) { + if (!collisionShape.added) { this.compoundShape.addChildShape(collisionShape.localTransform, collisionShape); collisionShape.added = true; } diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index 5bdc22c..6022cd7 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var e=require("cannon-es"),t="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-1/0,i=1/0,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-1/0!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"cannon-es":4}],7:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;const obj=this.el.object3D;if(this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,obj.scale,this.prevScale)&&(this.prevScale.copy(obj.scale),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var e=require("cannon-es"),t="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-1/0,i=1/0,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-1/0!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"cannon-es":4}],7:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;const obj=this.el.object3D;if(this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,obj.scale,this.prevScale)&&(this.prevScale.copy(obj.scale),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file diff --git a/src/components/body/ammo-body.js b/src/components/body/ammo-body.js index 8e5b479..46784e6 100644 --- a/src/components/body/ammo-body.js +++ b/src/components/body/ammo-body.js @@ -191,8 +191,7 @@ let AmmoBody = { const collisionShapes = shapeComponent.getShapes(); for (let j = 0; j < collisionShapes.length; j++) { const collisionShape = collisionShapes[j]; - if (collisionShape && - !collisionShape.added) { + if (!collisionShape.added) { this.compoundShape.addChildShape(collisionShape.localTransform, collisionShape); collisionShape.added = true; } From f9dc225ec3cc1789f808c1924993453bbf81bb46 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Thu, 6 Oct 2022 17:21:44 +0100 Subject: [PATCH 25/28] FIx merge error --- src/components/body/ammo-body.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/components/body/ammo-body.js b/src/components/body/ammo-body.js index e4f28ae..8f3ff51 100644 --- a/src/components/body/ammo-body.js +++ b/src/components/body/ammo-body.js @@ -420,7 +420,6 @@ let AmmoBody = { const quaternion = this.msTransform.getRotation(); const el = this.el, - parentEl = el.parentEl, body = this.body; // For the parent, prefer to use the THHREE.js scene graph parent (if it can be determined) @@ -431,7 +430,7 @@ let AmmoBody = { // of object positioning etc. // For specific examples, and more discussion, see: // https://github.com/c-frame/aframe-physics-system/pull/1#issuecomment-1264686433 - parentEl = el.object3D.parent.el ? el.object3D.parent.el : el.parentEl; + const parentEl = el.object3D.parent.el ? el.object3D.parent.el : el.parentEl; if (!body) return; if (!parentEl) return; From 023c85c33fd6bc6f6573a49f3203b73b9b3e64ea Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Thu, 6 Oct 2022 17:22:11 +0100 Subject: [PATCH 26/28] This is not a THREE.Quaternion. inverse() is still correct. --- src/components/ammo-constraint.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/ammo-constraint.js b/src/components/ammo-constraint.js index 5ac1a94..c9e7ecc 100644 --- a/src/components/ammo-constraint.js +++ b/src/components/ammo-constraint.js @@ -69,7 +69,7 @@ module.exports = AFRAME.registerComponent("ammo-constraint", { const bodyTransform = body .getCenterOfMassTransform() - .invert() + .inverse() .op_mul(targetBody.getWorldTransform()); const targetTransform = new Ammo.btTransform(); targetTransform.setIdentity(); From dc7dcf4469d0de2f8cef4549dcb5e63dbd5b24e0 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Thu, 6 Oct 2022 17:22:36 +0100 Subject: [PATCH 27/28] Optimization - create fewer THREE.Vector3s. --- lib/CANNON-shape2mesh.js | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/lib/CANNON-shape2mesh.js b/lib/CANNON-shape2mesh.js index 6f4f728..43c6a47 100644 --- a/lib/CANNON-shape2mesh.js +++ b/lib/CANNON-shape2mesh.js @@ -9,10 +9,10 @@ var CANNON = require('cannon-es'); CANNON.shape2mesh = function(body){ var obj = new THREE.Object3D(); - function createBufferGeometry(vertices, faces) { + function createBufferGeometry(positions, faces) { var geometry = new THREE.BufferGeometry(); - geometry.setFromPoints(vertices); + geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) ); geometry.setIndex(faces); geometry.computeBoundingSphere(); return geometry; @@ -60,10 +60,10 @@ CANNON.shape2mesh = function(body){ case CANNON.Shape.types.CONVEXPOLYHEDRON: // Add vertices - var vertices = [] + var positions = [] for (var i = 0; i < shape.vertices.length; i++) { var v = shape.vertices[i]; - vertices.push(new THREE.Vector3(v.x, v.y, v.z)); + positions.push(v.x, v.y, v.z); } var faces = [] @@ -79,7 +79,7 @@ CANNON.shape2mesh = function(body){ } } - var geo = createBufferGeometry(vertices, faces); + var geo = createBufferGeometry(positions, faces); mesh = new THREE.Mesh( geo, this.currentMaterial ); break; @@ -88,7 +88,7 @@ CANNON.shape2mesh = function(body){ var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); - var vertices = []; + var positions = []; var faces = []; for (var xi = 0; xi < shape.data.length - 1; xi++) { for (var yi = 0; yi < shape.data[xi].length - 1; yi++) { @@ -100,17 +100,17 @@ CANNON.shape2mesh = function(body){ v0.vadd(shape.pillarOffset, v0); v1.vadd(shape.pillarOffset, v1); v2.vadd(shape.pillarOffset, v2); - vertices.push( - new THREE.Vector3(v0.x, v0.y, v0.z), - new THREE.Vector3(v1.x, v1.y, v1.z), - new THREE.Vector3(v2.x, v2.y, v2.z) + positions.push( + v0.x, v0.y, v0.z, + v1.x, v1.y, v1.z, + v2.x, v2.y, v2.z ); - var i = vertices.length - 3; + var i = positions.length / 3 - 3; faces.push(i, i+1, i+2); } } } - var geometry = createBufferGeometry(vertices, faces); + var geometry = createBufferGeometry(positions, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; @@ -120,19 +120,19 @@ CANNON.shape2mesh = function(body){ var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); - var vertices = []; + var positions = []; var faces = []; for (var i = 0; i < shape.indices.length / 3; i++) { shape.getTriangleVertices(i, v0, v1, v2); - vertices.push( - new THREE.Vector3(v0.x, v0.y, v0.z), - new THREE.Vector3(v1.x, v1.y, v1.z), - new THREE.Vector3(v2.x, v2.y, v2.z) + positions.push( + v0.x, v0.y, v0.z, + v1.x, v1.y, v1.z, + v2.x, v2.y, v2.z ); - var j = vertices.length - 3; + var j = positions.length / 3 - 3; faces.push(j, j+1, j+2); } - var geometry = createBufferGeometry(vertices, faces); + var geometry = createBufferGeometry(positions, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; From 7001a5b0c221063986ef6777ac4e5d3c35ee2cb3 Mon Sep 17 00:00:00 2001 From: diarmidmackenzie Date: Thu, 6 Oct 2022 17:22:53 +0100 Subject: [PATCH 28/28] Update builds --- dist/aframe-physics-system.js | 1376 ++++++++++++++++++++++++++++- dist/aframe-physics-system.min.js | 2 +- 2 files changed, 1355 insertions(+), 23 deletions(-) diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index 2960826..fe4b33d 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -34,10 +34,10 @@ var CANNON = require('cannon-es'); CANNON.shape2mesh = function(body){ var obj = new THREE.Object3D(); - function createBufferGeometry(vertices, faces) { + function createBufferGeometry(positions, faces) { var geometry = new THREE.BufferGeometry(); - geometry.setFromPoints(vertices); + geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) ); geometry.setIndex(faces); geometry.computeBoundingSphere(); return geometry; @@ -85,10 +85,10 @@ CANNON.shape2mesh = function(body){ case CANNON.Shape.types.CONVEXPOLYHEDRON: // Add vertices - var vertices = [] + var positions = [] for (var i = 0; i < shape.vertices.length; i++) { var v = shape.vertices[i]; - vertices.push(new THREE.Vector3(v.x, v.y, v.z)); + positions.push(v.x, v.y, v.z); } var faces = [] @@ -104,7 +104,7 @@ CANNON.shape2mesh = function(body){ } } - var geo = createBufferGeometry(vertices, faces); + var geo = createBufferGeometry(positions, faces); mesh = new THREE.Mesh( geo, this.currentMaterial ); break; @@ -113,7 +113,7 @@ CANNON.shape2mesh = function(body){ var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); - var vertices = []; + var positions = []; var faces = []; for (var xi = 0; xi < shape.data.length - 1; xi++) { for (var yi = 0; yi < shape.data[xi].length - 1; yi++) { @@ -125,17 +125,17 @@ CANNON.shape2mesh = function(body){ v0.vadd(shape.pillarOffset, v0); v1.vadd(shape.pillarOffset, v1); v2.vadd(shape.pillarOffset, v2); - vertices.push( - new THREE.Vector3(v0.x, v0.y, v0.z), - new THREE.Vector3(v1.x, v1.y, v1.z), - new THREE.Vector3(v2.x, v2.y, v2.z) + positions.push( + v0.x, v0.y, v0.z, + v1.x, v1.y, v1.z, + v2.x, v2.y, v2.z ); - var i = vertices.length - 3; + var i = positions.length / 3 - 3; faces.push(i, i+1, i+2); } } } - var geometry = createBufferGeometry(vertices, faces); + var geometry = createBufferGeometry(positions, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; @@ -145,19 +145,19 @@ CANNON.shape2mesh = function(body){ var v0 = new CANNON.Vec3(); var v1 = new CANNON.Vec3(); var v2 = new CANNON.Vec3(); - var vertices = []; + var positions = []; var faces = []; for (var i = 0; i < shape.indices.length / 3; i++) { shape.getTriangleVertices(i, v0, v1, v2); - vertices.push( - new THREE.Vector3(v0.x, v0.y, v0.z), - new THREE.Vector3(v1.x, v1.y, v1.z), - new THREE.Vector3(v2.x, v2.y, v2.z) + positions.push( + v0.x, v0.y, v0.z, + v1.x, v1.y, v1.z, + v2.x, v2.y, v2.z ); - var j = vertices.length - 3; + var j = positions.length / 3 - 3; faces.push(j, j+1, j+2); } - var geometry = createBufferGeometry(vertices, faces); + var geometry = createBufferGeometry(positions, faces); mesh = new THREE.Mesh(geometry, this.currentMaterial); break; @@ -14339,7 +14339,1330 @@ const _computeBounds = (function() { },{}],6:[function(require,module,exports){ (function (global){ -var e=require("cannon-es"),t=(typeof window !== "undefined" ? window['THREE'] : typeof global !== "undefined" ? global['THREE'] : null),n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-Infinity,i=Infinity,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-Infinity!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o; +var cannonEs = require('cannon-es'); +var three = (typeof window !== "undefined" ? window['THREE'] : typeof global !== "undefined" ? global['THREE'] : null); + +/** + * Ported from: https://github.com/maurizzzio/quickhull3d/ by Mauricio Poppe (https://github.com/maurizzzio) + */ + +var ConvexHull = function () { + var Visible = 0; + var Deleted = 1; + var v1 = new three.Vector3(); + + function ConvexHull() { + this.tolerance = -1; + this.faces = []; // the generated faces of the convex hull + + this.newFaces = []; // this array holds the faces that are generated within a single iteration + // the vertex lists work as follows: + // + // let 'a' and 'b' be 'Face' instances + // let 'v' be points wrapped as instance of 'Vertex' + // + // [v, v, ..., v, v, v, ...] + // ^ ^ + // | | + // a.outside b.outside + // + + this.assigned = new VertexList(); + this.unassigned = new VertexList(); + this.vertices = []; // vertices of the hull (internal representation of given geometry data) + } + + Object.assign(ConvexHull.prototype, { + setFromPoints: function (points) { + if (Array.isArray(points) !== true) { + console.error('THREE.ConvexHull: Points parameter is not an array.'); + } + + if (points.length < 4) { + console.error('THREE.ConvexHull: The algorithm needs at least four points.'); + } + + this.makeEmpty(); + + for (var i = 0, l = points.length; i < l; i++) { + this.vertices.push(new VertexNode(points[i])); + } + + this.compute(); + return this; + }, + setFromObject: function (object) { + var points = []; + object.updateMatrixWorld(true); + object.traverse(function (node) { + var i, l, point; + var geometry = node.geometry; + if (geometry === undefined) return; + + if (geometry.isGeometry) { + geometry = geometry.toBufferGeometry ? geometry.toBufferGeometry() : new three.BufferGeometry().fromGeometry(geometry); + } + + if (geometry.isBufferGeometry) { + var attribute = geometry.attributes.position; + + if (attribute !== undefined) { + for (i = 0, l = attribute.count; i < l; i++) { + point = new three.Vector3(); + point.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld); + points.push(point); + } + } + } + }); + return this.setFromPoints(points); + }, + containsPoint: function (point) { + var faces = this.faces; + + for (var i = 0, l = faces.length; i < l; i++) { + var face = faces[i]; // compute signed distance and check on what half space the point lies + + if (face.distanceToPoint(point) > this.tolerance) return false; + } + + return true; + }, + intersectRay: function (ray, target) { + // based on "Fast Ray-Convex Polyhedron Intersection" by Eric Haines, GRAPHICS GEMS II + var faces = this.faces; + var tNear = -Infinity; + var tFar = Infinity; + + for (var i = 0, l = faces.length; i < l; i++) { + var face = faces[i]; // interpret faces as planes for the further computation + + var vN = face.distanceToPoint(ray.origin); + var vD = face.normal.dot(ray.direction); // if the origin is on the positive side of a plane (so the plane can "see" the origin) and + // the ray is turned away or parallel to the plane, there is no intersection + + if (vN > 0 && vD >= 0) return null; // compute the distance from the ray’s origin to the intersection with the plane + + var t = vD !== 0 ? -vN / vD : 0; // only proceed if the distance is positive. a negative distance means the intersection point + // lies "behind" the origin + + if (t <= 0) continue; // now categorized plane as front-facing or back-facing + + if (vD > 0) { + // plane faces away from the ray, so this plane is a back-face + tFar = Math.min(t, tFar); + } else { + // front-face + tNear = Math.max(t, tNear); + } + + if (tNear > tFar) { + // if tNear ever is greater than tFar, the ray must miss the convex hull + return null; + } + } // evaluate intersection point + // always try tNear first since its the closer intersection point + + + if (tNear !== -Infinity) { + ray.at(tNear, target); + } else { + ray.at(tFar, target); + } + + return target; + }, + intersectsRay: function (ray) { + return this.intersectRay(ray, v1) !== null; + }, + makeEmpty: function () { + this.faces = []; + this.vertices = []; + return this; + }, + // Adds a vertex to the 'assigned' list of vertices and assigns it to the given face + addVertexToFace: function (vertex, face) { + vertex.face = face; + + if (face.outside === null) { + this.assigned.append(vertex); + } else { + this.assigned.insertBefore(face.outside, vertex); + } + + face.outside = vertex; + return this; + }, + // Removes a vertex from the 'assigned' list of vertices and from the given face + removeVertexFromFace: function (vertex, face) { + if (vertex === face.outside) { + // fix face.outside link + if (vertex.next !== null && vertex.next.face === face) { + // face has at least 2 outside vertices, move the 'outside' reference + face.outside = vertex.next; + } else { + // vertex was the only outside vertex that face had + face.outside = null; + } + } + + this.assigned.remove(vertex); + return this; + }, + // Removes all the visible vertices that a given face is able to see which are stored in the 'assigned' vertext list + removeAllVerticesFromFace: function (face) { + if (face.outside !== null) { + // reference to the first and last vertex of this face + var start = face.outside; + var end = face.outside; + + while (end.next !== null && end.next.face === face) { + end = end.next; + } + + this.assigned.removeSubList(start, end); // fix references + + start.prev = end.next = null; + face.outside = null; + return start; + } + }, + // Removes all the visible vertices that 'face' is able to see + deleteFaceVertices: function (face, absorbingFace) { + var faceVertices = this.removeAllVerticesFromFace(face); + + if (faceVertices !== undefined) { + if (absorbingFace === undefined) { + // mark the vertices to be reassigned to some other face + this.unassigned.appendChain(faceVertices); + } else { + // if there's an absorbing face try to assign as many vertices as possible to it + var vertex = faceVertices; + + do { + // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference + // will be changed by upcoming method calls + var nextVertex = vertex.next; + var distance = absorbingFace.distanceToPoint(vertex.point); // check if 'vertex' is able to see 'absorbingFace' + + if (distance > this.tolerance) { + this.addVertexToFace(vertex, absorbingFace); + } else { + this.unassigned.append(vertex); + } // now assign next vertex + + + vertex = nextVertex; + } while (vertex !== null); + } + } + + return this; + }, + // Reassigns as many vertices as possible from the unassigned list to the new faces + resolveUnassignedPoints: function (newFaces) { + if (this.unassigned.isEmpty() === false) { + var vertex = this.unassigned.first(); + + do { + // buffer 'next' reference, see .deleteFaceVertices() + var nextVertex = vertex.next; + var maxDistance = this.tolerance; + var maxFace = null; + + for (var i = 0; i < newFaces.length; i++) { + var face = newFaces[i]; + + if (face.mark === Visible) { + var distance = face.distanceToPoint(vertex.point); + + if (distance > maxDistance) { + maxDistance = distance; + maxFace = face; + } + + if (maxDistance > 1000 * this.tolerance) break; + } + } // 'maxFace' can be null e.g. if there are identical vertices + + + if (maxFace !== null) { + this.addVertexToFace(vertex, maxFace); + } + + vertex = nextVertex; + } while (vertex !== null); + } + + return this; + }, + // Computes the extremes of a simplex which will be the initial hull + computeExtremes: function () { + var min = new three.Vector3(); + var max = new three.Vector3(); + var minVertices = []; + var maxVertices = []; + var i, l, j; // initially assume that the first vertex is the min/max + + for (i = 0; i < 3; i++) { + minVertices[i] = maxVertices[i] = this.vertices[0]; + } + + min.copy(this.vertices[0].point); + max.copy(this.vertices[0].point); // compute the min/max vertex on all six directions + + for (i = 0, l = this.vertices.length; i < l; i++) { + var vertex = this.vertices[i]; + var point = vertex.point; // update the min coordinates + + for (j = 0; j < 3; j++) { + if (point.getComponent(j) < min.getComponent(j)) { + min.setComponent(j, point.getComponent(j)); + minVertices[j] = vertex; + } + } // update the max coordinates + + + for (j = 0; j < 3; j++) { + if (point.getComponent(j) > max.getComponent(j)) { + max.setComponent(j, point.getComponent(j)); + maxVertices[j] = vertex; + } + } + } // use min/max vectors to compute an optimal epsilon + + + this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max.x)) + Math.max(Math.abs(min.y), Math.abs(max.y)) + Math.max(Math.abs(min.z), Math.abs(max.z))); + return { + min: minVertices, + max: maxVertices + }; + }, + // Computes the initial simplex assigning to its faces all the points + // that are candidates to form part of the hull + computeInitialHull: function () { + var line3, plane, closestPoint; + return function computeInitialHull() { + if (line3 === undefined) { + line3 = new three.Line3(); + plane = new three.Plane(); + closestPoint = new three.Vector3(); + } + + var vertex, + vertices = this.vertices; + var extremes = this.computeExtremes(); + var min = extremes.min; + var max = extremes.max; + var v0, v1, v2, v3; + var i, l, j; // 1. Find the two vertices 'v0' and 'v1' with the greatest 1d separation + // (max.x - min.x) + // (max.y - min.y) + // (max.z - min.z) + + var distance, + maxDistance = 0; + var index = 0; + + for (i = 0; i < 3; i++) { + distance = max[i].point.getComponent(i) - min[i].point.getComponent(i); + + if (distance > maxDistance) { + maxDistance = distance; + index = i; + } + } + + v0 = min[index]; + v1 = max[index]; // 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1' + + maxDistance = 0; + line3.set(v0.point, v1.point); + + for (i = 0, l = this.vertices.length; i < l; i++) { + vertex = vertices[i]; + + if (vertex !== v0 && vertex !== v1) { + line3.closestPointToPoint(vertex.point, true, closestPoint); + distance = closestPoint.distanceToSquared(vertex.point); + + if (distance > maxDistance) { + maxDistance = distance; + v2 = vertex; + } + } + } // 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2' + + + maxDistance = -1; + plane.setFromCoplanarPoints(v0.point, v1.point, v2.point); + + for (i = 0, l = this.vertices.length; i < l; i++) { + vertex = vertices[i]; + + if (vertex !== v0 && vertex !== v1 && vertex !== v2) { + distance = Math.abs(plane.distanceToPoint(vertex.point)); + + if (distance > maxDistance) { + maxDistance = distance; + v3 = vertex; + } + } + } + + var faces = []; + + if (plane.distanceToPoint(v3.point) < 0) { + // the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron + faces.push(Face.create(v0, v1, v2), Face.create(v3, v1, v0), Face.create(v3, v2, v1), Face.create(v3, v0, v2)); // set the twin edge + + for (i = 0; i < 3; i++) { + j = (i + 1) % 3; // join face[ i ] i > 0, with the first face + + faces[i + 1].getEdge(2).setTwin(faces[0].getEdge(j)); // join face[ i ] with face[ i + 1 ], 1 <= i <= 3 + + faces[i + 1].getEdge(1).setTwin(faces[j + 1].getEdge(0)); + } + } else { + // the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron + faces.push(Face.create(v0, v2, v1), Face.create(v3, v0, v1), Face.create(v3, v1, v2), Face.create(v3, v2, v0)); // set the twin edge + + for (i = 0; i < 3; i++) { + j = (i + 1) % 3; // join face[ i ] i > 0, with the first face + + faces[i + 1].getEdge(2).setTwin(faces[0].getEdge((3 - i) % 3)); // join face[ i ] with face[ i + 1 ] + + faces[i + 1].getEdge(0).setTwin(faces[j + 1].getEdge(1)); + } + } // the initial hull is the tetrahedron + + + for (i = 0; i < 4; i++) { + this.faces.push(faces[i]); + } // initial assignment of vertices to the faces of the tetrahedron + + + for (i = 0, l = vertices.length; i < l; i++) { + vertex = vertices[i]; + + if (vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3) { + maxDistance = this.tolerance; + var maxFace = null; + + for (j = 0; j < 4; j++) { + distance = this.faces[j].distanceToPoint(vertex.point); + + if (distance > maxDistance) { + maxDistance = distance; + maxFace = this.faces[j]; + } + } + + if (maxFace !== null) { + this.addVertexToFace(vertex, maxFace); + } + } + } + + return this; + }; + }(), + // Removes inactive faces + reindexFaces: function () { + var activeFaces = []; + + for (var i = 0; i < this.faces.length; i++) { + var face = this.faces[i]; + + if (face.mark === Visible) { + activeFaces.push(face); + } + } + + this.faces = activeFaces; + return this; + }, + // Finds the next vertex to create faces with the current hull + nextVertexToAdd: function () { + // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined' + if (this.assigned.isEmpty() === false) { + var eyeVertex, + maxDistance = 0; // grap the first available face and start with the first visible vertex of that face + + var eyeFace = this.assigned.first().face; + var vertex = eyeFace.outside; // now calculate the farthest vertex that face can see + + do { + var distance = eyeFace.distanceToPoint(vertex.point); + + if (distance > maxDistance) { + maxDistance = distance; + eyeVertex = vertex; + } + + vertex = vertex.next; + } while (vertex !== null && vertex.face === eyeFace); + + return eyeVertex; + } + }, + // Computes a chain of half edges in CCW order called the 'horizon'. + // For an edge to be part of the horizon it must join a face that can see + // 'eyePoint' and a face that cannot see 'eyePoint'. + computeHorizon: function (eyePoint, crossEdge, face, horizon) { + // moves face's vertices to the 'unassigned' vertex list + this.deleteFaceVertices(face); + face.mark = Deleted; + var edge; + + if (crossEdge === null) { + edge = crossEdge = face.getEdge(0); + } else { + // start from the next edge since 'crossEdge' was already analyzed + // (actually 'crossEdge.twin' was the edge who called this method recursively) + edge = crossEdge.next; + } + + do { + var twinEdge = edge.twin; + var oppositeFace = twinEdge.face; + + if (oppositeFace.mark === Visible) { + if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) { + // the opposite face can see the vertex, so proceed with next edge + this.computeHorizon(eyePoint, twinEdge, oppositeFace, horizon); + } else { + // the opposite face can't see the vertex, so this edge is part of the horizon + horizon.push(edge); + } + } + + edge = edge.next; + } while (edge !== crossEdge); + + return this; + }, + // Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head' in CCW order + addAdjoiningFace: function (eyeVertex, horizonEdge) { + // all the half edges are created in ccw order thus the face is always pointing outside the hull + var face = Face.create(eyeVertex, horizonEdge.tail(), horizonEdge.head()); + this.faces.push(face); // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 ) + + face.getEdge(-1).setTwin(horizonEdge.twin); + return face.getEdge(0); // the half edge whose vertex is the eyeVertex + }, + // Adds 'horizon.length' faces to the hull, each face will be linked with the + // horizon opposite face and the face on the left/right + addNewFaces: function (eyeVertex, horizon) { + this.newFaces = []; + var firstSideEdge = null; + var previousSideEdge = null; + + for (var i = 0; i < horizon.length; i++) { + var horizonEdge = horizon[i]; // returns the right side edge + + var sideEdge = this.addAdjoiningFace(eyeVertex, horizonEdge); + + if (firstSideEdge === null) { + firstSideEdge = sideEdge; + } else { + // joins face.getEdge( 1 ) with previousFace.getEdge( 0 ) + sideEdge.next.setTwin(previousSideEdge); + } + + this.newFaces.push(sideEdge.face); + previousSideEdge = sideEdge; + } // perform final join of new faces + + + firstSideEdge.next.setTwin(previousSideEdge); + return this; + }, + // Adds a vertex to the hull + addVertexToHull: function (eyeVertex) { + var horizon = []; + this.unassigned.clear(); // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list + + this.removeVertexFromFace(eyeVertex, eyeVertex.face); + this.computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon); + this.addNewFaces(eyeVertex, horizon); // reassign 'unassigned' vertices to the new faces + + this.resolveUnassignedPoints(this.newFaces); + return this; + }, + cleanup: function () { + this.assigned.clear(); + this.unassigned.clear(); + this.newFaces = []; + return this; + }, + compute: function () { + var vertex; + this.computeInitialHull(); // add all available vertices gradually to the hull + + while ((vertex = this.nextVertexToAdd()) !== undefined) { + this.addVertexToHull(vertex); + } + + this.reindexFaces(); + this.cleanup(); + return this; + } + }); // + + function Face() { + this.normal = new three.Vector3(); + this.midpoint = new three.Vector3(); + this.area = 0; + this.constant = 0; // signed distance from face to the origin + + this.outside = null; // reference to a vertex in a vertex list this face can see + + this.mark = Visible; + this.edge = null; + } + + Object.assign(Face, { + create: function (a, b, c) { + var face = new Face(); + var e0 = new HalfEdge(a, face); + var e1 = new HalfEdge(b, face); + var e2 = new HalfEdge(c, face); // join edges + + e0.next = e2.prev = e1; + e1.next = e0.prev = e2; + e2.next = e1.prev = e0; // main half edge reference + + face.edge = e0; + return face.compute(); + } + }); + Object.assign(Face.prototype, { + getEdge: function (i) { + var edge = this.edge; + + while (i > 0) { + edge = edge.next; + i--; + } + + while (i < 0) { + edge = edge.prev; + i++; + } + + return edge; + }, + compute: function () { + var triangle; + return function compute() { + if (triangle === undefined) triangle = new three.Triangle(); + var a = this.edge.tail(); + var b = this.edge.head(); + var c = this.edge.next.head(); + triangle.set(a.point, b.point, c.point); + triangle.getNormal(this.normal); + triangle.getMidpoint(this.midpoint); + this.area = triangle.getArea(); + this.constant = this.normal.dot(this.midpoint); + return this; + }; + }(), + distanceToPoint: function (point) { + return this.normal.dot(point) - this.constant; + } + }); // Entity for a Doubly-Connected Edge List (DCEL). + + function HalfEdge(vertex, face) { + this.vertex = vertex; + this.prev = null; + this.next = null; + this.twin = null; + this.face = face; + } + + Object.assign(HalfEdge.prototype, { + head: function () { + return this.vertex; + }, + tail: function () { + return this.prev ? this.prev.vertex : null; + }, + length: function () { + var head = this.head(); + var tail = this.tail(); + + if (tail !== null) { + return tail.point.distanceTo(head.point); + } + + return -1; + }, + lengthSquared: function () { + var head = this.head(); + var tail = this.tail(); + + if (tail !== null) { + return tail.point.distanceToSquared(head.point); + } + + return -1; + }, + setTwin: function (edge) { + this.twin = edge; + edge.twin = this; + return this; + } + }); // A vertex as a double linked list node. + + function VertexNode(point) { + this.point = point; + this.prev = null; + this.next = null; + this.face = null; // the face that is able to see this vertex + } // A double linked list that contains vertex nodes. + + + function VertexList() { + this.head = null; + this.tail = null; + } + + Object.assign(VertexList.prototype, { + first: function () { + return this.head; + }, + last: function () { + return this.tail; + }, + clear: function () { + this.head = this.tail = null; + return this; + }, + // Inserts a vertex before the target vertex + insertBefore: function (target, vertex) { + vertex.prev = target.prev; + vertex.next = target; + + if (vertex.prev === null) { + this.head = vertex; + } else { + vertex.prev.next = vertex; + } + + target.prev = vertex; + return this; + }, + // Inserts a vertex after the target vertex + insertAfter: function (target, vertex) { + vertex.prev = target; + vertex.next = target.next; + + if (vertex.next === null) { + this.tail = vertex; + } else { + vertex.next.prev = vertex; + } + + target.next = vertex; + return this; + }, + // Appends a vertex to the end of the linked list + append: function (vertex) { + if (this.head === null) { + this.head = vertex; + } else { + this.tail.next = vertex; + } + + vertex.prev = this.tail; + vertex.next = null; // the tail has no subsequent vertex + + this.tail = vertex; + return this; + }, + // Appends a chain of vertices where 'vertex' is the head. + appendChain: function (vertex) { + if (this.head === null) { + this.head = vertex; + } else { + this.tail.next = vertex; + } + + vertex.prev = this.tail; // ensure that the 'tail' reference points to the last vertex of the chain + + while (vertex.next !== null) { + vertex = vertex.next; + } + + this.tail = vertex; + return this; + }, + // Removes a vertex from the linked list + remove: function (vertex) { + if (vertex.prev === null) { + this.head = vertex.next; + } else { + vertex.prev.next = vertex.next; + } + + if (vertex.next === null) { + this.tail = vertex.prev; + } else { + vertex.next.prev = vertex.prev; + } + + return this; + }, + // Removes a list of vertices whose 'head' is 'a' and whose 'tail' is b + removeSubList: function (a, b) { + if (a.prev === null) { + this.head = b.next; + } else { + a.prev.next = b.next; + } + + if (b.next === null) { + this.tail = a.prev; + } else { + b.next.prev = a.prev; + } + + return this; + }, + isEmpty: function () { + return this.head === null; + } + }); + return ConvexHull; +}(); + +const _v1 = new three.Vector3(); + +const _v2 = new three.Vector3(); + +const _q1 = new three.Quaternion(); +/** +* Returns a single geometry for the given object. If the object is compound, +* its geometries are automatically merged. Bake world scale into each +* geometry, because we can't easily apply that to the cannonjs shapes later. +*/ + + +function getGeometry(object) { + const meshes = getMeshes(object); + if (meshes.length === 0) return null; // Single mesh. Return, preserving original type. + + if (meshes.length === 1) { + return normalizeGeometry(meshes[0]); + } // Multiple meshes. Merge and return. + + + let mesh; + const geometries = []; + + while (mesh = meshes.pop()) { + geometries.push(simplifyGeometry(normalizeGeometry(mesh))); + } + + return mergeBufferGeometries(geometries); +} + +function normalizeGeometry(mesh) { + let geometry = mesh.geometry; + + if (geometry.toBufferGeometry) { + geometry = geometry.toBufferGeometry(); + } else { + // Preserve original type, e.g. CylinderBufferGeometry. + geometry = geometry.clone(); + } + + mesh.updateMatrixWorld(); + mesh.matrixWorld.decompose(_v1, _q1, _v2); + geometry.scale(_v2.x, _v2.y, _v2.z); + return geometry; +} +/** + * Greatly simplified version of BufferGeometryUtils.mergeBufferGeometries. + * Because we only care about the vertex positions, and not the indices or + * other attributes, we throw everything else away. + */ + + +function mergeBufferGeometries(geometries) { + let vertexCount = 0; + + for (let i = 0; i < geometries.length; i++) { + const position = geometries[i].attributes.position; + + if (position && position.itemSize === 3) { + vertexCount += position.count; + } + } + + const positionArray = new Float32Array(vertexCount * 3); + let positionOffset = 0; + + for (let i = 0; i < geometries.length; i++) { + const position = geometries[i].attributes.position; + + if (position && position.itemSize === 3) { + for (let j = 0; j < position.count; j++) { + positionArray[positionOffset++] = position.getX(j); + positionArray[positionOffset++] = position.getY(j); + positionArray[positionOffset++] = position.getZ(j); + } + } + } + + return new three.BufferGeometry().setAttribute('position', new three.BufferAttribute(positionArray, 3)); +} + +function getVertices(geometry) { + const position = geometry.attributes.position; + const vertices = new Float32Array(position.count * 3); + + for (let i = 0; i < position.count; i++) { + vertices[i * 3] = position.getX(i); + vertices[i * 3 + 1] = position.getY(i); + vertices[i * 3 + 2] = position.getZ(i); + } + + return vertices; +} +/** +* Returns a flat array of THREE.Mesh instances from the given object. If +* nested transformations are found, they are applied to child meshes +* as mesh.userData.matrix, so that each mesh has its position/rotation/scale +* independently of all of its parents except the top-level object. +*/ + +function getMeshes(object) { + const meshes = []; + object.traverse(function (o) { + if (o.isMesh) { + meshes.push(o); + } + }); + return meshes; +} + +function getComponent(v, component) { + switch (component) { + case 'x': + return v.x; + + case 'y': + return v.y; + + case 'z': + return v.z; + } + + throw new Error("Unexpected component " + component); +} +/** +* Modified version of BufferGeometryUtils.mergeVertices, ignoring vertex +* attributes other than position. +* +* @param {THREE.BufferGeometry} geometry +* @param {number} tolerance +* @return {THREE.BufferGeometry>} +*/ + +function simplifyGeometry(geometry, tolerance = 1e-4) { + tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it + // if it's already available. + + const hashToIndex = {}; + const indices = geometry.getIndex(); + const positions = geometry.getAttribute('position'); + const vertexCount = indices ? indices.count : positions.count; // Next value for triangle indices. + + let nextIndex = 0; + const newIndices = []; + const newPositions = []; // Convert the error tolerance to an amount of decimal places to truncate to. + + const decimalShift = Math.log10(1 / tolerance); + const shiftMultiplier = Math.pow(10, decimalShift); + + for (let i = 0; i < vertexCount; i++) { + const index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'. + + let hash = ''; // Double tilde truncates the decimal value. + + hash += ~~(positions.getX(index) * shiftMultiplier) + ","; + hash += ~~(positions.getY(index) * shiftMultiplier) + ","; + hash += ~~(positions.getZ(index) * shiftMultiplier) + ","; // Add another reference to the vertex if it's already + // used by another index. + + if (hash in hashToIndex) { + newIndices.push(hashToIndex[hash]); + } else { + newPositions.push(positions.getX(index)); + newPositions.push(positions.getY(index)); + newPositions.push(positions.getZ(index)); + hashToIndex[hash] = nextIndex; + newIndices.push(nextIndex); + nextIndex++; + } + } // Construct merged BufferGeometry. + + + const positionAttribute = new three.BufferAttribute(new Float32Array(newPositions), positions.itemSize, positions.normalized); + const result = new three.BufferGeometry(); + result.setAttribute('position', positionAttribute); + result.setIndex(newIndices); + return result; +} + +const PI_2 = Math.PI / 2; +exports.ShapeType = void 0; + +(function (ShapeType) { + ShapeType["BOX"] = "Box"; + ShapeType["CYLINDER"] = "Cylinder"; + ShapeType["SPHERE"] = "Sphere"; + ShapeType["HULL"] = "ConvexPolyhedron"; + ShapeType["MESH"] = "Trimesh"; +})(exports.ShapeType || (exports.ShapeType = {})); +/** + * Given a THREE.Object3D instance, creates parameters for a CANNON shape. + */ + + +const getShapeParameters = function (object, options = {}) { + let geometry; + + if (options.type === exports.ShapeType.BOX) { + return getBoundingBoxParameters(object); + } else if (options.type === exports.ShapeType.CYLINDER) { + return getBoundingCylinderParameters(object, options); + } else if (options.type === exports.ShapeType.SPHERE) { + return getBoundingSphereParameters(object, options); + } else if (options.type === exports.ShapeType.HULL) { + return getConvexPolyhedronParameters(object); + } else if (options.type === exports.ShapeType.MESH) { + geometry = getGeometry(object); + return geometry ? getTrimeshParameters(geometry) : null; + } else if (options.type) { + throw new Error("[CANNON.getShapeParameters] Invalid type \"" + options.type + "\"."); + } + + geometry = getGeometry(object); + if (!geometry) return null; + + switch (geometry.type) { + case 'BoxGeometry': + case 'BoxBufferGeometry': + return getBoxParameters(geometry); + + case 'CylinderGeometry': + case 'CylinderBufferGeometry': + return getCylinderParameters(geometry); + + case 'PlaneGeometry': + case 'PlaneBufferGeometry': + return getPlaneParameters(geometry); + + case 'SphereGeometry': + case 'SphereBufferGeometry': + return getSphereParameters(geometry); + + case 'TubeGeometry': + case 'BufferGeometry': + return getBoundingBoxParameters(object); + + default: + console.warn('Unrecognized geometry: "%s". Using bounding box as shape.', geometry.type); + return getBoxParameters(geometry); + } +}; +/** + * Given a THREE.Object3D instance, creates a corresponding CANNON shape. + */ + +const threeToCannon = function (object, options = {}) { + const shapeParameters = getShapeParameters(object, options); + + if (!shapeParameters) { + return null; + } + + const { + type, + params, + offset, + orientation + } = shapeParameters; + let shape; + + if (type === exports.ShapeType.BOX) { + shape = createBox(params); + } else if (type === exports.ShapeType.CYLINDER) { + shape = createCylinder(params); + } else if (type === exports.ShapeType.SPHERE) { + shape = createSphere(params); + } else if (type === exports.ShapeType.HULL) { + shape = createConvexPolyhedron(params); + } else { + shape = createTrimesh(params); + } + + return { + shape, + offset, + orientation + }; +}; +/****************************************************************************** + * Shape construction + */ + +function createBox(params) { + const { + x, + y, + z + } = params; + const shape = new cannonEs.Box(new cannonEs.Vec3(x, y, z)); + return shape; +} + +function createCylinder(params) { + const { + radiusTop, + radiusBottom, + height, + segments + } = params; + const shape = new cannonEs.Cylinder(radiusTop, radiusBottom, height, segments); // Include metadata for serialization. + // TODO(cleanup): Is this still necessary? + + shape.radiusTop = radiusBottom; + shape.radiusBottom = radiusBottom; + shape.height = height; + shape.numSegments = segments; + return shape; +} + +function createSphere(params) { + const shape = new cannonEs.Sphere(params.radius); + return shape; +} + +function createConvexPolyhedron(params) { + const { + faces, + vertices: verticesArray + } = params; + const vertices = []; + + for (let i = 0; i < verticesArray.length; i += 3) { + vertices.push(new cannonEs.Vec3(verticesArray[i], verticesArray[i + 1], verticesArray[i + 2])); + } + + const shape = new cannonEs.ConvexPolyhedron({ + faces, + vertices + }); + return shape; +} + +function createTrimesh(params) { + const { + vertices, + indices + } = params; + const shape = new cannonEs.Trimesh(vertices, indices); + return shape; +} +/****************************************************************************** + * Shape parameters + */ + + +function getBoxParameters(geometry) { + const vertices = getVertices(geometry); + if (!vertices.length) return null; + geometry.computeBoundingBox(); + const box = geometry.boundingBox; + return { + type: exports.ShapeType.BOX, + params: { + x: (box.max.x - box.min.x) / 2, + y: (box.max.y - box.min.y) / 2, + z: (box.max.z - box.min.z) / 2 + } + }; +} +/** Bounding box needs to be computed with the entire subtree, not just geometry. */ + + +function getBoundingBoxParameters(object) { + const clone = object.clone(); + clone.quaternion.set(0, 0, 0, 1); + clone.updateMatrixWorld(); + const box = new three.Box3().setFromObject(clone); + if (!isFinite(box.min.lengthSq())) return null; + const localPosition = box.translate(clone.position.negate()).getCenter(new three.Vector3()); + return { + type: exports.ShapeType.BOX, + params: { + x: (box.max.x - box.min.x) / 2, + y: (box.max.y - box.min.y) / 2, + z: (box.max.z - box.min.z) / 2 + }, + offset: localPosition.lengthSq() ? new cannonEs.Vec3(localPosition.x, localPosition.y, localPosition.z) : undefined + }; +} +/** Computes 3D convex hull as a CANNON.ConvexPolyhedron. */ + + +function getConvexPolyhedronParameters(object) { + const geometry = getGeometry(object); + if (!geometry) return null; // Perturb. + + const eps = 1e-4; + + for (let i = 0; i < geometry.attributes.position.count; i++) { + geometry.attributes.position.setXYZ(i, geometry.attributes.position.getX(i) + (Math.random() - 0.5) * eps, geometry.attributes.position.getY(i) + (Math.random() - 0.5) * eps, geometry.attributes.position.getZ(i) + (Math.random() - 0.5) * eps); + } // Compute the 3D convex hull. + + + const hull = new ConvexHull().setFromObject(new three.Mesh(geometry)); + const hullFaces = hull.faces; + const vertices = []; + const faces = []; + let currentFaceVertex = 0; + + for (let i = 0; i < hullFaces.length; i++) { + const hullFace = hullFaces[i]; + const face = []; + faces.push(face); + let edge = hullFace.edge; + + do { + const point = edge.head().point; + vertices.push(point.x, point.y, point.z); + face.push(currentFaceVertex); + currentFaceVertex++; + edge = edge.next; + } while (edge !== hullFace.edge); + } + + const verticesTypedArray = new Float32Array(vertices.length); + verticesTypedArray.set(vertices); + return { + type: exports.ShapeType.HULL, + params: { + vertices: verticesTypedArray, + faces + } + }; +} + +function getCylinderParameters(geometry) { + const params = geometry.parameters; + return { + type: exports.ShapeType.CYLINDER, + params: { + radiusTop: params.radiusTop, + radiusBottom: params.radiusBottom, + height: params.height, + segments: params.radialSegments + }, + orientation: new cannonEs.Quaternion().setFromEuler(three.MathUtils.degToRad(-90), 0, 0, 'XYZ').normalize() + }; +} + +function getBoundingCylinderParameters(object, options) { + const axes = ['x', 'y', 'z']; + const majorAxis = options.cylinderAxis || 'y'; + const minorAxes = axes.splice(axes.indexOf(majorAxis), 1) && axes; + const box = new three.Box3().setFromObject(object); + if (!isFinite(box.min.lengthSq())) return null; // Compute cylinder dimensions. + + const height = box.max[majorAxis] - box.min[majorAxis]; + const radius = 0.5 * Math.max(getComponent(box.max, minorAxes[0]) - getComponent(box.min, minorAxes[0]), getComponent(box.max, minorAxes[1]) - getComponent(box.min, minorAxes[1])); + const eulerX = majorAxis === 'y' ? PI_2 : 0; + const eulerY = majorAxis === 'z' ? PI_2 : 0; + return { + type: exports.ShapeType.CYLINDER, + params: { + radiusTop: radius, + radiusBottom: radius, + height, + segments: 12 + }, + orientation: new cannonEs.Quaternion().setFromEuler(eulerX, eulerY, 0, 'XYZ').normalize() + }; +} + +function getPlaneParameters(geometry) { + geometry.computeBoundingBox(); + const box = geometry.boundingBox; + return { + type: exports.ShapeType.BOX, + params: { + x: (box.max.x - box.min.x) / 2 || 0.1, + y: (box.max.y - box.min.y) / 2 || 0.1, + z: (box.max.z - box.min.z) / 2 || 0.1 + } + }; +} + +function getSphereParameters(geometry) { + return { + type: exports.ShapeType.SPHERE, + params: { + radius: geometry.parameters.radius + } + }; +} + +function getBoundingSphereParameters(object, options) { + if (options.sphereRadius) { + return { + type: exports.ShapeType.SPHERE, + params: { + radius: options.sphereRadius + } + }; + } + + const geometry = getGeometry(object); + if (!geometry) return null; + geometry.computeBoundingSphere(); + return { + type: exports.ShapeType.SPHERE, + params: { + radius: geometry.boundingSphere.radius + } + }; +} + +function getTrimeshParameters(geometry) { + const vertices = getVertices(geometry); + if (!vertices.length) return null; + const indices = new Uint32Array(vertices.length); + + for (let i = 0; i < vertices.length; i++) { + indices[i] = i; + } + + return { + type: exports.ShapeType.MESH, + params: { + vertices, + indices + } + }; +} + +exports.getShapeParameters = getShapeParameters; +exports.threeToCannon = threeToCannon; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) @@ -14498,7 +15821,7 @@ module.exports = AFRAME.registerComponent("ammo-constraint", { const bodyTransform = body .getCenterOfMassTransform() - .invert() + .inverse() .op_mul(targetBody.getWorldTransform()); const targetTransform = new Ammo.btTransform(); targetTransform.setIdentity(); @@ -15008,9 +16331,18 @@ let AmmoBody = { const quaternion = this.msTransform.getRotation(); const el = this.el, - parentEl = el.parentEl, body = this.body; + // For the parent, prefer to use the THHREE.js scene graph parent (if it can be determined) + // and only use the HTML scene graph parent as a fallback. + // Usually these are the same, but there are various cases where it's useful to modify the THREE.js + // scene graph so that it deviates from the HTML. + // In these cases the THREE.js scene graph should be considered the definitive reference in terms + // of object positioning etc. + // For specific examples, and more discussion, see: + // https://github.com/c-frame/aframe-physics-system/pull/1#issuecomment-1264686433 + const parentEl = el.object3D.parent.el ? el.object3D.parent.el : el.parentEl; + if (!body) return; if (!parentEl) return; diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index 6022cd7..ea7eda5 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var e=require("cannon-es"),t="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,n=function(){var e,n,r,i,o=new t.Vector3;function a(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new l,this.unassigned=new l,this.vertices=[]}function s(){this.normal=new t.Vector3,this.midpoint=new t.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}function u(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}function h(e){this.point=e,this.prev=null,this.next=null,this.face=null}function l(){this.head=null,this.tail=null}return Object.assign(a.prototype,{setFromPoints:function(e){!0!==Array.isArray(e)&&console.error("THREE.ConvexHull: Points parameter is not an array."),e.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var t=0,n=e.length;tthis.tolerance)return!1;return!0},intersectRay:function(e,t){for(var n=this.faces,r=-1/0,i=1/0,o=0,a=n.length;o0&&h>=0)return null;var l=0!==h?-u/h:0;if(!(l<=0)&&(h>0?i=Math.min(l,i):r=Math.max(l,r),r>i))return null}return e.at(-1/0!==r?r:i,t),t},intersectsRay:function(e){return null!==this.intersectRay(e,o)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this},removeVertexFromFace:function(e,t){return e===t.outside&&(t.outside=null!==e.next&&e.next.face===t?e.next:null),this.assigned.remove(e),this},removeAllVerticesFromFace:function(e){if(null!==e.outside){for(var t=e.outside,n=e.outside;null!==n.next&&n.next.face===e;)n=n.next;return this.assigned.removeSubList(t,n),t.prev=n.next=null,e.outside=null,t}},deleteFaceVertices:function(e,t){var n=this.removeAllVerticesFromFace(e);if(void 0!==n)if(void 0===t)this.unassigned.appendChain(n);else{var r=n;do{var i=r.next;t.distanceToPoint(r.point)>this.tolerance?this.addVertexToFace(r,t):this.unassigned.append(r),r=i}while(null!==r)}return this},resolveUnassignedPoints:function(e){if(!1===this.unassigned.isEmpty()){var t=this.unassigned.first();do{for(var n=t.next,r=this.tolerance,i=null,o=0;or&&(r=s,i=a),r>1e3*this.tolerance)break}}null!==i&&this.addVertexToFace(t,i),t=n}while(null!==t)}return this},computeExtremes:function(){var e,n,r,i=new t.Vector3,o=new t.Vector3,a=[],s=[];for(e=0;e<3;e++)a[e]=s[e]=this.vertices[0];for(i.copy(this.vertices[0].point),o.copy(this.vertices[0].point),e=0,n=this.vertices.length;eo.getComponent(r)&&(o.setComponent(r,h.getComponent(r)),s[r]=u)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(i.x),Math.abs(o.x))+Math.max(Math.abs(i.y),Math.abs(o.y))+Math.max(Math.abs(i.z),Math.abs(o.z))),{min:a,max:s}},computeInitialHull:function(){void 0===e&&(e=new t.Line3,n=new t.Plane,r=new t.Vector3);var i,o,a,u,h,l,c,d,m,p=this.vertices,f=this.computeExtremes(),v=f.min,g=f.max,x=0,y=0;for(l=0;l<3;l++)(m=g[l].point.getComponent(l)-v[l].point.getComponent(l))>x&&(x=m,y=l);for(x=0,e.set((o=v[y]).point,(a=g[y]).point),l=0,c=this.vertices.length;lx&&(x=m,u=i));for(x=-1,n.setFromCoplanarPoints(o.point,a.point,u.point),l=0,c=this.vertices.length;lx&&(x=m,h=i);var w=[];if(n.distanceToPoint(h.point)<0)for(w.push(s.create(o,a,u),s.create(h,a,o),s.create(h,u,a),s.create(h,o,u)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge(d)),w[l+1].getEdge(1).setTwin(w[d+1].getEdge(0));else for(w.push(s.create(o,u,a),s.create(h,o,a),s.create(h,a,u),s.create(h,u,o)),l=0;l<3;l++)d=(l+1)%3,w[l+1].getEdge(2).setTwin(w[0].getEdge((3-l)%3)),w[l+1].getEdge(0).setTwin(w[d+1].getEdge(1));for(l=0;l<4;l++)this.faces.push(w[l]);for(l=0,c=p.length;lx&&(x=m,T=this.faces[d]);null!==T&&this.addVertexToFace(i,T)}return this},reindexFaces:function(){for(var e=[],t=0;tt&&(t=i,e=r),r=r.next}while(null!==r&&r.face===n);return e}},computeHorizon:function(e,t,n,r){var i;this.deleteFaceVertices(n),n.mark=1,i=null===t?t=n.getEdge(0):t.next;do{var o=i.twin,a=o.face;0===a.mark&&(a.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,o,a,r):r.push(i)),i=i.next}while(i!==t);return this},addAdjoiningFace:function(e,t){var n=s.create(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setTwin(t.twin),n.getEdge(0)},addNewFaces:function(e,t){this.newFaces=[];for(var n=null,r=null,i=0;i0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t},compute:function(){void 0===i&&(i=new t.Triangle);var e=this.edge.tail(),n=this.edge.head(),r=this.edge.next.head();return i.set(e.point,n.point,r.point),i.getNormal(this.normal),i.getMidpoint(this.midpoint),this.area=i.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(e){return this.normal.dot(e)-this.constant}}),Object.assign(u.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceTo(e.point):-1},lengthSquared:function(){var e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1},setTwin:function(e){return this.twin=e,e.twin=this,this}}),Object.assign(l.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(e,t){return t.prev=e.prev,t.next=e,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this},insertAfter:function(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this},append:function(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this},appendChain:function(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this},remove:function(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this},removeSubList:function(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this},isEmpty:function(){return null===this.head}}),a}(),r=Math.PI/2,i={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},o=function(o,l){var c;if((l=l||{}).type===i.BOX)return s(o);if(l.type===i.CYLINDER)return function(n,i){var o=["x","y","z"],a=i.cylinderAxis||"y",s=o.splice(o.indexOf(a),1)&&o,u=(new t.Box3).setFromObject(n);if(!isFinite(u.min.lengthSq()))return null;var h=u.max[a]-u.min[a],l=.5*Math.max(u.max[s[0]]-u.min[s[0]],u.max[s[1]]-u.min[s[1]]),c=new e.Cylinder(l,l,h,12);return c._type=e.Shape.types.CYLINDER,c.radiusTop=l,c.radiusBottom=l,c.height=h,c.numSegments=12,c.orientation=new e.Quaternion,c.orientation.setFromEuler("y"===a?r:0,"z"===a?r:0,0,"XYZ").normalize(),c}(o,l);if(l.type===i.SPHERE)return function(t,n){if(n.sphereRadius)return new e.Sphere(n.sphereRadius);var r=u(t);return r?(r.computeBoundingSphere(),new e.Sphere(r.boundingSphere.radius)):null}(o,l);if(l.type===i.HULL)return function(r){var i=u(r);if(!i||!i.vertices.length)return null;for(var o=0;o2&&i.fromBufferGeometry(r[0].geometry):i=r[0].geometry.clone(),i.metadata=r[0].geometry.metadata,r[0].updateMatrixWorld(),r[0].matrixWorld.decompose(a,s,u),i.scale(u.x,u.y,u.z)}for(;n=r.pop();)if(n.updateMatrixWorld(),n.geometry.isBufferGeometry){if(n.geometry.attributes.position&&n.geometry.attributes.position.itemSize>2){var h=new t.Geometry;h.fromBufferGeometry(n.geometry),o.merge(h,n.matrixWorld),h.dispose()}}else o.merge(n.geometry,n.matrixWorld);var l=new t.Matrix4;return l.scale(e.scale),o.applyMatrix(l),o}function h(e){return e.attributes||(e=(new t.BufferGeometry).fromGeometry(e)),(e.attributes.position||{}).array||[]}o.Type=i,exports.threeToCannon=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"cannon-es":4}],7:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;const obj=this.el.object3D;if(this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,obj.scale,this.prevScale)&&(this.prevScale.copy(obj.scale),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file +!function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},_proto.set=function(bi,bj,value){var i=bi.id,j=bj.id;if(j>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},_proto.reset=function(){this.matrix={}},_proto.setNumObjects=function(n){},ObjectCollisionMatrix}(),Mat3=function(){function Mat3(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}var _proto=Mat3.prototype;return _proto.identity=function(){var e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1},_proto.setZero=function(){var e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0},_proto.setTrace=function(vector){var e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z},_proto.getTrace=function(target){void 0===target&&(target=new Vec3);var e=this.elements;target.x=e[0],target.y=e[4],target.z=e[8]},_proto.vmult=function(v,target){void 0===target&&(target=new Vec3);var e=this.elements,x=v.x,y=v.y,z=v.z;return target.x=e[0]*x+e[1]*y+e[2]*z,target.y=e[3]*x+e[4]*y+e[5]*z,target.z=e[6]*x+e[7]*y+e[8]*z,target},_proto.smult=function(s){for(var i=0;i0){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},_proto.unit=function(target){void 0===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},_proto.length=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},_proto.lengthSquared=function(){return this.dot(this)},_proto.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))},_proto.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)},_proto.scale=function(scalar,target){void 0===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},_proto.vmul=function(vector,target){return void 0===target&&(target=new Vec3),target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},_proto.addScaledVector=function(scalar,vector,target){return void 0===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},_proto.dot=function(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z},_proto.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},_proto.negate=function(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target},_proto.tangents=function(t1,t2){var norm=this.length();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)},_proto.toString=function(){return this.x+","+this.y+","+this.z},_proto.toArray=function(){return[this.x,this.y,this.z]},_proto.copy=function(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this},_proto.lerp=function(vector,t,target){var x=this.x,y=this.y,z=this.z;target.x=x+(vector.x-x)*t,target.y=y+(vector.y-y)*t,target.z=z+(vector.z-z)*t},_proto.almostEquals=function(vector,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-vector.x)>precision||Math.abs(this.y-vector.y)>precision||Math.abs(this.z-vector.z)>precision)},_proto.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)},_proto.isAntiparallelTo=function(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)},_proto.clone=function(){return new Vec3(this.x,this.y,this.z)},Vec3}();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);var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3,AABB=function(){function AABB(options){void 0===options&&(options={}),this.lowerBound=new Vec3,this.upperBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),options.upperBound&&this.upperBound.copy(options.upperBound)}var _proto=AABB.prototype;return _proto.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},_proto.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,u.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)},_proto.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)},_proto.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)},_proto.overlapsRay=function(ray){var direction=ray.direction,from=ray.from,dirFracX=1/direction.x,dirFracY=1/direction.y,dirFracZ=1/direction.z,t1=(this.lowerBound.x-from.x)*dirFracX,t2=(this.upperBound.x-from.x)*dirFracX,t3=(this.lowerBound.y-from.y)*dirFracY,t4=(this.upperBound.y-from.y)*dirFracY,t5=(this.lowerBound.z-from.z)*dirFracZ,t6=(this.upperBound.z-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)},AABB}(),tmp=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],ArrayCollisionMatrix=function(){function ArrayCollisionMatrix(){this.matrix=[]}var _proto=ArrayCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},_proto.set=function(bi,bj,value){var i=bi.index,j=bj.index;if(j>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},_proto.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},_proto.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1},ArrayCollisionMatrix}();function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}var EventTarget=function(){function EventTarget(){}var _proto=EventTarget.prototype;return _proto.addEventListener=function(type,listener){void 0===this._listeners&&(this._listeners={});var listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this},_proto.hasEventListener=function(type,listener){if(void 0===this._listeners)return!1;var listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))},_proto.hasAnyEventListener=function(type){return void 0!==this._listeners&&void 0!==this._listeners[type]},_proto.removeEventListener=function(type,listener){if(void 0===this._listeners)return this;var listeners=this._listeners;if(void 0===listeners[type])return this;var index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this},_proto.dispatchEvent=function(event){if(void 0===this._listeners)return this;var listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(var i=0,l=listenerArray.length;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),void 0===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},_proto.setFromEuler=function(x,y,z,order){void 0===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},_proto.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},_proto.slerp=function(toQuat,t,target){void 0===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},_proto.integrate=function(angularVelocity,dt,angularFactor,target){void 0===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},Quaternion}(),sfv_t1=new Vec3,sfv_t2=new Vec3,SHAPE_TYPES={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},Shape=function(){function Shape(options){void 0===options&&(options={}),this.id=Shape.idCounter++,this.type=options.type||0,this.boundingSphereRadius=0,this.collisionResponse=!options.collisionResponse||options.collisionResponse,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.material=options.material?options.material:null,this.body=null}var _proto=Shape.prototype;return _proto.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},_proto.volume=function(){throw"volume() not implemented for shape type "+this.type},_proto.calculateLocalInertia=function(mass,target){throw"calculateLocalInertia() not implemented for shape type "+this.type},_proto.calculateWorldAABB=function(pos,quat,min,max){throw"calculateWorldAABB() not implemented for shape type "+this.type},Shape}();Shape.idCounter=0,Shape.types=SHAPE_TYPES;var Transform=function(){function Transform(options){void 0===options&&(options={}),this.position=new Vec3,this.quaternion=new Quaternion,options.position&&this.position.copy(options.position),options.quaternion&&this.quaternion.copy(options.quaternion)}var _proto=Transform.prototype;return _proto.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},_proto.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result},Transform}(),tmpQuat=new Quaternion,ConvexPolyhedron=function(_Shape){function ConvexPolyhedron(props){var _this;void 0===props&&(props={});var _props=props,_props$vertices=_props.vertices,vertices=void 0===_props$vertices?[]:_props$vertices,_props$faces=_props.faces,faces=void 0===_props$faces?[]:_props$faces,_props$normals=_props.normals,normals=void 0===_props$normals?[]:_props$normals,axes=_props.axes,boundingSphereRadius=_props.boundingSphereRadius;return(_this=_Shape.call(this,{type:Shape.types.CONVEXPOLYHEDRON})||this).vertices=vertices,_this.faces=faces,_this.faceNormals=normals,0===_this.faceNormals.length&&_this.computeNormals(),boundingSphereRadius?_this.boundingSphereRadius=boundingSphereRadius:_this.updateBoundingSphereRadius(),_this.worldVertices=[],_this.worldVerticesNeedsUpdate=!0,_this.worldFaceNormals=[],_this.worldFaceNormalsNeedsUpdate=!0,_this.uniqueAxes=axes?axes.slice():null,_this.uniqueEdges=[],_this.computeEdges(),_this}_inheritsLoose(ConvexPolyhedron,_Shape);var _proto=ConvexPolyhedron.prototype;return _proto.computeEdges=function(){var faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;for(var edge=new Vec3,i=0;i!==faces.length;i++)for(var face=faces[i],numVertices=face.length,j=0;j!==numVertices;j++){var k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();for(var found=!1,p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}},_proto.computeNormals=function(){this.faceNormals.length=this.faces.length;for(var i=0;idmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)},_proto.findSeparatingAxis=function(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){var faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3,dmin=Number.MAX_VALUE;if(this.uniqueAxes)for(var _i=0;_i!==this.uniqueAxes.length;_i++){quatA.vmult(this.uniqueAxes[_i],faceANormalWS3);var _d=this.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===_d)return!1;_d0&&target.negate(target),!0},_proto.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,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(maxA0?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.boundingRadius=0,_this.wlambda=new Vec3,options.shape&&_this.addShape(options.shape),_this.updateMassProperties(),_this}_inheritsLoose(Body,_EventTarget);var _proto=Body.prototype;return _proto.wakeUp=function(){var prevState=this.sleepState;this.sleepState=0,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},_proto.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1},_proto.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),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))}},_proto.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))},_proto.pointToLocalFrame=function(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},_proto.vectorToLocalFrame=function(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result},_proto.pointToWorldFrame=function(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},_proto.vectorToWorldFrame=function(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result},_proto.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},_proto.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].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius},_proto.computeAABB=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat$1,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),bodyQuat.mult(shapeOrientations[i],orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1},_proto.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;},_proto.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)}},_proto.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)}},_proto.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(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)}},_proto.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)}},_proto.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)},_proto.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},_proto.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()}},Body}(EventTarget);Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};var tmpVec=new Vec3,tmpQuat$1=new Quaternion,computeAABB_shapeAABB=new AABB,uiw_m1=new Mat3,uiw_m2=new Mat3,Body_applyForce_rotForce=(new Mat3,new Vec3),Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3,Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3,Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3,Body_updateMassProperties_halfExtents=new Vec3,Broadphase=function(){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var _proto=Broadphase.prototype;return _proto.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},_proto.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)},_proto.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)},_proto.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.lengthSquared()dist.lengthSquared()};var GridBroadphase=function(_Broadphase){function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){var _this;void 0===aabbMin&&(aabbMin=new Vec3(100,100,100)),void 0===aabbMax&&(aabbMax=new Vec3(-100,-100,-100)),void 0===nx&&(nx=10),void 0===ny&&(ny=10),void 0===nz&&(nz=10),(_this=_Broadphase.call(this)||this).nx=nx,_this.ny=ny,_this.nz=nz,_this.aabbMin=aabbMin,_this.aabbMax=aabbMax;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 _i=0;_i!==N;_i++){var bi=bodies[_i],si=bi.shapes[0];switch(si.type){case SPHERE:var shape=si,x=bi.position.x,y=bi.position.y,z=bi.position.z,r=shape.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:var _shape=si;_shape.worldNormalNeedsUpdate&&_shape.computeWorldNormal(bi.quaternion);var planeNormal=_shape.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[_i2],_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)},GridBroadphase}(Broadphase),GridBroadphase_collisionPairs_d=new Vec3,NaiveBroadphase=(new Vec3,function(_Broadphase){function NaiveBroadphase(){return _Broadphase.call(this)||this}_inheritsLoose(NaiveBroadphase,_Broadphase);var _proto=NaiveBroadphase.prototype;return _proto.collisionPairs=function(world,pairs1,pairs2){for(var bi,bj,bodies=world.bodies,n=bodies.length,i=0;i!==n;i++)for(var j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)},_proto.aabbQuery=function(world,aabb,result){void 0===result&&(result=[]);for(var i=0;ishape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}},_proto._intersectBox=function(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)},_proto._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))}},_proto._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)}}}}},_proto._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,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},_proto.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&&(v=dot00*dot12-dot01*dot02)>=0&&u+vvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},_proto.aabbQuery=function(world,aabb,result){void 0===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=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.checkBounds=function(bi,bj,axisIndex){var biPos,bjPos;0===axisIndex?(biPos=bi.position.x,bjPos=bj.position.x):1===axisIndex?(biPos=bi.position.y,bjPos=bj.position.y):2===axisIndex&&(biPos=bi.position.z,bjPos=bj.position.z);var ri=bi.boundingRadius;return bjPos-bj.boundingRadius=-.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},WheelInfo}(),chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3,RaycastVehicle=function(){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,this.constraints=[],this.preStepCallback=function(){},this.currentVehicleSpeedKmHour=0}var _proto=RaycastVehicle.prototype;return _proto.addWheel=function(options){void 0===options&&(options={});var info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},_proto.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value},_proto.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},_proto.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},_proto.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},_proto.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},_proto.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);for(var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3,_i3=0;_i30?1:-1)*_wheel.customSlidingRotationalSpeed*timeStep),Math.abs(_wheel.brake)>Math.abs(_wheel.engineForce)&&(_wheel.deltaRotation=0),_wheel.rotation+=_wheel.deltaRotation,_wheel.deltaRotation*=.99}},_proto.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},_proto.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)},_proto.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)},_proto.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform},_proto.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,i=0;imaximpSquared){this.sliding=!0,_wheel3.sliding=!0;var _factor=maximp/Math.sqrt(impulseSquared);_wheel3.skidInfo*=_factor}}}if(this.sliding)for(var _i6=0;_i61.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))}var Sphere=function(_Shape){function Sphere(radius){var _this;if((_this=_Shape.call(this,{type:Shape.types.SPHERE})||this).radius=void 0!==radius?radius:1,_this.radius<0)throw new Error("The sphere radius cannot be negative.");return _this.updateBoundingSphereRadius(),_this}_inheritsLoose(Sphere,_Shape);var _proto=Sphere.prototype;return _proto.calculateLocalInertia=function(mass,target){void 0===target&&(target=new Vec3);var I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target},_proto.volume=function(){return 4*Math.PI*Math.pow(this.radius,3)/3},_proto.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},_proto.calculateWorldAABB=function(pos,quat,min,max){for(var r=this.radius,axes=["x","y","z"],i=0;ithis.particles.length&&this.neighbors.pop())},_proto.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.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue},_proto.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)},_proto.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){void 0===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},_proto.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)},_proto.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},_proto.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()},_proto.getAabbAtIndex=function(xi,yi,_ref){var lowerBound=_ref.lowerBound,upperBound=_ref.upperBound,data=this.data,elementSize=this.elementSize;lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},_proto.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);!function(x,y,ax,ay,bx,by,cx,cy,result){result.x=((by-cy)*(x-cx)+(cx-bx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.y=((cy-ay)*(x-cx)+(ax-cx)*(y-cy))/((by-cy)*(ax-cx)+(cx-bx)*(ay-cy)),result.z=1-result.x-result.y}(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},_proto.getCacheConvexTrianglePillarKey=function(xi,yi,getUpperTriangle){return xi+"_"+yi+"_"+(getUpperTriangle?1:0)},_proto.getCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.setCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}},_proto.clearCachedConvexTrianglePillar=function(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]},_proto.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]))},_proto.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){var _data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle);if(_data)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(var 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)},_proto.calculateLocalInertia=function(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target},_proto.volume=function(){return Number.MAX_VALUE},_proto.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)},_proto.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))).length()},_proto.setHeightsFromImage=function(image,scale){var x=scale.x,z=scale.z,y=scale.y,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(x)/imageData.width;for(var i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)},OctreeNode}()),halfDiagonal=new Vec3,tmpAABB$1=new AABB,Trimesh=function(_Shape){function Trimesh(vertices,indices){var _this;return(_this=_Shape.call(this,{type:Shape.types.TRIMESH})||this).vertices=new Float32Array(vertices),_this.indices=new Int16Array(indices),_this.normals=new Float32Array(indices.length),_this.aabb=new AABB,_this.edges=null,_this.scale=new Vec3(1,1,1),_this.tree=new Octree,_this.updateEdges(),_this.updateNormals(),_this.updateAABB(),_this.updateBoundingSphereRadius(),_this.updateTree(),_this}_inheritsLoose(Trimesh,_Shape);var _proto=Trimesh.prototype;return _proto.updateTree=function(){var tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);var scale=this.scale;tree.aabb.lowerBound.x*=1/scale.x,tree.aabb.lowerBound.y*=1/scale.y,tree.aabb.lowerBound.z*=1/scale.z,tree.aabb.upperBound.x*=1/scale.x,tree.aabb.upperBound.y*=1/scale.y,tree.aabb.upperBound.z*=1/scale.z;for(var triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c],i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},_proto.updateAABB=function(){this.computeLocalAABB(this.aabb)},_proto.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.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)},_proto.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)},_proto.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh}(Shape),computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3;Trimesh.computeNormal=function(va,vb,vc,target){vb.vsub(va,ab),vc.vsub(vb,cb),cb.cross(ab,target),target.isZero()||target.normalize()};var va=new Vec3,vb=new Vec3,vc=new Vec3,cli_aabb=new AABB,computeLocalAABB_worldVert=new Vec3,calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){void 0===radius&&(radius=1),void 0===tube&&(tube=.5),void 0===radialSegments&&(radialSegments=8),void 0===tubularSegments&&(tubularSegments=6),void 0===arc&&(arc=2*Math.PI);for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(var 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(var _j=1;_j<=radialSegments;_j++)for(var _i2=1;_i2<=tubularSegments;_i2++){var a=(tubularSegments+1)*_j+_i2-1,b=(tubularSegments+1)*(_j-1)+_i2-1,c=(tubularSegments+1)*(_j-1)+_i2,d=(tubularSegments+1)*_j+_i2;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)};var Solver=function(){function Solver(){this.equations=[]}var _proto=Solver.prototype;return _proto.solve=function(dt,world){return 0},_proto.addEquation=function(eq){eq.enabled&&this.equations.push(eq)},_proto.removeEquation=function(eq){var eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)},_proto.removeAllEquations=function(){this.equations.length=0},Solver}(),GSSolver=function(_Solver){function GSSolver(){var _this;return(_this=_Solver.call(this)||this).iterations=10,_this.tolerance=1e-7,_this}return _inheritsLoose(GSSolver,_Solver),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(var 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(var _i=0;_i!==Neq;_i++){var c=equations[_i];lambda[_i]=0,Bs[_i]=c.computeB(h),invCs[_i]=1/c.computeC()}if(0!==Neq){for(var _i2=0;_i2!==Nbodies;_i2++){var b=bodies[_i2],vlambda=b.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.minForce?deltalambda=_c.minForce-lambdaj:lambdaj+deltalambda>_c.maxForce&&(deltalambda=_c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,_c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTotsize;)objects.pop();for(;objects.length=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},_proto.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},_proto.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]).bi!==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)}},_proto.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$3,xj=tmpVec2$3,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){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){var _dist=Math.abs(dot-h-R);if((null===side_distance||_distsi.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.scale(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)}},_proto.sphereConvex=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){var v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);for(var normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius,found=!1,i=0;i!==verts.length;i++){var v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);var sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){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;var _r3=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,_r3.ri),worldNormal.negate(_r3.ni);var penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,_r3.rj),_r3.rj.vadd(penetrationSpherePoint,_r3.rj),_r3.rj.vadd(penetrationVec2,_r3.rj),_r3.rj.vadd(xj,_r3.rj),_r3.rj.vsub(bj.position,_r3.rj),_r3.ri.vadd(xi,_r3.ri),_r3.ri.vsub(bi.position,_r3.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(_r3),this.createFrictionEquationsFromContact(_r3,this.frictionResult);for(var _j2=0,Nfaceverts=faceVerts.length;_j2!==Nfaceverts;_j2++)v3pool.release(faceVerts[_j2]);return}for(var _j3=0;_j3!==face.length;_j3++){var v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(_j3+1)%face.length]],v1),qj.vmult(verts[face[(_j3+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.scale(dot,p),p.vadd(v1,p);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.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(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}},_proto.boxHeightfield=function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){return si.convexPolyhedronRepresentation.material=si.material,si.convexPolyhedronRepresentation.collisionResponse=si.collisionResponse,this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest)},_proto.convexHeightfield=function(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){var data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);var iMinX=Math.floor((localConvexPos.x-radius)/w)-1,iMaxX=Math.ceil((localConvexPos.x+radius)/w)+1,iMinY=Math.floor((localConvexPos.y-radius)/w)-1,iMaxY=Math.ceil((localConvexPos.y+radius)/w)+1;if(!(iMaxX<0||iMaxY<0||iMinX>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+radius0&&positionAlongEdgeB<0)if(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),tmp.distanceTo(localSpherePos)0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}var box_to_sphere=new Vec3,sphereBox_ns=new Vec3,sphereBox_ns1=new Vec3,sphereBox_ns2=new Vec3,sphereBox_sides=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3],sphereBox_sphere_to_corner=new Vec3,sphereBox_side_ns=new Vec3,sphereBox_side_ns1=new Vec3,sphereBox_side_ns2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereBox]=Narrowphase.prototype.sphereBox;var convex_to_sphere=new Vec3,sphereConvex_edge=new Vec3,sphereConvex_edgeUnit=new Vec3,sphereConvex_sphereToCorner=new Vec3,sphereConvex_worldCorner=new Vec3,sphereConvex_worldNormal=new Vec3,sphereConvex_worldPoint=new Vec3,sphereConvex_worldSpherePointClosestToPlane=new Vec3,sphereConvex_penetrationVec=new Vec3,sphereConvex_sphereToWorldPoint=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereConvex]=Narrowphase.prototype.sphereConvex;new Vec3,new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeBox]=Narrowphase.prototype.planeBox;var planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeConvex]=Narrowphase.prototype.planeConvex;var convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexConvex]=Narrowphase.prototype.convexConvex;var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[COLLISION_TYPES.planeParticle]=Narrowphase.prototype.planeParticle;var particleSphere_normal=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereParticle]=Narrowphase.prototype.sphereParticle;var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[COLLISION_TYPES.convexParticle]=Narrowphase.prototype.convexParticle,Narrowphase.prototype[COLLISION_TYPES.boxHeightfield]=Narrowphase.prototype.boxHeightfield;var convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0];Narrowphase.prototype[COLLISION_TYPES.convexHeightfield]=Narrowphase.prototype.convexHeightfield;var sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;Narrowphase.prototype[COLLISION_TYPES.sphereHeightfield]=Narrowphase.prototype.sphereHeightfield;var OverlapKeeper=function(){function OverlapKeeper(){this.current=[],this.previous=[]}var _proto=OverlapKeeper.prototype;return _proto.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}},_proto.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},_proto.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(var _i=0;_ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}},OverlapKeeper}();function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}var TupleDictionary=function(){function TupleDictionary(){this.data={keys:[]}}var _proto=TupleDictionary.prototype;return _proto.get=function(i,j){if(i>j){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},_proto.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},_proto.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;){delete data[keys.pop()]}},TupleDictionary}(),World=function(_EventTarget){function World(options){var _this;return void 0===options&&(options={}),(_this=_EventTarget.call(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.hasActiveBodies=!1,_this.solver=void 0!==options.solver?options.solver:new GSSolver,_this.constraints=[],_this.narrowphase=new Narrowphase(_assertThisInitialized(_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(_assertThisInitialized(_this)),_this}_inheritsLoose(World,_EventTarget);var _proto=World.prototype;return _proto.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},_proto.numObjects=function(){return this.bodies.length},_proto.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},_proto.addConstraint=function(c){this.constraints.push(c)},_proto.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},_proto.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},_proto.raycastAll=function(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay$1.intersectWorld(this,options)},_proto.raycastAny=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.raycastClosest=function(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay$1.intersectWorld(this,options)},_proto.addBody=function(body){this.bodies.includes(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))},_proto.removeBody=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)}},_proto.getBodyById=function(id){return this.idToBodyMap[id]},_proto.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]);for(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()),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.lengthSquared()+bj.angularVelocity.lengthSquared()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(_bi.wakeUpAfterNarrowphase=!0);if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&_bi.sleepState===Body.AWAKE&&_bi.type!==Body.STATIC)_bi.velocity.lengthSquared()+_bi.angularVelocity.lengthSquared()>=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++){var _bi2=bodies[i];_bi2.wakeUpAfterNarrowphase&&(_bi2.wakeUp(),_bi2.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){var _c2=constraints[i];_c2.update();for(var _j=0,Neq=_c2.equations.length;_j!==Neq;_j++){var eq=_c2.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++){var _bi3=bodies[i];if(_bi3.type&DYNAMIC){var ld=pow(1-_bi3.linearDamping,dt),v=_bi3.velocity;v.scale(ld,v);var av=_bi3.angularVelocity;if(av){var ad=pow(1-_bi3.angularDamping,dt);av.scale(ad,av)}}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++){var _bi4=bodies[i];_bi4.preStep&&_bi4.preStep.call(_bi4)}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 _bi5=bodies[i],postStep=_bi5.postStep;postStep&&postStep.call(_bi5)}var hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){var _bi6=bodies[i];_bi6.sleepTick(this.time),_bi6.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies},_proto.clearForces=function(){for(var bodies=this.bodies,N=bodies.length,i=0;i!==N;i++){var b=bodies[i];b.force,b.torque;b.force.set(0,0,0),b.torque.set(0,0,0)}},World}(EventTarget),tmpRay$1=(new AABB,new Ray);if("undefined"==typeof performance&&(performance={}),!performance.now){var nowOffset=Date.now();performance.timing&&performance.timing.navigationStart&&(nowOffset=performance.timing.navigationStart),performance.now=function(){return Date.now()-nowOffset}}new Vec3;var additions,removals,beginContactEvent,endContactEvent,beginShapeContactEvent,endShapeContactEvent,World_step_postStepEvent={type:"postStep"},World_step_preStepEvent={type:"preStep"},World_step_collideEvent={type:Body.COLLIDE_EVENT_NAME,body:null,contact:null},World_step_oldContacts=[],World_step_frictionEquationPool=[],World_step_p1=[],World_step_p2=[];World.prototype.emitContactEvents=(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},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;i{switch(options.cylinderAxis){case"y":return new Ammo.btCylinderShape(btHalfExtents);case"x":return new Ammo.btCylinderShapeX(btHalfExtents);case"z":return new Ammo.btCylinderShapeZ(btHalfExtents)}return null})();return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createCapsuleShape=function(root,options){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btCapsuleShape(Math.max(x,z),2*y);case"x":return new Ammo.btCapsuleShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btCapsuleShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createConeShape=function(root,options){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(root,_computeBounds(root,options),options.minHalfExtent,options.maxHalfExtent));const{x:x,y:y,z:z}=options.halfExtents,collisionShape=(()=>{switch(options.cylinderAxis){case"y":return new Ammo.btConeShape(Math.max(x,z),2*y);case"x":return new Ammo.btConeShapeX(Math.max(y,z),2*x);case"z":return new Ammo.btConeShapeZ(Math.max(x,y),2*z)}return null})();return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createSphereShape=function(root,options){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(root,options,_computeBounds(root,options)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape},exports.createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HULL,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hull"),null;const bounds=_computeBounds(root,options),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3});const maxVertices=options.hullMaxVertices||1e5;vertexCount>maxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i=100){const shapeHull=new Ammo.btShapeHull(originalHull);shapeHull.buildHull(options.margin),Ammo.destroy(originalHull),collisionShape=new Ammo.btConvexHullShape(Ammo.getPointer(shapeHull.getVertexPointer()),shapeHull.numVertices()),Ammo.destroy(shapeHull)}return Ammo.destroy(btVertex),_finishCollisionShape(collisionShape,options,_computeScale(root,options)),collisionShape}}(),exports.createHACDShapes=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options){if(options.type=TYPE.HACD,_setOptions(options),options.fit===FIT.MANUAL)return console.warn("cannot use fit: manual with type: hacd"),[];if(!Ammo.hasOwnProperty("HACD"))return console.warn("HACD unavailable in included build of Ammo.js. Visit https://github.com/mozillareality/ammo.js for the latest version."),[];const bounds=_computeBounds(root),scale=_computeScale(root,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5),_iterateGeometries(root,options,geo=>{vertexCount+=geo.attributes.position.array.length/3,geo.index?triCount+=geo.index.array.length/3:triCount+=geo.attributes.position.array.length/9});const hacd=new Ammo.HACD;options.hasOwnProperty("compacityWeight")&&hacd.SetCompacityWeight(options.compacityWeight),options.hasOwnProperty("volumeWeight")&&hacd.SetVolumeWeight(options.volumeWeight),options.hasOwnProperty("nClusters")&&hacd.SetNClusters(options.nClusters),options.hasOwnProperty("nVerticesPerCH")&&hacd.SetNVerticesPerCH(options.nVerticesPerCH),options.hasOwnProperty("concavity")&&hacd.SetConcavity(options.concavity);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);hacd.SetPoints(points),hacd.SetTriangles(triangles),hacd.SetNPoints(vertexCount),hacd.SetNTriangles(triCount);const pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{vertexCount+=geo.attributes.position.count,geo.index?triCount+=geo.index.count/3:triCount+=geo.attributes.position.count/3});const vhacd=new Ammo.VHACD,params=new Ammo.Parameters;options.hasOwnProperty("resolution")&¶ms.set_m_resolution(options.resolution),options.hasOwnProperty("depth")&¶ms.set_m_depth(options.depth),options.hasOwnProperty("concavity")&¶ms.set_m_concavity(options.concavity),options.hasOwnProperty("planeDownsampling")&¶ms.set_m_planeDownsampling(options.planeDownsampling),options.hasOwnProperty("convexhullDownsampling")&¶ms.set_m_convexhullDownsampling(options.convexhullDownsampling),options.hasOwnProperty("alpha")&¶ms.set_m_alpha(options.alpha),options.hasOwnProperty("beta")&¶ms.set_m_beta(options.beta),options.hasOwnProperty("gamma")&¶ms.set_m_gamma(options.gamma),options.hasOwnProperty("pca")&¶ms.set_m_pca(options.pca),options.hasOwnProperty("mode")&¶ms.set_m_mode(options.mode),options.hasOwnProperty("maxNumVerticesPerCH")&¶ms.set_m_maxNumVerticesPerCH(options.maxNumVerticesPerCH),options.hasOwnProperty("minVolumePerCH")&¶ms.set_m_minVolumePerCH(options.minVolumePerCH),options.hasOwnProperty("convexhullApproximation")&¶ms.set_m_convexhullApproximation(options.convexhullApproximation),options.hasOwnProperty("oclAcceleration")&¶ms.set_m_oclAcceleration(options.oclAcceleration);const points=Ammo._malloc(3*vertexCount*8),triangles=Ammo._malloc(3*triCount*4);let pptr=points/8,tptr=triangles/4;_iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array,indices=geo.index?geo.index.array:null;for(let i=0;i{const components=geo.attributes.position.array;if(geo.index)for(let i=0;i{switch(options.heightDataType){case"short":return Ammo.PHY_SHORT;case"float":default:return Ammo.PHY_FLOAT}})(),flipQuadEdges=!options.hasOwnProperty("flipQuadEdges")||options.flipQuadEdges,heightStickLength=heightfieldData.length,heightStickWidth=heightStickLength>0?heightfieldData[0].length:0,data=Ammo._malloc(heightStickLength*heightStickWidth*4),ptr=data/4;let minHeight=Number.POSITIVE_INFINITY,maxHeight=Number.NEGATIVE_INFINITY,index=0;for(let l=0;l{for(let res of collisionShape.resources||[])Ammo.destroy(res);collisionShape.heightfieldData&&Ammo._free(collisionShape.heightfieldData),Ammo.destroy(collisionShape)});const localTransform=new Ammo.btTransform,rotation=new Ammo.btQuaternion;if(localTransform.setIdentity(),localTransform.getOrigin().setValue(options.offset.x,options.offset.y,options.offset.z),rotation.setValue(options.orientation.x,options.orientation.y,options.orientation.z,options.orientation.w),localTransform.setRotation(rotation),Ammo.destroy(rotation),scale){const localScale=new Ammo.btVector3(scale.x,scale.y,scale.z);collisionShape.setLocalScaling(localScale),Ammo.destroy(localScale)}collisionShape.localTransform=localTransform},_iterateGeometries=function(){const transform=new THREE.Matrix4,inverse=new THREE.Matrix4,bufferGeometry=new THREE.BufferGeometry;return function(root,options,cb){inverse.getInverse(root.matrixWorld),root.traverse(mesh=>{!mesh.isMesh||THREE.Sky&&mesh.__proto__==THREE.Sky.prototype||!(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)||(mesh===root?transform.identity():(hasUpdateMatricesFunction&&mesh.updateMatrices(),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry:bufferGeometry.fromGeometry(mesh.geometry),transform))})}}(),_computeScale=function(root,options){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&scale.setFromMatrixScale(root.matrixWorld),scale},_computeRadius=function(){const v=new THREE.Vector3,center=new THREE.Vector3;return function(root,options,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateGeometries(root,options,(geo,transform)=>{const components=geo.attributes.position.array;for(let i=0;i{const components=geo.attributes.position.array;for(let i=0;imaxX&&(maxX=v.x),v.y>maxY&&(maxY=v.y),v.z>maxZ&&(maxZ=v.z)}),bounds.min.set(minX,minY,minZ),bounds.max.set(maxX,maxY,maxZ),bounds}}()},{}],6:[function(require,module,exports){(function(global){var cannonEs=require("cannon-es"),three="undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null,ConvexHull=function(){var line3,plane,closestPoint,triangle,Visible=0,v1=new three.Vector3;function ConvexHull(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new VertexList,this.unassigned=new VertexList,this.vertices=[]}function Face(){this.normal=new three.Vector3,this.midpoint=new three.Vector3,this.area=0,this.constant=0,this.outside=null,this.mark=Visible,this.edge=null}function HalfEdge(vertex,face){this.vertex=vertex,this.prev=null,this.next=null,this.twin=null,this.face=face}function VertexNode(point){this.point=point,this.prev=null,this.next=null,this.face=null}function VertexList(){this.head=null,this.tail=null}return Object.assign(ConvexHull.prototype,{setFromPoints:function(points){!0!==Array.isArray(points)&&console.error("THREE.ConvexHull: Points parameter is not an array."),points.length<4&&console.error("THREE.ConvexHull: The algorithm needs at least four points."),this.makeEmpty();for(var i=0,l=points.length;ithis.tolerance)return!1}return!0},intersectRay:function(ray,target){for(var faces=this.faces,tNear=-1/0,tFar=1/0,i=0,l=faces.length;i0&&vD>=0)return null;var t=0!==vD?-vN/vD:0;if(!(t<=0)&&(vD>0?tFar=Math.min(t,tFar):tNear=Math.max(t,tNear),tNear>tFar))return null}return tNear!==-1/0?ray.at(tNear,target):ray.at(tFar,target),target},intersectsRay:function(ray){return null!==this.intersectRay(ray,v1)},makeEmpty:function(){return this.faces=[],this.vertices=[],this},addVertexToFace:function(vertex,face){return vertex.face=face,null===face.outside?this.assigned.append(vertex):this.assigned.insertBefore(face.outside,vertex),face.outside=vertex,this},removeVertexFromFace:function(vertex,face){return vertex===face.outside&&(null!==vertex.next&&vertex.next.face===face?face.outside=vertex.next:face.outside=null),this.assigned.remove(vertex),this},removeAllVerticesFromFace:function(face){if(null!==face.outside){for(var start=face.outside,end=face.outside;null!==end.next&&end.next.face===face;)end=end.next;return this.assigned.removeSubList(start,end),start.prev=end.next=null,face.outside=null,start}},deleteFaceVertices:function(face,absorbingFace){var faceVertices=this.removeAllVerticesFromFace(face);if(void 0!==faceVertices)if(void 0===absorbingFace)this.unassigned.appendChain(faceVertices);else{var vertex=faceVertices;do{var nextVertex=vertex.next;absorbingFace.distanceToPoint(vertex.point)>this.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unassigned.append(vertex),vertex=nextVertex}while(null!==vertex)}return this},resolveUnassignedPoints:function(newFaces){if(!1===this.unassigned.isEmpty()){var vertex=this.unassigned.first();do{for(var nextVertex=vertex.next,maxDistance=this.tolerance,maxFace=null,i=0;imaxDistance&&(maxDistance=distance,maxFace=face),maxDistance>1e3*this.tolerance)break}}null!==maxFace&&this.addVertexToFace(vertex,maxFace),vertex=nextVertex}while(null!==vertex)}return this},computeExtremes:function(){var i,l,j,min=new three.Vector3,max=new three.Vector3,minVertices=[],maxVertices=[];for(i=0;i<3;i++)minVertices[i]=maxVertices[i]=this.vertices[0];for(min.copy(this.vertices[0].point),max.copy(this.vertices[0].point),i=0,l=this.vertices.length;imax.getComponent(j)&&(max.setComponent(j,point.getComponent(j)),maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min.x),Math.abs(max.x))+Math.max(Math.abs(min.y),Math.abs(max.y))+Math.max(Math.abs(min.z),Math.abs(max.z))),{min:minVertices,max:maxVertices}},computeInitialHull:function(){void 0===line3&&(line3=new three.Line3,plane=new three.Plane,closestPoint=new three.Vector3);var vertex,v0,v1,v2,v3,i,l,j,distance,vertices=this.vertices,extremes=this.computeExtremes(),min=extremes.min,max=extremes.max,maxDistance=0,index=0;for(i=0;i<3;i++)(distance=max[i].point.getComponent(i)-min[i].point.getComponent(i))>maxDistance&&(maxDistance=distance,index=i);for(v0=min[index],v1=max[index],maxDistance=0,line3.set(v0.point,v1.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v2=vertex));for(maxDistance=-1,plane.setFromCoplanarPoints(v0.point,v1.point,v2.point),i=0,l=this.vertices.length;imaxDistance&&(maxDistance=distance,v3=vertex);var faces=[];if(plane.distanceToPoint(v3.point)<0)for(faces.push(Face.create(v0,v1,v2),Face.create(v3,v1,v0),Face.create(v3,v2,v1),Face.create(v3,v0,v2)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge(j)),faces[i+1].getEdge(1).setTwin(faces[j+1].getEdge(0));else for(faces.push(Face.create(v0,v2,v1),Face.create(v3,v0,v1),Face.create(v3,v1,v2),Face.create(v3,v2,v0)),i=0;i<3;i++)j=(i+1)%3,faces[i+1].getEdge(2).setTwin(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setTwin(faces[j+1].getEdge(1));for(i=0;i<4;i++)this.faces.push(faces[i]);for(i=0,l=vertices.length;imaxDistance&&(maxDistance=distance,maxFace=this.faces[j]);null!==maxFace&&this.addVertexToFace(vertex,maxFace)}return this},reindexFaces:function(){for(var activeFaces=[],i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex),vertex=vertex.next}while(null!==vertex&&vertex.face===eyeFace);return eyeVertex}},computeHorizon:function(eyePoint,crossEdge,face,horizon){var edge;this.deleteFaceVertices(face),face.mark=1,edge=null===crossEdge?crossEdge=face.getEdge(0):crossEdge.next;do{var twinEdge=edge.twin,oppositeFace=twinEdge.face;oppositeFace.mark===Visible&&(oppositeFace.distanceToPoint(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,twinEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge);return this},addAdjoiningFace:function(eyeVertex,horizonEdge){var face=Face.create(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setTwin(horizonEdge.twin),face.getEdge(0)},addNewFaces:function(eyeVertex,horizon){this.newFaces=[];for(var firstSideEdge=null,previousSideEdge=null,i=0;i0;)edge=edge.next,i--;for(;i<0;)edge=edge.prev,i++;return edge},compute:function(){void 0===triangle&&(triangle=new three.Triangle);var a=this.edge.tail(),b=this.edge.head(),c=this.edge.next.head();return triangle.set(a.point,b.point,c.point),triangle.getNormal(this.normal),triangle.getMidpoint(this.midpoint),this.area=triangle.getArea(),this.constant=this.normal.dot(this.midpoint),this},distanceToPoint:function(point){return this.normal.dot(point)-this.constant}}),Object.assign(HalfEdge.prototype,{head:function(){return this.vertex},tail:function(){return this.prev?this.prev.vertex:null},length:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceTo(head.point):-1},lengthSquared:function(){var head=this.head(),tail=this.tail();return null!==tail?tail.point.distanceToSquared(head.point):-1},setTwin:function(edge){return this.twin=edge,edge.twin=this,this}}),Object.assign(VertexList.prototype,{first:function(){return this.head},last:function(){return this.tail},clear:function(){return this.head=this.tail=null,this},insertBefore:function(target,vertex){return vertex.prev=target.prev,vertex.next=target,null===vertex.prev?this.head=vertex:vertex.prev.next=vertex,target.prev=vertex,this},insertAfter:function(target,vertex){return vertex.prev=target,vertex.next=target.next,null===vertex.next?this.tail=vertex:vertex.next.prev=vertex,target.next=vertex,this},append:function(vertex){return null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail,vertex.next=null,this.tail=vertex,this},appendChain:function(vertex){for(null===this.head?this.head=vertex:this.tail.next=vertex,vertex.prev=this.tail;null!==vertex.next;)vertex=vertex.next;return this.tail=vertex,this},remove:function(vertex){return null===vertex.prev?this.head=vertex.next:vertex.prev.next=vertex.next,null===vertex.next?this.tail=vertex.prev:vertex.next.prev=vertex.prev,this},removeSubList:function(a,b){return null===a.prev?this.head=b.next:a.prev.next=b.next,null===b.next?this.tail=a.prev:b.next.prev=a.prev,this},isEmpty:function(){return null===this.head}}),ConvexHull}();const _v1=new three.Vector3,_v2=new three.Vector3,_q1=new three.Quaternion;function getGeometry(object){const meshes=function(object){const meshes=[];return object.traverse(function(o){o.isMesh&&meshes.push(o)}),meshes}(object);if(0===meshes.length)return null;if(1===meshes.length)return normalizeGeometry(meshes[0]);let mesh;const geometries=[];for(;mesh=meshes.pop();)geometries.push(simplifyGeometry(normalizeGeometry(mesh)));return function(geometries){let vertexCount=0;for(let i=0;i{this.loadedEventFired=!0},{once:!0}),this.system.initialized&&this.loadedEventFired&&this.initBody()},initBody:function(){const pos=new THREE.Vector3,quat=new THREE.Quaternion;new THREE.Box3;return function(){const el=this.el,data=this.data;this.localScaling=new Ammo.btVector3;const obj=this.el.object3D;obj.getWorldPosition(pos),obj.getWorldQuaternion(quat),this.prevScale=new THREE.Vector3(1,1,1),this.prevNumChildShapes=0,this.msTransform=new Ammo.btTransform,this.msTransform.setIdentity(),this.rotation=new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w),this.msTransform.getOrigin().setValue(pos.x,pos.y,pos.z),this.msTransform.setRotation(this.rotation),this.motionState=new Ammo.btDefaultMotionState(this.msTransform),this.localInertia=new Ammo.btVector3(0,0,0),this.compoundShape=new Ammo.btCompoundShape(!0),this.rbInfo=new Ammo.btRigidBodyConstructionInfo(data.mass,this.motionState,this.compoundShape,this.localInertia),this.body=new Ammo.btRigidBody(this.rbInfo),this.body.setActivationState(ACTIVATION_STATES.indexOf(data.activationState)+1),this.body.setSleepingThresholds(data.linearSleepingThreshold,data.angularSleepingThreshold),this.body.setDamping(data.linearDamping,data.angularDamping);const angularFactor=new Ammo.btVector3(data.angularFactor.x,data.angularFactor.y,data.angularFactor.z);this.body.setAngularFactor(angularFactor),Ammo.destroy(angularFactor);const gravity=new Ammo.btVector3(data.gravity.x,data.gravity.y,data.gravity.z);almostEqualsBtVector3(.001,gravity,this.system.driver.physicsWorld.getGravity())||(this.body.setGravity(gravity),this.body.setFlags(RIGID_BODY_FLAGS_DISABLE_WORLD_GRAVITY)),Ammo.destroy(gravity),this.updateCollisionFlags(),this.el.body=this.body,this.body.el=el,this.isLoaded=!0,this.el.emit("body-loaded",{body:this.el.body}),this._addToSystem()}}(),tick:function(){this.system.initialized&&!this.isLoaded&&this.loadedEventFired&&this.initBody()},_updateShapes:function(){const needsPolyhedralInitialization=[SHAPE.HULL,SHAPE.HACD,SHAPE.VHACD];return function(){let updated=!1;const obj=this.el.object3D;if(this.data.scaleAutoUpdate&&this.prevScale&&!almostEqualsVector3(.001,obj.scale,this.prevScale)&&(this.prevScale.copy(obj.scale),updated=!0,this.localScaling.setValue(this.prevScale.x,this.prevScale.y,this.prevScale.z),this.compoundShape.setLocalScaling(this.localScaling)),this.shapeComponentsChanged){this.shapeComponentsChanged=!1,updated=!0;for(let i=0;i0;){const collisionShape=this.collisionShapes.pop();collisionShape.destroy(),Ammo.destroy(collisionShape.localTransform)}}};module.exports.definition=AmmoShape,module.exports.Component=AFRAME.registerComponent("ammo-shape",AmmoShape)},{"../../constants":19,"three-to-ammo":5}],17:[function(require,module,exports){var CANNON=require("cannon-es"),Shape={schema:{shape:{default:"box",oneOf:["box","sphere","cylinder"]},offset:{type:"vec3",default:{x:0,y:0,z:0}},orientation:{type:"vec4",default:{x:0,y:0,z:0,w:1}},radius:{type:"number",default:1,if:{shape:["sphere"]}},halfExtents:{type:"vec3",default:{x:.5,y:.5,z:.5},if:{shape:["box"]}},radiusTop:{type:"number",default:1,if:{shape:["cylinder"]}},radiusBottom:{type:"number",default:1,if:{shape:["cylinder"]}},height:{type:"number",default:1,if:{shape:["cylinder"]}},numSegments:{type:"int",default:8,if:{shape:["cylinder"]}}},multiple:!0,init:function(){this.el.sceneEl.hasLoaded?this.initShape():this.el.sceneEl.addEventListener("loaded",this.initShape.bind(this))},initShape:function(){this.bodyEl=this.el;for(var bodyType=this._findType(this.bodyEl),data=this.data;!bodyType&&this.bodyEl.parentNode!=this.el.sceneEl;)this.bodyEl=this.bodyEl.parentNode,bodyType=this._findType(this.bodyEl);if(bodyType){var shape,offset,orientation,scale=new THREE.Vector3;switch(this.bodyEl.object3D.getWorldScale(scale),data.hasOwnProperty("offset")&&(offset=new CANNON.Vec3(data.offset.x*scale.x,data.offset.y*scale.y,data.offset.z*scale.z)),data.hasOwnProperty("orientation")&&(orientation=new CANNON.Quaternion).copy(data.orientation),data.shape){case"sphere":shape=new CANNON.Sphere(data.radius*scale.x);break;case"box":var halfExtents=new CANNON.Vec3(data.halfExtents.x*scale.x,data.halfExtents.y*scale.y,data.halfExtents.z*scale.z);shape=new CANNON.Box(halfExtents);break;case"cylinder":shape=new CANNON.Cylinder(data.radiusTop*scale.x,data.radiusBottom*scale.x,data.height*scale.y,data.numSegments);var quat=new CANNON.Quaternion;quat.setFromEuler(90*THREE.Math.DEG2RAD,0,0,"XYZ").normalize(),orientation.mult(quat,orientation);break;default:return void console.warn(data.shape+" shape not supported")}this.bodyEl.body?this.bodyEl.components[bodyType].addShape(shape,offset,orientation):this.bodyEl.addEventListener("body-loaded",function(){this.bodyEl.components[bodyType].addShape(shape,offset,orientation)},{once:!0})}else console.warn("body not found")},_findType:function(el){return el.hasAttribute("body")?"body":el.hasAttribute("dynamic-body")?"dynamic-body":el.hasAttribute("static-body")?"static-body":null},remove:function(){this.bodyEl.parentNode&&console.warn("removing shape component not currently supported")}};module.exports.definition=Shape,module.exports.Component=AFRAME.registerComponent("shape",Shape)},{"cannon-es":4}],18:[function(require,module,exports){var CANNON=require("cannon-es");module.exports=AFRAME.registerComponent("spring",{multiple:!0,schema:{target:{type:"selector"},restLength:{default:1,min:0},stiffness:{default:100,min:0},damping:{default:1,min:0},localAnchorA:{type:"vec3",default:{x:0,y:0,z:0}},localAnchorB:{type:"vec3",default:{x:0,y:0,z:0}}},init:function(){this.system=this.el.sceneEl.systems.physics,this.system.addComponent(this),this.isActive=!0,this.spring=null},update:function(oldData){var el=this.el,data=this.data;data.target?el.body&&data.target.body?(this.createSpring(),this.updateSpring(oldData)):(el.body?data.target:el).addEventListener("body-loaded",this.update.bind(this,{})):console.warn("Spring: invalid target specified.")},updateSpring:function(oldData){if(this.spring){var data=this.data,spring=this.spring;Object.keys(data).forEach(function(attr){if(data[attr]!==oldData[attr]){if("target"===attr)return void(spring.bodyB=data.target.body);spring[attr]=data[attr]}})}else console.warn("Spring: Component attempted to change spring before its created. No changes made.")},createSpring:function(){this.spring||(this.spring=new CANNON.Spring(this.el.body))},step:function(t,dt){return this.spring&&this.isActive?this.spring.applyForce():void 0},play:function(){this.isActive=!0},pause:function(){this.isActive=!1},remove:function(){this.spring&&delete this.spring,this.spring=null}})},{"cannon-es":4}],19:[function(require,module,exports){module.exports={GRAVITY:-9.8,MAX_INTERVAL:4/60,ITERATIONS:10,CONTACT_MATERIAL:{friction:.01,restitution:.3,contactEquationStiffness:1e8,contactEquationRelaxation:3,frictionEquationStiffness:1e8,frictionEquationRegularization:3},ACTIVATION_STATE:{ACTIVE_TAG:"active",ISLAND_SLEEPING:"islandSleeping",WANTS_DEACTIVATION:"wantsDeactivation",DISABLE_DEACTIVATION:"disableDeactivation",DISABLE_SIMULATION:"disableSimulation"},COLLISION_FLAG:{STATIC_OBJECT:1,KINEMATIC_OBJECT:2,NO_CONTACT_RESPONSE:4,CUSTOM_MATERIAL_CALLBACK:8,CHARACTER_OBJECT:16,DISABLE_VISUALIZE_OBJECT:32,DISABLE_SPU_COLLISION_PROCESSING:64},TYPE:{STATIC:"static",DYNAMIC:"dynamic",KINEMATIC:"kinematic"},SHAPE:{BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"},FIT:{ALL:"all",MANUAL:"manual"},CONSTRAINT:{LOCK:"lock",FIXED:"fixed",SPRING:"spring",SLIDER:"slider",HINGE:"hinge",CONE_TWIST:"coneTwist",POINT_TO_POINT:"pointToPoint"}}},{}],20:[function(require,module,exports){const Driver=require("./driver");"undefined"!=typeof window&&(window.AmmoModule=window.Ammo,window.Ammo=null);function AmmoDriver(){this.collisionConfiguration=null,this.dispatcher=null,this.broadphase=null,this.solver=null,this.physicsWorld=null,this.debugDrawer=null,this.els=new Map,this.eventListeners=[],this.collisions=new Map,this.collisionKeys=[],this.currentCollisions=new Map}AmmoDriver.prototype=new Driver,AmmoDriver.prototype.constructor=AmmoDriver,module.exports=AmmoDriver,AmmoDriver.prototype.init=function(worldConfig){return new Promise(resolve=>{AmmoModule().then(result=>{Ammo=result,this.epsilon=worldConfig.epsilon||1e-5,this.debugDrawMode=worldConfig.debugDrawMode||THREE.AmmoDebugConstants.NoDebug,this.maxSubSteps=worldConfig.maxSubSteps||4,this.fixedTimeStep=worldConfig.fixedTimeStep||1/60,this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.broadphase=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.physicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.broadphase,this.solver,this.collisionConfiguration),this.physicsWorld.setForceUpdateAllAabbs(!1),this.physicsWorld.setGravity(new Ammo.btVector3(0,worldConfig.hasOwnProperty("gravity")?worldConfig.gravity:-9.8,0)),this.physicsWorld.getSolverInfo().set_m_numIterations(worldConfig.solverIterations),resolve()})})},AmmoDriver.prototype.addBody=function(body,group,mask){this.physicsWorld.addRigidBody(body,group,mask),this.els.set(Ammo.getPointer(body),body.el)},AmmoDriver.prototype.removeBody=function(body){this.physicsWorld.removeRigidBody(body),this.removeEventListener(body);const bodyptr=Ammo.getPointer(body);this.els.delete(bodyptr),this.collisions.delete(bodyptr),this.collisionKeys.splice(this.collisionKeys.indexOf(bodyptr),1),this.currentCollisions.delete(bodyptr)},AmmoDriver.prototype.updateBody=function(body){this.els.has(Ammo.getPointer(body))&&this.physicsWorld.updateSingleAabb(body)},AmmoDriver.prototype.step=function(deltaTime){this.physicsWorld.stepSimulation(deltaTime,this.maxSubSteps,this.fixedTimeStep);const numManifolds=this.dispatcher.getNumManifolds();for(let i=0;i=0;j--){const body1ptr=body1ptrs[j];this.currentCollisions.get(body0ptr).has(body1ptr)||(-1!==this.eventListeners.indexOf(body0ptr)&&this.els.get(body0ptr).emit("collideend",{targetEl:this.els.get(body1ptr)}),-1!==this.eventListeners.indexOf(body1ptr)&&this.els.get(body1ptr).emit("collideend",{targetEl:this.els.get(body0ptr)}),body1ptrs.splice(j,1))}this.currentCollisions.get(body0ptr).clear()}this.debugDrawer&&this.debugDrawer.update()},AmmoDriver.prototype.addConstraint=function(constraint){this.physicsWorld.addConstraint(constraint,!1)},AmmoDriver.prototype.removeConstraint=function(constraint){this.physicsWorld.removeConstraint(constraint)},AmmoDriver.prototype.addEventListener=function(body){this.eventListeners.push(Ammo.getPointer(body))},AmmoDriver.prototype.removeEventListener=function(body){const ptr=Ammo.getPointer(body);-1!==this.eventListeners.indexOf(ptr)&&this.eventListeners.splice(this.eventListeners.indexOf(ptr),1)},AmmoDriver.prototype.destroy=function(){Ammo.destroy(this.collisionConfiguration),Ammo.destroy(this.dispatcher),Ammo.destroy(this.broadphase),Ammo.destroy(this.solver),Ammo.destroy(this.physicsWorld),Ammo.destroy(this.debugDrawer)},AmmoDriver.prototype.getDebugDrawer=function(scene,options){return this.debugDrawer||((options=options||{}).debugDrawMode=options.debugDrawMode||this.debugDrawMode,this.debugDrawer=new THREE.AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21}],21:[function(require,module,exports){function Driver(){}function abstractMethod(){throw new Error("Method not implemented.")}module.exports=Driver,Driver.prototype.init=abstractMethod,Driver.prototype.step=abstractMethod,Driver.prototype.destroy=abstractMethod,Driver.prototype.addBody=abstractMethod,Driver.prototype.removeBody=abstractMethod,Driver.prototype.applyBodyMethod=abstractMethod,Driver.prototype.updateBodyProperties=abstractMethod,Driver.prototype.addMaterial=abstractMethod,Driver.prototype.addContactMaterial=abstractMethod,Driver.prototype.addConstraint=abstractMethod,Driver.prototype.removeConstraint=abstractMethod,Driver.prototype.getContacts=abstractMethod},{}],22:[function(require,module,exports){module.exports={INIT:"init",STEP:"step",ADD_BODY:"add-body",REMOVE_BODY:"remove-body",APPLY_BODY_METHOD:"apply-body-method",UPDATE_BODY_PROPERTIES:"update-body-properties",ADD_MATERIAL:"add-material",ADD_CONTACT_MATERIAL:"add-contact-material",ADD_CONSTRAINT:"add-constraint",REMOVE_CONSTRAINT:"remove-constraint",COLLIDE:"collide"}},{}],23:[function(require,module,exports){var CANNON=require("cannon-es"),Driver=require("./driver");function LocalDriver(){this.world=null,this.materials={},this.contactMaterial=null}LocalDriver.prototype=new Driver,LocalDriver.prototype.constructor=LocalDriver,module.exports=LocalDriver,LocalDriver.prototype.init=function(worldConfig){var world=new CANNON.World;world.quatNormalizeSkip=worldConfig.quatNormalizeSkip,world.quatNormalizeFast=worldConfig.quatNormalizeFast,world.solver.iterations=worldConfig.solverIterations,world.gravity.set(0,worldConfig.gravity,0),world.broadphase=new CANNON.NaiveBroadphase,this.world=world},LocalDriver.prototype.step=function(deltaMS){this.world.step(deltaMS)},LocalDriver.prototype.destroy=function(){delete this.world,delete this.contactMaterial,this.materials={}},LocalDriver.prototype.addBody=function(body){this.world.addBody(body)},LocalDriver.prototype.removeBody=function(body){this.world.removeBody(body)},LocalDriver.prototype.applyBodyMethod=function(body,methodName,args){body["__"+methodName].apply(body,args)},LocalDriver.prototype.updateBodyProperties=function(){},LocalDriver.prototype.getMaterial=function(name){return this.materials[name]},LocalDriver.prototype.addMaterial=function(materialConfig){this.materials[materialConfig.name]=new CANNON.Material(materialConfig),this.materials[materialConfig.name].name=materialConfig.name},LocalDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){var mat1=this.materials[matName1],mat2=this.materials[matName2];this.contactMaterial=new CANNON.ContactMaterial(mat1,mat2,contactMaterialConfig),this.world.addContactMaterial(this.contactMaterial)},LocalDriver.prototype.addConstraint=function(constraint){constraint.type||(constraint instanceof CANNON.LockConstraint?constraint.type="LockConstraint":constraint instanceof CANNON.DistanceConstraint?constraint.type="DistanceConstraint":constraint instanceof CANNON.HingeConstraint?constraint.type="HingeConstraint":constraint instanceof CANNON.ConeTwistConstraint?constraint.type="ConeTwistConstraint":constraint instanceof CANNON.PointToPointConstraint&&(constraint.type="PointToPointConstraint")),this.world.addConstraint(constraint)},LocalDriver.prototype.removeConstraint=function(constraint){this.world.removeConstraint(constraint)},LocalDriver.prototype.getContacts=function(){return this.world.contacts}},{"./driver":21,"cannon-es":4}],24:[function(require,module,exports){var Driver=require("./driver");function NetworkDriver(){throw new Error("[NetworkDriver] Driver not implemented.")}NetworkDriver.prototype=new Driver,NetworkDriver.prototype.constructor=NetworkDriver,module.exports=NetworkDriver},{"./driver":21}],25:[function(require,module,exports){function EventTarget(){this.listeners=[]}module.exports=function(worker){var targetA=new EventTarget,targetB=new EventTarget;return targetA.setTarget(targetB),targetB.setTarget(targetA),worker(targetA),targetB},EventTarget.prototype.setTarget=function(target){this.target=target},EventTarget.prototype.addEventListener=function(type,fn){this.listeners.push(fn)},EventTarget.prototype.dispatchEvent=function(type,event){for(var i=0;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;for(var id in mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize,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){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])}else{if(event.data.type!==Event.COLLIDE)throw new Error("[WorkerDriver] Unexpected message type.");var body=this.bodies[event.data.bodyID],target=this.bodies[event.data.targetID],contact=protocol.deserializeContact(event.data.contact,this.bodies);if(!body._listeners||!body._listeners.collide)return;for(var 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}},{}],30:[function(require,module,exports){var CANNON=require("cannon-es"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};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])}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":29,"cannon-es":4}]},{},[1]); \ No newline at end of file