diff --git a/src/components/README.md b/src/components/README.md index dc13a046d..2ea69a0e1 100644 --- a/src/components/README.md +++ b/src/components/README.md @@ -31,7 +31,7 @@
collision-listener

Listen for collisions, callback on event. -Requires Physics for A-Frame VR

+Requires Physics for A-Frame VR

gesture-detector

Detect multi-finger touch gestures. Publish events accordingly. @@ -43,7 +43,7 @@ Based off 8th Wall's impulse

One physics feature is applying an impulse to an object to set it in motion. This happens in conjunction with an event. -Requires Physics for A-Frame VR

+Requires Physics for A-Frame VR

jitsi-video

Apply a jitsi video to a geometry @@ -222,7 +222,7 @@ Keep track of mouse events and publish corresponding events ## collision-listener Listen for collisions, callback on event. -Requires [Physics for A-Frame VR](https://github.com/n5ro/aframe-physics-system) +Requires [Physics for A-Frame VR](https://github.com/c-frame/aframe-physics-system) **Requires**: module:'aframe-physics-system' @@ -252,7 +252,7 @@ Load new URL when object is clicked One physics feature is applying an impulse to an object to set it in motion. This happens in conjunction with an event. -Requires [Physics for A-Frame VR](https://github.com/n5ro/aframe-physics-system) +Requires [Physics for A-Frame VR](https://github.com/c-frame/aframe-physics-system) **Requires**: module:aframe-physics-system diff --git a/src/components/object/collision-listener.js b/src/components/object/collision-listener.js index f771de08a..a8cdba8bb 100644 --- a/src/components/object/collision-listener.js +++ b/src/components/object/collision-listener.js @@ -10,7 +10,7 @@ /** * Listen for collisions, callback on event. - * Requires [Physics for A-Frame VR]{@link https://github.com/n5ro/aframe-physics-system} + * Requires [Physics for A-Frame VR]{@link https://github.com/c-frame/aframe-physics-system} * @module collision-listener * @requires 'aframe-physics-system' */ diff --git a/src/components/object/impulse.js b/src/components/object/impulse.js index 589c6809f..39fce6ecc 100644 --- a/src/components/object/impulse.js +++ b/src/components/object/impulse.js @@ -11,7 +11,7 @@ /** * One physics feature is applying an impulse to an object to set it in motion. * This happens in conjunction with an event. - * Requires [Physics for A-Frame VR]{@link https://github.com/n5ro/aframe-physics-system} + * Requires [Physics for A-Frame VR]{@link https://github.com/c-frame/aframe-physics-system} * @module impulse * @requires aframe-physics-system * diff --git a/src/systems/core/arena.js b/src/systems/core/arena.js index 3eb80370f..72e6d1839 100644 --- a/src/systems/core/arena.js +++ b/src/systems/core/arena.js @@ -669,7 +669,7 @@ AFRAME.registerSystem('arena-scene', { Object.assign(sceneOptions, options['scene-options']); if (sceneOptions.physics) { - // physics system, build with cannon-js: https://github.com/n5ro/aframe-physics-system + // physics system, build with cannon-js: https://github.com/c-frame/aframe-physics-system import('../vendor/aframe-physics-system.min'); const physicsWait = setInterval(() => { // wait for physics system and static-body component to be registered, needs 15-30 ms diff --git a/src/systems/vendor/aframe-physics-system.min.js b/src/systems/vendor/aframe-physics-system.min.js index 2f0d9ba9b..dfd12b2a7 100644 --- a/src/systems/vendor/aframe-physics-system.min.js +++ b/src/systems/vendor/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){const temp=j;j=i,i=temp}return`${i}-${j}`in this.matrix}set(bi,bj,value){let{id:i}=bi,{id:j}=bj;if(j>i){const temp=j;j=i,i=temp}value?this.matrix[`${i}-${j}`]=!0:delete this.matrix[`${i}-${j}`]}reset(){this.matrix={}}setNumObjects(n){}};class Mat3{constructor(elements){void 0===elements&&(elements=[0,0,0,0,0,0,0,0,0]),this.elements=elements}identity(){const 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}setZero(){const 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}setTrace(vector){const e=this.elements;e[0]=vector.x,e[4]=vector.y,e[8]=vector.z}getTrace(target){void 0===target&&(target=new Vec3);const e=this.elements;return target.x=e[0],target.y=e[4],target.z=e[8],target}vmult(v,target){void 0===target&&(target=new Vec3);const 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}smult(s){for(let i=0;i0){const invN=1/n;this.x*=invN,this.y*=invN,this.z*=invN}else this.x=0,this.y=0,this.z=0;return n}unit(target){void 0===target&&(target=new Vec3);const x=this.x,y=this.y,z=this.z;let 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}length(){const x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)}lengthSquared(){return this.dot(this)}distanceTo(p){const 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))}distanceSquared(p){const 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)}scale(scalar,target){void 0===target&&(target=new Vec3);const x=this.x,y=this.y,z=this.z;return target.x=scalar*x,target.y=scalar*y,target.z=scalar*z,target}vmul(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}addScaledVector(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}dot(vector){return this.x*vector.x+this.y*vector.y+this.z*vector.z}isZero(){return 0===this.x&&0===this.y&&0===this.z}negate(target){return void 0===target&&(target=new Vec3),target.x=-this.x,target.y=-this.y,target.z=-this.z,target}tangents(t1,t2){const norm=this.length();if(norm>0){const n=Vec3_tangents_n,inorm=1/norm;n.set(this.x*inorm,this.y*inorm,this.z*inorm);const 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)}toString(){return`${this.x},${this.y},${this.z}`}toArray(){return[this.x,this.y,this.z]}copy(vector){return this.x=vector.x,this.y=vector.y,this.z=vector.z,this}lerp(vector,t,target){const 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}almostEquals(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)}almostZero(precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x)>precision||Math.abs(this.y)>precision||Math.abs(this.z)>precision)}isAntiparallelTo(vector,precision){return this.negate(antip_neg),antip_neg.almostEquals(vector,precision)}clone(){return new Vec3(this.x,this.y,this.z)}}exports.Vec3=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);const Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3,antip_neg=new Vec3;class AABB{constructor(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)}setFromPoints(points,position,quaternion,skinSize){const l=this.lowerBound,u=this.upperBound,q=quaternion;l.copy(points[0]),q&&q.vmult(l,l),u.copy(l);for(let 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}getCorners(a,b,c,d,e,f,g,h){const 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)}toLocalFrame(frame,target){const 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(let i=0;8!==i;i++){const corner=corners[i];frame.pointToLocal(corner,corner)}return target.setFromPoints(corners)}toWorldFrame(frame,target){const 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(let i=0;8!==i;i++){const corner=corners[i];frame.pointToWorld(corner,corner)}return target.setFromPoints(corners)}overlapsRay(ray){const{direction:direction,from:from}=ray,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)}}exports.AABB=AABB;const tmp$1=new Vec3,transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3];class ArrayCollisionMatrix{constructor(){this.matrix=[]}get(bi,bj){let{index:i}=bi,{index:j}=bj;if(j>i){const temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]}set(bi,bj,value){let{index:i}=bi,{index:j}=bj;if(j>i){const temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0}reset(){for(let i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0}setNumObjects(n){this.matrix.length=n*(n-1)>>1}}exports.ArrayCollisionMatrix=ArrayCollisionMatrix;class EventTarget{addEventListener(type,listener){void 0===this._listeners&&(this._listeners={});const listeners=this._listeners;return void 0===listeners[type]&&(listeners[type]=[]),listeners[type].includes(listener)||listeners[type].push(listener),this}hasEventListener(type,listener){if(void 0===this._listeners)return!1;const listeners=this._listeners;return!(void 0===listeners[type]||!listeners[type].includes(listener))}hasAnyEventListener(type){if(void 0===this._listeners)return!1;return void 0!==this._listeners[type]}removeEventListener(type,listener){if(void 0===this._listeners)return this;const listeners=this._listeners;if(void 0===listeners[type])return this;const index=listeners[type].indexOf(listener);return-1!==index&&listeners[type].splice(index,1),this}dispatchEvent(event){if(void 0===this._listeners)return this;const listenerArray=this._listeners[event.type];if(void 0!==listenerArray){event.target=this;for(let 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){const 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}setFromEuler(x,y,z,order){void 0===order&&(order="XYZ");const 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}clone(){return new Quaternion(this.x,this.y,this.z,this.w)}slerp(toQuat,t,target){void 0===target&&(target=new Quaternion);const ax=this.x,ay=this.y,az=this.z,aw=this.w;let omega,cosom,sinom,scale0,scale1,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}integrate(angularVelocity,dt,angularFactor,target){void 0===target&&(target=new Quaternion);const 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}}exports.Quaternion=Quaternion;const 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};exports.SHAPE_TYPES=SHAPE_TYPES;class Shape{constructor(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}updateBoundingSphereRadius(){throw`computeBoundingSphereRadius() not implemented for shape type ${this.type}`}volume(){throw`volume() not implemented for shape type ${this.type}`}calculateLocalInertia(mass,target){throw`calculateLocalInertia() not implemented for shape type ${this.type}`}calculateWorldAABB(pos,quat,min,max){throw`calculateWorldAABB() not implemented for shape type ${this.type}`}}exports.Shape=Shape,Shape.idCounter=0,Shape.types=SHAPE_TYPES;class Transform{constructor(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)}pointToLocal(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)}pointToWorld(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)}vectorToWorldFrame(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result}static pointToLocalFrame(position,quaternion,worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat$1),tmpQuat$1.vmult(result,result),result}static pointToWorldFrame(position,quaternion,localPoint,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localPoint,result),result.vadd(position,result),result}static vectorToWorldFrame(quaternion,localVector,result){return void 0===result&&(result=new Vec3),quaternion.vmult(localVector,result),result}static vectorToLocalFrame(position,quaternion,worldVector,result){return void 0===result&&(result=new Vec3),quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result}}exports.Transform=Transform;const tmpQuat$1=new Quaternion;class ConvexPolyhedron extends Shape{constructor(props){void 0===props&&(props={});const{vertices:vertices=[],faces:faces=[],normals:normals=[],axes:axes,boundingSphereRadius:boundingSphereRadius}=props;super({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()}computeEdges(){const faces=this.faces,vertices=this.vertices,edges=this.uniqueEdges;edges.length=0;const edge=new Vec3;for(let i=0;i!==faces.length;i++){const face=faces[i],numVertices=face.length;for(let j=0;j!==numVertices;j++){const k=(j+1)%numVertices;vertices[face[j]].vsub(vertices[face[k]],edge),edge.normalize();let found=!1;for(let p=0;p!==edges.length;p++)if(edges[p].almostEquals(edge)||edges[p].almostEquals(edge)){found=!0;break}found||edges.push(edge.clone())}}}computeNormals(){this.faceNormals.length=this.faces.length;for(let i=0;idmax&&(dmax=d,closestFaceB=face)}const worldVertsB1=[];for(let i=0;i=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)}findSeparatingAxis(hullB,posA,quatA,posB,quatB,target,faceListA,faceListB){const faceANormalWS3=new Vec3,Worldnormal1=new Vec3,deltaC=new Vec3,worldEdge0=new Vec3,worldEdge1=new Vec3,Cross=new Vec3;let dmin=Number.MAX_VALUE;const hullA=this;if(hullA.uniqueAxes)for(let i=0;i!==hullA.uniqueAxes.length;i++){quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3);const d=hullA.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB);if(!1===d)return!1;d0&&target.negate(target),!0}testSepAxis(axis,hullB,posA,quatA,posB,quatB){ConvexPolyhedron.project(this,axis,posA,quatA,maxminA),ConvexPolyhedron.project(hullB,axis,posB,quatB,maxminB);const maxA=maxminA[0],minA=maxminA[1],maxB=maxminB[0],minB=maxminB[1];if(maxAaabbmax.x&&(aabbmax.x=v.x),v.yaabbmax.y&&(aabbmax.y=v.y),v.zaabbmax.z&&(aabbmax.z=v.z)}}computeWorldFaceNormals(quat){const N=this.faceNormals.length;for(;this.worldFaceNormals.lengthmax2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)}calculateWorldAABB(pos,quat,min,max){const verts=this.vertices;let minx,miny,minz,maxx,maxy,maxz,tempWorldVertex=new Vec3;for(let i=0;imaxx)&&(maxx=v.x),(void 0===miny||v.ymaxy)&&(maxy=v.y),(void 0===minz||v.zmaxz)&&(maxz=v.z)}min.set(minx,miny,minz),max.set(maxx,maxy,maxz)}volume(){return 4*Math.PI*this.boundingSphereRadius/3}getAveragePointLocal(target){void 0===target&&(target=new Vec3);const verts=this.vertices;for(let i=0;i0||r1>0&&r2<0)return!1}return-1}static project(shape,axis,pos,quat,result){const n=shape.vertices.length,localAxis=project_localAxis;let max=0,min=0;const localOrigin=project_localOrigin,vs=shape.vertices;localOrigin.setZero(),Transform.vectorToLocalFrame(pos,quat,axis,localAxis),Transform.pointToLocalFrame(pos,quat,localOrigin,localOrigin);const add=localOrigin.dot(localAxis);min=max=vs[0].dot(localAxis);for(let i=1;imax&&(max=val),val(max-=add)){const temp=min;min=max,max=temp}result[0]=max,result[1]=min}}exports.ConvexPolyhedron=ConvexPolyhedron;const maxminA=[],maxminB=[],project_localAxis=(new Vec3,new Vec3),project_localOrigin=new Vec3;class Box extends Shape{constructor(halfExtents){super({type:Shape.types.BOX}),this.halfExtents=halfExtents,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}updateConvexPolyhedronRepresentation(){const sx=this.halfExtents.x,sy=this.halfExtents.y,sz=this.halfExtents.z,V=Vec3,vertices=[new V(-sx,-sy,-sz),new V(sx,-sy,-sz),new V(sx,sy,-sz),new V(-sx,sy,-sz),new V(-sx,-sy,sz),new V(sx,-sy,sz),new V(sx,sy,sz),new V(-sx,sy,sz)],axes=[new V(0,0,1),new V(0,1,0),new V(1,0,0)],h=new ConvexPolyhedron({vertices:vertices,faces:[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]],axes:axes});this.convexPolyhedronRepresentation=h,h.material=this.material}calculateLocalInertia(mass,target){return void 0===target&&(target=new Vec3),Box.calculateInertia(this.halfExtents,mass,target),target}static calculateInertia(halfExtents,mass,target){const e=halfExtents;target.x=1/12*mass*(2*e.y*2*e.y+2*e.z*2*e.z),target.y=1/12*mass*(2*e.x*2*e.x+2*e.z*2*e.z),target.z=1/12*mass*(2*e.y*2*e.y+2*e.x*2*e.x)}getSideNormals(sixTargetVectors,quat){const sides=sixTargetVectors,ex=this.halfExtents;if(sides[0].set(ex.x,0,0),sides[1].set(0,ex.y,0),sides[2].set(0,0,ex.z),sides[3].set(-ex.x,0,0),sides[4].set(0,-ex.y,0),sides[5].set(0,0,-ex.z),void 0!==quat)for(let i=0;i!==sides.length;i++)quat.vmult(sides[i],sides[i]);return sides}volume(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z}updateBoundingSphereRadius(){this.boundingSphereRadius=this.halfExtents.length()}forEachWorldCorner(pos,quat,callback){const e=this.halfExtents,corners=[[e.x,e.y,e.z],[-e.x,e.y,e.z],[-e.x,-e.y,e.z],[-e.x,-e.y,-e.z],[e.x,-e.y,-e.z],[e.x,e.y,-e.z],[-e.x,e.y,-e.z],[e.x,-e.y,e.z]];for(let i=0;imax.x&&(max.x=x),y>max.y&&(max.y=y),z>max.z&&(max.z=z),x0?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=Body.AWAKE,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,this.isTrigger=Boolean(options.isTrigger),options.shape&&this.addShape(options.shape),this.updateMassProperties()}wakeUp(){const prevState=this.sleepState;this.sleepState=Body.AWAKE,this.wakeUpAfterNarrowphase=!1,prevState===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)}sleep(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1}sleepTick(time){if(this.allowSleep){const sleepState=this.sleepState,speedSquared=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),speedLimitSquared=this.sleepSpeedLimit**2;sleepState===Body.AWAKE&&speedSquaredspeedLimitSquared?this.wakeUp():sleepState===Body.SLEEPY&&time-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(Body.sleepEvent))}}updateSolveMassProperties(){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))}pointToLocalFrame(worldPoint,result){return void 0===result&&(result=new Vec3),worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result}vectorToLocalFrame(worldVector,result){return void 0===result&&(result=new Vec3),this.quaternion.conjugate().vmult(worldVector,result),result}pointToWorldFrame(localPoint,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result}vectorToWorldFrame(localVector,result){return void 0===result&&(result=new Vec3),this.quaternion.vmult(localVector,result),result}addShape(shape,_offset,_orientation){const 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}removeShape(shape){const index=this.shapes.indexOf(shape);return-1===index?(console.warn("Shape does not belong to the body"),this):(this.shapes.splice(index,1),this.shapeOffsets.splice(index,1),this.shapeOrientations.splice(index,1),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,shape.body=null,this)}updateBoundingRadius(){const shapes=this.shapes,shapeOffsets=this.shapeOffsets,N=shapes.length;let radius=0;for(let i=0;i!==N;i++){const shape=shapes[i];shape.updateBoundingSphereRadius();const offset=shapeOffsets[i].length(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius}updateAABB(){const shapes=this.shapes,shapeOffsets=this.shapeOffsets,shapeOrientations=this.shapeOrientations,N=shapes.length,offset=tmpVec,orientation=tmpQuat,bodyQuat=this.quaternion,aabb=this.aabb,shapeAABB=updateAABB_shapeAABB;for(let i=0;i!==N;i++){const 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}updateInertiaWorld(force){const I=this.invInertia;if(I.x!==I.y||I.y!==I.z||force){const m1=uiw_m1,m2=uiw_m2;m1.setRotationFromQuaternion(this.quaternion),m1.transpose(m2),m1.scale(I,m1),m1.mmult(m2,this.invInertiaWorld)}else;}applyForce(force,relativePoint){if(void 0===relativePoint&&(relativePoint=new Vec3),this.type!==Body.DYNAMIC)return;this.sleepState===Body.SLEEPING&&this.wakeUp();const rotForce=Body_applyForce_rotForce;relativePoint.cross(force,rotForce),this.force.vadd(force,this.force),this.torque.vadd(rotForce,this.torque)}applyLocalForce(localForce,localPoint){if(void 0===localPoint&&(localPoint=new Vec3),this.type!==Body.DYNAMIC)return;const worldForce=Body_applyLocalForce_worldForce,relativePointWorld=Body_applyLocalForce_relativePointWorld;this.vectorToWorldFrame(localForce,worldForce),this.vectorToWorldFrame(localPoint,relativePointWorld),this.applyForce(worldForce,relativePointWorld)}applyTorque(torque){this.type===Body.DYNAMIC&&(this.sleepState===Body.SLEEPING&&this.wakeUp(),this.torque.vadd(torque,this.torque))}applyImpulse(impulse,relativePoint){if(void 0===relativePoint&&(relativePoint=new Vec3),this.type!==Body.DYNAMIC)return;this.sleepState===Body.SLEEPING&&this.wakeUp();const r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.scale(this.invMass,velo),this.velocity.vadd(velo,this.velocity);const rotVelo=Body_applyImpulse_rotVelo;r.cross(impulse,rotVelo),this.invInertiaWorld.vmult(rotVelo,rotVelo),this.angularVelocity.vadd(rotVelo,this.angularVelocity)}applyLocalImpulse(localImpulse,localPoint){if(void 0===localPoint&&(localPoint=new Vec3),this.type!==Body.DYNAMIC)return;const worldImpulse=Body_applyLocalImpulse_worldImpulse,relativePointWorld=Body_applyLocalImpulse_relativePoint;this.vectorToWorldFrame(localImpulse,worldImpulse),this.vectorToWorldFrame(localPoint,relativePointWorld),this.applyImpulse(worldImpulse,relativePointWorld)}updateMassProperties(){const halfExtents=Body_updateMassProperties_halfExtents;this.invMass=this.mass>0?1/this.mass:0;const I=this.inertia,fixed=this.fixedRotation;this.updateAABB(),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)}getVelocityAtWorldPoint(worldPoint,result){const r=new Vec3;return worldPoint.vsub(this.position,r),this.angularVelocity.cross(r,result),this.velocity.vadd(result,result),result}integrate(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)return;const 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;const 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()}}exports.Body=Body,Body.idCounter=0,Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=BODY_TYPES.DYNAMIC,Body.STATIC=BODY_TYPES.STATIC,Body.KINEMATIC=BODY_TYPES.KINEMATIC,Body.AWAKE=BODY_SLEEP_STATES.AWAKE,Body.SLEEPY=BODY_SLEEP_STATES.SLEEPY,Body.SLEEPING=BODY_SLEEP_STATES.SLEEPING,Body.wakeupEvent={type:"wakeup"},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"};const tmpVec=new Vec3,tmpQuat=new Quaternion,updateAABB_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;class Broadphase{constructor(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}collisionPairs(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")}needBroadphaseCollision(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)}intersectionTest(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)}doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2){const r=Broadphase_collisionPairs_r;bodyB.position.vsub(bodyA.position,r);const boundingRadiusSum2=(bodyA.boundingRadius+bodyB.boundingRadius)**2;r.lengthSquared()dist.lengthSquared()}aabbQuery(world,aabb,result){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}}exports.Broadphase=Broadphase;const Broadphase_collisionPairs_r=new Vec3;new Vec3,new Quaternion,new Vec3;const Broadphase_makePairsUnique_temp={keys:[]},Broadphase_makePairsUnique_p1=[],Broadphase_makePairsUnique_p2=[];new Vec3;exports.GridBroadphase=class extends Broadphase{constructor(aabbMin,aabbMax,nx,ny,nz){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),super(),this.nx=nx,this.ny=ny,this.nz=nz,this.aabbMin=aabbMin,this.aabbMax=aabbMax;const 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(let 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(let xoff=xoff0*=xstep;xoff<=xoff1;xoff+=xstep)for(let yoff=yoff0;yoff<=yoff1;yoff+=ystep)for(let zoff=zoff0;zoff<=zoff1;zoff+=zstep){const idx=xoff+yoff+zoff;bins[idx][binLengths[idx]++]=bi}}for(let i=0;i!==N;i++){const bi=bodies[i],si=bi.shapes[0];switch(si.type){case SPHERE:{const 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:{const shape=si;shape.worldNormalNeedsUpdate&&shape.computeWorldNormal(bi.quaternion);const 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(let xi=0,xoff=0;xi!==nx;xi++,xoff+=xstep,d.y=yreset,d.x+=binsizeX)for(let yi=0,yoff=0;yi!==ny;yi++,yoff+=ystep,d.z=zreset,d.y+=binsizeY)for(let zi=0,zoff=0;zi!==nz;zi++,zoff+=zstep,d.z+=binsizeZ)if(d.dot(planeNormal)1){const bin=bins[i];for(let xi=0;xi!==binLength;xi++){const bi=bin[xi];for(let yi=0;yi!==xi;yi++){const bj=bin[yi];this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)}}}}this.makePairsUnique(pairs1,pairs2)}};const GridBroadphase_collisionPairs_d=new Vec3;new Vec3;class NaiveBroadphase extends Broadphase{constructor(){super()}collisionPairs(world,pairs1,pairs2){const bodies=world.bodies,n=bodies.length;let bi,bj;for(let i=0;i!==n;i++)for(let j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)}aabbQuery(world,aabb,result){void 0===result&&(result=[]);for(let i=0;i{})}intersectWorld(world,options){return this.mode=options.mode||Ray.ANY,this.result=options.result||new RaycastResult,this.skipBackfaces=!!options.skipBackfaces,this.collisionFilterMask=void 0!==options.collisionFilterMask?options.collisionFilterMask:-1,this.collisionFilterGroup=void 0!==options.collisionFilterGroup?options.collisionFilterGroup:-1,this.checkCollisionResponse=void 0===options.checkCollisionResponse||options.checkCollisionResponse,options.from&&this.from.copy(options.from),options.to&&this.to.copy(options.to),this.callback=options.callback||(()=>{}),this.hasHit=!1,this.result.reset(),this.updateDirection(),this.getAABB(tmpAABB$1),tmpArray.length=0,world.broadphase.aabbQuery(world,tmpAABB$1,tmpArray),this.intersectBodies(tmpArray),this.hasHit}intersectBody(body,result){result&&(this.result=result,this.updateDirection());const checkCollisionResponse=this.checkCollisionResponse;if(checkCollisionResponse&&!body.collisionResponse)return;if(0==(this.collisionFilterGroup&body.collisionFilterMask)||0==(body.collisionFilterGroup&this.collisionFilterMask))return;const xi=intersectBody_xi,qi=intersectBody_qi;for(let i=0,N=body.shapes.length;ishape.boundingSphereRadius)return;const intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}_intersectBox(box,quat,position,body,reportedShape){return this._intersectConvex(box.convexPolyhedronRepresentation,quat,position,body,reportedShape)}_intersectPlane(shape,quat,position,body,reportedShape){const from=this.from,to=this.to,direction=this.direction,worldNormal=new Vec3(0,0,1);quat.vmult(worldNormal,worldNormal);const len=new Vec3;from.vsub(position,len);const planeToFrom=len.dot(worldNormal);if(to.vsub(position,len),planeToFrom*len.dot(worldNormal)>0)return;if(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))}}_intersectConvex(shape,quat,position,body,reportedShape,options){const 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;for(let j=0;!result.shouldStop&&jfromToDistance||this.reportIntersection(normal,intersectPoint,reportedShape,body,fi)}}}}_intersectTrimesh(mesh,quat,position,body,reportedShape,options){const 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=mesh.indices;mesh.vertices;const from=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();const fromToDistanceSquared=localFrom.distanceSquared(localTo);mesh.tree.rayQuery(this,treeTransform,triangles);for(let i=0,N=triangles.length;!this.result.shouldStop&&i!==N;i++){const trianglesIndex=triangles[i];mesh.getNormal(trianglesIndex,normal),mesh.getVertex(indices[3*trianglesIndex],a),a.vsub(localFrom,vector);const dot=localDirection.dot(normal),scalar=normal.dot(vector)/dot;if(scalar<0)continue;localDirection.scale(scalar,intersectPoint),intersectPoint.vadd(localFrom,intersectPoint),mesh.getVertex(indices[3*trianglesIndex+1],b),mesh.getVertex(indices[3*trianglesIndex+2],c);const squaredDistance=intersectPoint.distanceSquared(localFrom);!Ray.pointInTriangle(intersectPoint,b,a,c)&&!Ray.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}reportIntersection(normal,hitPointWorld,shape,body,hitFaceIndex){const 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+v=0&&!(a[j].aabb.lowerBound.x<=v.aabb.lowerBound.x);j--)a[j+1]=a[j];a[j+1]=v}return a}static insertionSortY(a){for(let 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}static insertionSortZ(a){for(let 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}constructor(world){super(),this.axisList=[],this.world=null,this.axisIndex=0;const axisList=this.axisList;this._addBodyHandler=(event=>{axisList.push(event.body)}),this._removeBodyHandler=(event=>{const idx=axisList.indexOf(event.body);-1!==idx&&axisList.splice(idx,1)}),world&&this.setWorld(world)}setWorld(world){this.axisList.length=0;for(let i=0;ivarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2}aabbQuery(world,aabb,result){void 0===result&&(result=[]),this.dirty&&(this.sortList(),this.dirty=!1);const axisIndex=this.axisIndex;let axis="x";1===axisIndex&&(axis="y"),2===axisIndex&&(axis="z");const axisList=this.axisList;aabb.lowerBound[axis],aabb.upperBound[axis];for(let i=0;i=-.1)this.suspensionRelativeVelocity=0,this.clippedInvContactDotSuspension=10;else{const 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}}exports.WheelInfo=WheelInfo;const chassis_velocity_at_contactPoint=new Vec3,relpos=new Vec3;exports.RaycastVehicle=class{constructor(options){this.chassisBody=options.chassisBody,this.wheelInfos=[],this.sliding=!1,this.world=null,this.indexRightAxis=void 0!==options.indexRightAxis?options.indexRightAxis:2,this.indexForwardAxis=void 0!==options.indexForwardAxis?options.indexForwardAxis:0,this.indexUpAxis=void 0!==options.indexUpAxis?options.indexUpAxis:1,this.constraints=[],this.preStepCallback=(()=>{}),this.currentVehicleSpeedKmHour=0,this.numWheelsOnGround=0}addWheel(options){void 0===options&&(options={});const info=new WheelInfo(options),index=this.wheelInfos.length;return this.wheelInfos.push(info),index}setSteeringValue(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value}applyEngineForce(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value}setBrake(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake}addToWorld(world){world.addBody(this.chassisBody);const that=this;this.preStepCallback=(()=>{that.updateVehicle(world.dt)}),world.addEventListener("preStep",this.preStepCallback),this.world=world}getVehicleAxisWorld(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)}updateVehicle(timeStep){const wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,chassisBody=this.chassisBody;for(let 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);const hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3;for(let i=0;i0?1:-1)*wheel.customSlidingRotationalSpeed*timeStep),Math.abs(wheel.brake)>Math.abs(wheel.engineForce)&&(wheel.deltaRotation=0),wheel.rotation+=wheel.deltaRotation,wheel.deltaRotation*=.99}}updateSuspension(deltaTime){const chassisMass=this.chassisBody.mass,wheelInfos=this.wheelInfos,numWheels=wheelInfos.length;for(let w_it=0;w_itmaxSuspensionLength&&(wheel.suspensionLength=maxSuspensionLength,wheel.raycastResult.reset());const denominator=wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld),chassis_velocity_at_contactPoint=new Vec3;chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld,chassis_velocity_at_contactPoint);const projVel=wheel.raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);if(denominator>=-.1)wheel.suspensionRelativeVelocity=0,wheel.clippedInvContactDotSuspension=10;else{const 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}updateWheelTransformWorld(wheel){wheel.isInContact=!1;const chassisBody=this.chassisBody;chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal,wheel.chassisConnectionPointWorld),chassisBody.vectorToWorldFrame(wheel.directionLocal,wheel.directionWorld),chassisBody.vectorToWorldFrame(wheel.axleLocal,wheel.axleWorld)}updateWheelTransform(wheelIndex){const 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();const steering=wheel.steering,steeringOrn=new Quaternion;steeringOrn.setFromAxisAngle(up,steering);const rotatingOrn=new Quaternion;rotatingOrn.setFromAxisAngle(right,wheel.rotation);const q=wheel.worldTransform.quaternion;this.chassisBody.quaternion.mult(steeringOrn,q),q.mult(rotatingOrn,q),q.normalize();const p=wheel.worldTransform.position;p.copy(wheel.directionWorld),p.scale(wheel.suspensionLength,p),p.vadd(wheel.chassisConnectionPointWorld,p)}getWheelTransformWorld(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform}updateFriction(timeStep){const surfNormalWS_scaled_proj=updateFriction_surfNormalWS_scaled_proj,wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,chassisBody=this.chassisBody,forwardWS=updateFriction_forwardWS,axle=updateFriction_axle;this.numWheelsOnGround=0;for(let i=0;imaximpSquared){this.sliding=!0,wheel.sliding=!0;const factor=maximp/Math.sqrt(impulseSquared);wheel.skidInfo*=factor}}}if(this.sliding)for(let i=0;i1.1)return 0;const 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))}class Sphere extends Shape{constructor(radius){if(super({type:Shape.types.SPHERE}),this.radius=void 0!==radius?radius:1,this.radius<0)throw new Error("The sphere radius cannot be negative.");this.updateBoundingSphereRadius()}calculateLocalInertia(mass,target){void 0===target&&(target=new Vec3);const I=2*mass*this.radius*this.radius/5;return target.x=I,target.y=I,target.z=I,target}volume(){return 4*Math.PI*Math.pow(this.radius,3)/3}updateBoundingSphereRadius(){this.boundingSphereRadius=this.radius}calculateWorldAABB(pos,quat,min,max){const r=this.radius,axes=["x","y","z"];for(let i=0;ithis.particles.length&&this.neighbors.pop())}getNeighbors(particle,neighbors){const N=this.particles.length,id=particle.id,R2=this.smoothingRadius*this.smoothingRadius,dist=SPHSystem_getNeighbors_dist;for(let i=0;i!==N;i++){const p=this.particles[i];p.position.vsub(particle.position,dist),id!==p.id&&dist.lengthSquared()maxValue&&(maxValue=v)}this.maxValue=maxValue}setHeightValueAtIndex(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)}getRectMinMax(iMinX,iMinY,iMaxX,iMaxY,result){void 0===result&&(result=[]);const data=this.data;let max=this.minValue;for(let i=iMinX;i<=iMaxX;i++)for(let j=iMinY;j<=iMaxY;j++){const height=data[i][j];height>max&&(max=height)}result[0]=this.minValue,result[1]=max}getIndexOfPosition(x,y,result,clamp){const w=this.elementSize,data=this.data;let 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)}getTriangleAt(x,y,edgeClamp,a,b,c){const idx=getHeightAt_idx;this.getIndexOfPosition(x,y,idx,edgeClamp);let xi=idx[0],yi=idx[1];const 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)));const elementSize=this.elementSize,upper=(x/elementSize-xi)**2+(y/elementSize-yi)**2>(x/elementSize-(xi+1))**2+(y/elementSize-(yi+1))**2;return this.getTriangle(xi,yi,upper,a,b,c),upper}getNormalAt(x,y,edgeClamp,result){const 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()}getAabbAtIndex(xi,yi,_ref){let{lowerBound:lowerBound,upperBound:upperBound}=_ref;const 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])}getHeightAt(x,y,edgeClamp){const data=this.data,a=getHeightAt_a,b=getHeightAt_b,c=getHeightAt_c,idx=getHeightAt_idx;this.getIndexOfPosition(x,y,idx,edgeClamp);let 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)));const 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);const 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}getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle){return`${xi}_${yi}_${getUpperTriangle?1:0}`}getCachedConvexTrianglePillar(xi,yi,getUpperTriangle){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]}setCachedConvexTrianglePillar(xi,yi,getUpperTriangle,convex,offset){this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]={convex:convex,offset:offset}}clearCachedConvexTrianglePillar(xi,yi,getUpperTriangle){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi,yi,getUpperTriangle)]}getTriangle(xi,yi,upper,a,b,c){const 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]))}getConvexTrianglePillar(xi,yi,getUpperTriangle){let result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){const 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}const data=this.data,elementSize=this.elementSize,faces=result.faces;result.vertices.length=6;for(let i=0;i<6;i++)result.vertices[i]||(result.vertices[i]=new Vec3);faces.length=5;for(let i=0;i<5;i++)faces[i]||(faces[i]=[]);const 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,-Math.abs(h)-1),verts[4].set(-.75*elementSize,.25*elementSize,-Math.abs(h)-1),verts[5].set(.25*elementSize,-.75*elementSize,-Math.abs(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,-Math.abs(h)-1),verts[4].set(.75*elementSize,-.25*elementSize,-Math.abs(h)-1),verts[5].set(-.25*elementSize,.75*elementSize,-Math.abs(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)}calculateLocalInertia(mass,target){return void 0===target&&(target=new Vec3),target.set(0,0,0),target}volume(){return Number.MAX_VALUE}calculateWorldAABB(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)}updateBoundingSphereRadius(){const 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()}setHeightsFromImage(image,scale){const{x:x,z:z,y:y}=scale,canvas=document.createElement("canvas");canvas.width=image.width,canvas.height=image.height;const context=canvas.getContext("2d");context.drawImage(image,0,0);const imageData=context.getImageData(0,0,image.width,image.height),matrix=this.data;matrix.length=0,this.elementSize=Math.abs(x)/imageData.width;for(let i=0;i=0;i--)this.children[i].removeEmptyNodes(),this.children[i].children.length||this.children[i].data.length||this.children.splice(i,1)}}class Octree extends OctreeNode{constructor(aabb,options){void 0===options&&(options={}),super({root:null,aabb:aabb}),this.maxDepth=void 0!==options.maxDepth?options.maxDepth:8}}const halfDiagonal=new Vec3,tmpAABB=new AABB;class Trimesh extends Shape{constructor(vertices,indices){super({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()}updateTree(){const tree=this.tree;tree.reset(),tree.aabb.copy(this.aabb);const 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;const triangleAABB=new AABB,a=new Vec3,b=new Vec3,c=new Vec3,points=[a,b,c];for(let i=0;i{edges[au.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)}updateAABB(){this.computeLocalAABB(this.aabb)}updateBoundingSphereRadius(){let max2=0;const vertices=this.vertices,v=new Vec3;for(let i=0,N=vertices.length/3;i!==N;i++){this.getVertex(i,v);const norm2=v.lengthSquared();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)}calculateWorldAABB(pos,quat,min,max){const 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)}volume(){return 4*Math.PI*this.boundingSphereRadius/3}static createTorus(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);const vertices=[],indices=[];for(let j=0;j<=radialSegments;j++)for(let i=0;i<=tubularSegments;i++){const 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(let j=1;j<=radialSegments;j++)for(let i=1;i<=tubularSegments;i++){const a=(tubularSegments+1)*j+i-1,b=(tubularSegments+1)*(j-1)+i-1,c=(tubularSegments+1)*(j-1)+i,d=(tubularSegments+1)*j+i;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)}}exports.Trimesh=Trimesh;const computeNormals_n=new Vec3,unscaledAABB=new AABB,getEdgeVector_va=new Vec3,getEdgeVector_vb=new Vec3,cb=new Vec3,ab=new Vec3,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;class Solver{constructor(){this.equations=[]}solve(dt,world){return 0}addEquation(eq){!eq.enabled||eq.bi.isTrigger||eq.bj.isTrigger||this.equations.push(eq)}removeEquation(eq){const eqs=this.equations,i=eqs.indexOf(eq);-1!==i&&eqs.splice(i,1)}removeAllEquations(){this.equations.length=0}}exports.Solver=Solver;class GSSolver extends Solver{constructor(){super(),this.iterations=10,this.tolerance=1e-7}solve(dt,world){let iter=0;const maxIter=this.iterations,tolSquared=this.tolerance*this.tolerance,equations=this.equations,Neq=equations.length,bodies=world.bodies,Nbodies=bodies.length,h=dt;let B,invC,deltalambda,deltalambdaTot,GWlambda,lambdaj;if(0!==Neq)for(let i=0;i!==Nbodies;i++)bodies[i].updateSolveMassProperties();const invCs=GSSolver_solve_invCs,Bs=GSSolver_solve_Bs,lambda=GSSolver_solve_lambda;invCs.length=Neq,Bs.length=Neq,lambda.length=Neq;for(let i=0;i!==Neq;i++){const c=equations[i];lambda[i]=0,Bs[i]=c.computeB(h),invCs[i]=1/c.computeC()}if(0!==Neq){for(let i=0;i!==Nbodies;i++){const b=bodies[i],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(let j=0;j!==Neq;j++){const c=equations[j];B=Bs[j],invC=invCs[j],(lambdaj=lambda[j])+(deltalambda=invC*(B-(GWlambda=c.computeGWlambda())-c.eps*lambdaj))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}createFrictionEquationsFromContact(contactEquation,outArray){const bodyA=contactEquation.bi,bodyB=contactEquation.bj,shapeA=contactEquation.si,shapeB=contactEquation.sj,world=this.world,cm=this.currentContactMaterial;let friction=cm.friction;const 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){const mug=friction*(world.frictionGravity||world.gravity).length();let reducedMass=bodyA.invMass+bodyB.invMass;reducedMass>0&&(reducedMass=1/reducedMass);const 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}createFrictionFromAverage(numContacts){let c=this.result[this.result.length-1];if(!this.createFrictionEquationsFromContact(c,this.frictionResult)||1===numContacts)return;const f1=this.frictionResult[this.frictionResult.length-2],f2=this.frictionResult[this.frictionResult.length-1];averageNormal.setZero(),averageContactPointA.setZero(),averageContactPointB.setZero();const bodyA=c.bi;c.bj;for(let i=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));const 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)}getContacts(p1,p2,world,result,oldcontacts,frictionResult,frictionPool){this.contactPointPool=oldcontacts,this.frictionEquationPool=frictionPool,this.result=result,this.frictionResult=frictionResult;const qi=tmpQuat1,qj=tmpQuat2,xi=tmpVec1,xj=tmpVec2;for(let k=0,N=p1.length;k!==N;k++){const bi=p1[k],bj=p2[k];let bodyContactMaterial=null;bi.material&&bj.material&&(bodyContactMaterial=world.getContactMaterial(bi.material,bj.material)||null);const 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;for(let i=0;isi.boundingSphereRadius+sj.boundingSphereRadius)continue;let shapeContactMaterial=null;si.material&&sj.material&&(shapeContactMaterial=world.getContactMaterial(si.material,sj.material)||null),this.currentContactMaterial=shapeContactMaterial||bodyContactMaterial||world.defaultContactMaterial;const resolver=this[si.type|sj.type];if(resolver){let retval=!1;(retval=si.type0){const ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);const h1=ns1.length(),h2=ns2.length();ns1.normalize(),ns2.normalize();const dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){const dist=Math.abs(dot-h-R);if((null===side_distance||distsi.boundingSphereRadius+sj.boundingSphereRadius)&&si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){const res=[],q=convexConvex_q;si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);let numContacts=0;for(let j=0;j!==res.length;j++){if(justTest)return!0;const 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)}}sphereConvex(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){const v3pool=this.v3pool;xi.vsub(xj,convex_to_sphere);const normals=sj.faceNormals,faces=sj.faces,verts=sj.vertices,R=si.radius;let found=!1;for(let i=0;i!==verts.length;i++){const v=verts[i],worldCorner=sphereConvex_worldCorner;qj.vmult(v,worldCorner),xj.vadd(worldCorner,worldCorner);const sphere_to_corner=sphereConvex_sphereToCorner;if(worldCorner.vsub(xi,sphere_to_corner),sphere_to_corner.lengthSquared()0){const faceVerts=[];for(let j=0,Nverts=face.length;j!==Nverts;j++){const 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;const r=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.scale(-R,r.ri),worldNormal.negate(r.ni);const penetrationVec2=v3pool.get();worldNormal.scale(-penetration,penetrationVec2);const penetrationSpherePoint=v3pool.get();worldNormal.scale(-R,penetrationSpherePoint),xi.vsub(xj,r.rj),r.rj.vadd(penetrationSpherePoint,r.rj),r.rj.vadd(penetrationVec2,r.rj),r.rj.vadd(xj,r.rj),r.rj.vsub(bj.position,r.rj),r.ri.vadd(xi,r.ri),r.ri.vsub(bi.position,r.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(r),this.createFrictionEquationsFromContact(r,this.frictionResult);for(let j=0,Nfaceverts=faceVerts.length;j!==Nfaceverts;j++)v3pool.release(faceVerts[j]);return}for(let j=0;j!==face.length;j++){const v1=v3pool.get(),v2=v3pool.get();qj.vmult(verts[face[(j+1)%face.length]],v1),qj.vmult(verts[face[(j+2)%face.length]],v2),xj.vadd(v1,v1),xj.vadd(v2,v2);const edge=sphereConvex_edge;v2.vsub(v1,edge);const edgeUnit=sphereConvex_edgeUnit;edge.unit(edgeUnit);const p=v3pool.get(),v1_to_xi=v3pool.get();xi.vsub(v1,v1_to_xi);const dot=v1_to_xi.dot(edgeUnit);edgeUnit.scale(dot,p),p.vadd(v1,p);const xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotdata.length||iMinY>data[0].length)return;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);const minMax=[];hfShape.getRectMinMax(iMinX,iMinY,iMaxX,iMaxY,minMax);const min=minMax[0],max=minMax[1];if(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}boxHeightfield(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)}convexHeightfield(convexShape,hfShape,convexPos,hfPos,convexQuat,hfQuat,convexBody,hfBody,rsi,rsj,justTest){const data=hfShape.data,w=hfShape.elementSize,radius=convexShape.boundingSphereRadius,worldPillarOffset=convexHeightfield_tmp2,faceList=convexHeightfield_faceList,localConvexPos=convexHeightfield_tmp1;Transform.pointToLocalFrame(hfPos,hfQuat,convexPos,localConvexPos);let 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)return;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);const minMax=[];hfShape.getRectMinMax(iMinX,iMinY,iMaxX,iMaxY,minMax);const 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}const 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,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;new Vec3,new Vec3;const planeConvex_v=new Vec3,planeConvex_normal=new Vec3,planeConvex_relpos=new Vec3,planeConvex_projected=new Vec3,convexConvex_sepAxis=new Vec3,convexConvex_q=new Vec3,particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3,particleSphere_normal=new Vec3,cqj=new Quaternion,convexParticle_local=new Vec3;new Vec3;const convexParticle_penetratedFaceNormal=new Vec3,convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3,convexHeightfield_tmp1=new Vec3,convexHeightfield_tmp2=new Vec3,convexHeightfield_faceList=[0],sphereHeightfield_tmp1=new Vec3,sphereHeightfield_tmp2=new Vec3;class OverlapKeeper{constructor(){this.current=[],this.previous=[]}getKey(i,j){if(jcurrent[index];)index++;if(key!==current[index]){for(let j=current.length-1;j>=index;j--)current[j+1]=current[j];current[index]=key}}tick(){const tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0}getDiff(additions,removals){const a=this.current,b=this.previous,al=a.length,bl=b.length;let j=0;for(let i=0;ib[j];)j++;(found=keyA===b[j])||unpackAndPush(additions,keyA)}j=0;for(let i=0;ia[j];)j++;(found=a[j]===keyB)||unpackAndPush(removals,keyB)}}}function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}const getKey=(i,j)=>i0;){delete data[keys.pop()]}}}exports.World=class extends EventTarget{constructor(options){void 0===options&&(options={}),super(),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),options.frictionGravity&&(this.frictionGravity=new Vec3,this.frictionGravity.copy(options.frictionGravity)),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(this),this.collisionMatrix=new ArrayCollisionMatrix,this.collisionMatrixPrevious=new ArrayCollisionMatrix,this.bodyOverlapKeeper=new OverlapKeeper,this.shapeOverlapKeeper=new OverlapKeeper,this.contactmaterials=[],this.contactMaterialTable=new TupleDictionary,this.defaultMaterial=new Material("default"),this.defaultContactMaterial=new ContactMaterial(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.accumulator=0,this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.idToBodyMap={},this.broadphase.setWorld(this)}getContactMaterial(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)}collisionMatrixTick(){const temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()}addConstraint(c){this.constraints.push(c)}removeConstraint(c){const idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)}rayTest(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)}raycastAll(from,to,options,callback){return void 0===options&&(options={}),options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay.intersectWorld(this,options)}raycastAny(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay.intersectWorld(this,options)}raycastClosest(from,to,options,result){return void 0===options&&(options={}),options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay.intersectWorld(this,options)}addBody(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))}removeBody(body){body.world=null;const n=this.bodies.length-1,bodies=this.bodies,idx=bodies.indexOf(body);if(-1!==idx){bodies.splice(idx,1);for(let 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)}}getBodyById(id){return this.idToBodyMap[id]}getShapeById(id){const bodies=this.bodies;for(let i=0;i=dt&&substeps1e3*dt)););this.accumulator=this.accumulator%dt;const t=this.accumulator/dt;for(let j=0;j!==this.bodies.length;j++){const b=this.bodies[j];b.previousPosition.lerp(b.position,t,b.interpolatedPosition),b.previousQuaternion.slerp(b.quaternion,t,b.interpolatedQuaternion),b.previousQuaternion.normalize()}this.time+=timeSinceLastCalled}}internalStep(dt){this.dt=dt;const contacts=this.contacts,p1=World_step_p1,p2=World_step_p2,N=this.bodies.length,bodies=this.bodies,solver=this.solver,gravity=this.gravity,doProfiling=this.doProfiling,profile=this.profile,DYNAMIC=Body.DYNAMIC;let profilingStart=-1/0;const constraints=this.constraints,frictionEquationPool=World_step_frictionEquationPool;gravity.length();const gx=gravity.x,gy=gravity.y,gz=gravity.z;let i=0;for(doProfiling&&(profilingStart=performance.now()),i=0;i!==N;i++){const bi=bodies[i];if(bi.type===DYNAMIC){const f=bi.force,m=bi.mass;f.x+=m*gx,f.y+=m*gy,f.z+=m*gz}}for(let i=0,Nsubsystems=this.subsystems.length;i!==Nsubsystems;i++)this.subsystems[i].update();doProfiling&&(profilingStart=performance.now()),p1.length=0,p2.length=0,this.broadphase.collisionPairs(this,p1,p2),doProfiling&&(profile.broadphase=performance.now()-profilingStart);let Nconstraints=constraints.length;for(i=0;i!==Nconstraints;i++){const c=constraints[i];if(!c.collideConnected)for(let j=p1.length-1;j>=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());const oldcontacts=World_step_oldContacts,NoldContacts=contacts.length;for(i=0;i!==NoldContacts;i++)oldcontacts.push(contacts[i]);contacts.length=0;const 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*bj.sleepSpeedLimit**2&&(bi.wakeUpAfterNarrowphase=!0),bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&bi.sleepState===Body.AWAKE&&bi.type!==Body.STATIC&&bi.velocity.lengthSquared()+bi.angularVelocity.lengthSquared()>=2*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++){const bi=bodies[i];bi.wakeUpAfterNarrowphase&&(bi.wakeUp(),bi.wakeUpAfterNarrowphase=!1)}for(Nconstraints=constraints.length,i=0;i!==Nconstraints;i++){const c=constraints[i];c.update();for(let j=0,Neq=c.equations.length;j!==Neq;j++){const eq=c.equations[j];solver.addEquation(eq)}}solver.solve(dt,this),doProfiling&&(profile.solve=performance.now()-profilingStart),solver.removeAllEquations();const pow=Math.pow;for(i=0;i!==N;i++){const bi=bodies[i];if(bi.type&DYNAMIC){const ld=pow(1-bi.linearDamping,dt),v=bi.velocity;v.scale(ld,v);const av=bi.angularVelocity;if(av){const ad=pow(1-bi.angularDamping,dt);av.scale(ad,av)}}}this.dispatchEvent(World_step_preStepEvent),doProfiling&&(profilingStart=performance.now());const quatNormalize=this.stepnumber%(this.quatNormalizeSkip+1)==0,quatNormalizeFast=this.quatNormalizeFast;for(i=0;i!==N;i++)bodies[i].integrate(dt,quatNormalize,quatNormalizeFast);this.clearForces(),this.broadphase.dirty=!0,doProfiling&&(profile.integrate=performance.now()-profilingStart),this.stepnumber+=1,this.dispatchEvent(World_step_postStepEvent);let hasActiveBodies=!0;if(this.allowSleep)for(hasActiveBodies=!1,i=0;i!==N;i++){const bi=bodies[i];bi.sleepTick(this.time),bi.sleepState!==Body.SLEEPING&&(hasActiveBodies=!0)}this.hasActiveBodies=hasActiveBodies}emitContactEvents(){const hasBeginContact=this.hasAnyEventListener("beginContact"),hasEndContact=this.hasAnyEventListener("endContact");if((hasBeginContact||hasEndContact)&&this.bodyOverlapKeeper.getDiff(additions,removals),hasBeginContact){for(let i=0,l=additions.length;iDate.now()-nowOffset)}new Vec3;const 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=[],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}},{}],5:[function(require,module,exports){(function(global){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.iterateGeometries=exports.createVHACDShapes=exports.createTriMeshShape=exports.createSphereShape=exports.createHullShape=exports.createHeightfieldTerrainShape=exports.createHACDShapes=exports.createCylinderShape=exports.createConeShape=exports.createCollisionShapes=exports.createCapsuleShape=exports.createBoxShape=exports.TYPE=exports.HEIGHTFIELD_DATA_TYPE=exports.FIT=void 0;var THREE=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}("undefined"!=typeof window?window.THREE:void 0!==global?global.THREE:null);function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}const TYPE={BOX:"box",CYLINDER:"cylinder",SPHERE:"sphere",CAPSULE:"capsule",CONE:"cone",HULL:"hull",HACD:"hacd",VHACD:"vhacd",MESH:"mesh",HEIGHTFIELD:"heightfield"};exports.TYPE=TYPE;const FIT={ALL:"all",MANUAL:"manual"};exports.FIT=FIT;exports.HEIGHTFIELD_DATA_TYPE={short:"short",float:"float"};exports.createCollisionShapes=function(vertices,matrices,indexes,matrixWorld,options={}){switch(options.type){case TYPE.BOX:return[createBoxShape(vertices,matrices,matrixWorld,options)];case TYPE.CYLINDER:return[createCylinderShape(vertices,matrices,matrixWorld,options)];case TYPE.CAPSULE:return[createCapsuleShape(vertices,matrices,matrixWorld,options)];case TYPE.CONE:return[createConeShape(vertices,matrices,matrixWorld,options)];case TYPE.SPHERE:return[createSphereShape(vertices,matrices,matrixWorld,options)];case TYPE.HULL:return[createHullShape(vertices,matrices,matrixWorld,options)];case TYPE.HACD:return createHACDShapes(vertices,matrices,indexes,matrixWorld,options);case TYPE.VHACD:return createVHACDShapes(vertices,matrices,indexes,matrixWorld,options);case TYPE.MESH:return[createTriMeshShape(vertices,matrices,indexes,matrixWorld,options)];case TYPE.HEIGHTFIELD:return[createHeightfieldTerrainShape(options)];default:return console.warn(options.type+" is not currently supported"),[]}};const createBoxShape=function(vertices,matrices,matrixWorld,options={}){options.type=TYPE.BOX,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(_computeBounds(vertices,matrices),options.minHalfExtent,options.maxHalfExtent));const btHalfExtents=new Ammo.btVector3(options.halfExtents.x,options.halfExtents.y,options.halfExtents.z),collisionShape=new Ammo.btBoxShape(btHalfExtents);return Ammo.destroy(btHalfExtents),_finishCollisionShape(collisionShape,options,_computeScale(matrixWorld,options)),collisionShape};exports.createBoxShape=createBoxShape;const createCylinderShape=function(vertices,matrices,matrixWorld,options={}){options.type=TYPE.CYLINDER,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(_computeBounds(vertices,matrices),options.minHalfExtent,options.maxHalfExtent));const btHalfExtents=new Ammo.btVector3(options.halfExtents.x,options.halfExtents.y,options.halfExtents.z),collisionShape=(()=>{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(matrixWorld,options)),collisionShape};exports.createCylinderShape=createCylinderShape;const createCapsuleShape=function(vertices,matrices,matrixWorld,options={}){options.type=TYPE.CAPSULE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(_computeBounds(vertices,matrices),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(matrixWorld,options)),collisionShape};exports.createCapsuleShape=createCapsuleShape;const createConeShape=function(vertices,matrices,matrixWorld,options={}){options.type=TYPE.CONE,_setOptions(options),options.fit===FIT.ALL&&(options.halfExtents=_computeHalfExtents(_computeBounds(vertices,matrices),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(matrixWorld,options)),collisionShape};exports.createConeShape=createConeShape;const createSphereShape=function(vertices,matrices,matrixWorld,options={}){let radius;options.type=TYPE.SPHERE,_setOptions(options),radius=options.fit!==FIT.MANUAL||isNaN(options.sphereRadius)?_computeRadius(vertices,matrices,_computeBounds(vertices,matrices)):options.sphereRadius;const collisionShape=new Ammo.btSphereShape(radius);return _finishCollisionShape(collisionShape,options,_computeScale(matrixWorld,options)),collisionShape};exports.createSphereShape=createSphereShape;const createHullShape=function(){const vertex=new THREE.Vector3,center=new THREE.Vector3,matrix=new THREE.Matrix4;return function(vertices,matrices,matrixWorld,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(vertices,matrices),btVertex=new Ammo.btVector3,originalHull=new Ammo.btConvexHullShape;originalHull.setMargin(options.margin),center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);let vertexCount=0;for(let i=0;imaxVertices&&console.warn(`too many vertices for hull shape; sampling ~${maxVertices} from ~${vertexCount} vertices`);const p=Math.min(1,maxVertices/vertexCount);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(matrixWorld,options)),collisionShape}}();exports.createHullShape=createHullShape;const createHACDShapes=function(){const vector=new THREE.Vector3,center=new THREE.Vector3,matrix=new THREE.Matrix4;return function(vertices,matrices,indexes,matrixWorld,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(vertices,matrices),scale=_computeScale(matrixWorld,options);let vertexCount=0,triCount=0;center.addVectors(bounds.max,bounds.min).multiplyScalar(.5);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 inverse=new THREE.Matrix4;return function(root,options,cb){inverse.copy(root.matrixWorld).invert(),(new THREE.Vector3).setFromMatrixScale(root.matrixWorld),root.traverse(mesh=>{const transform=new THREE.Matrix4;mesh.isMesh&&"Sky"!==mesh.name&&(options.includeInvisible||mesh.el&&mesh.el.object3D.visible||mesh.visible)&&(mesh===root?transform.identity():(mesh.updateWorldMatrix(!0),transform.multiplyMatrices(inverse,mesh.matrixWorld)),cb(mesh.geometry.isBufferGeometry?mesh.geometry.attributes.position.array:mesh.geometry.vertices,transform.elements,mesh.geometry.index?mesh.geometry.index.array:null))})}}();exports.iterateGeometries=iterateGeometries;const _computeScale=function(){const matrix=new THREE.Matrix4;return function(matrixWorld,options={}){const scale=new THREE.Vector3(1,1,1);return options.fit===FIT.ALL&&(matrix.fromArray(matrixWorld),scale.setFromMatrixScale(matrix)),scale}}(),_computeRadius=function(){const center=new THREE.Vector3;return function(vertices,matrices,bounds){let maxRadiusSq=0,{x:cx,y:cy,z:cz}=bounds.getCenter(center);return _iterateVertices(vertices,matrices,v=>{const dx=cx-v.x,dy=cy-v.y,dz=cz-v.z;maxRadiusSq=Math.max(maxRadiusSq,dx*dx+dy*dy+dz*dz)}),Math.sqrt(maxRadiusSq)}}(),_computeHalfExtents=function(bounds,minHalfExtent,maxHalfExtent){return(new THREE.Vector3).subVectors(bounds.max,bounds.min).multiplyScalar(.5).clampScalar(minHalfExtent,maxHalfExtent)},_computeBounds=function(vertices,matrices){const bounds=new THREE.Box3;let minX=1/0,minY=1/0,minZ=1/0,maxX=-1/0,maxY=-1/0,maxZ=-1/0;return bounds.min.set(0,0,0),bounds.max.set(0,0,0),_iterateVertices(vertices,matrices,v=>{v.xmaxX&&(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},_iterateVertices=function(){const vertex=new THREE.Vector3,matrix=new THREE.Matrix4;return function(vertices,matrices,cb){for(let i=0;if.toArray()),uniqueSrcIndices=Array.from(new Set(srcIndices.flat())).sort(),dstPositions=[];for(let i=0;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.MathUtils.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"),{AmmoDebugDrawer:AmmoDebugDrawer,AmmoDebugConstants:AmmoDebugConstants}=require("ammo-debug-drawer");"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||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 AmmoDebugDrawer(scene,this.physicsWorld,options)),this.debugDrawer}},{"./driver":21,"ammo-debug-drawer":3}],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;i{const counterValue=document.createElement("div");counterValue.classList.add("rs-counter-value"),counterValue.innerHTML="...",this.counter.appendChild(counterValue),this.counterValues[property]=counterValue}),this.updateData=this.updateData.bind(this),this.el.addEventListener(this.data.event,this.updateData),this.splitCache={}):console.warn(`Couldn't find stats group ${groupComponentName}`)},updateData(e){this.data.properties.forEach(property=>{const split=this.splitDot(property);let value=e.detail;for(i=0;i{this.outputDetail[property]={}}),this.statsReceived=this.statsReceived.bind(this),this.el.addEventListener(this.data.inEvent,this.statsReceived)},resetData(){this.counter=0,this.data.properties.forEach(property=>{this.statsData[property]=[]})},statsReceived(e){this.updateData(e.detail),this.counter++,this.counter===this.data.outputFrequency&&(this.outputData(),this.resetData())},updateData(detail){this.data.properties.forEach(property=>{let value=detail;value=value[property],this.statsData[property].push(value)})},outputData(){this.data.properties.forEach(property=>{this.data.outputs.forEach(output=>{this.outputDetail[property][output]=this.computeOutput(output,this.statsData[property])})}),this.data.outEvent&&this.el.emit(this.data.outEvent,this.outputDetail),this.data.outputToConsole&&console.log(this.data.outputToConsole,this.outputDetail)},computeOutput(outputInstruction,data){const outputInstructions=outputInstruction.split("__");let output;switch(outputInstructions[0]){case"mean":output=data.reduce((a,b)=>a+b,0)/data.length;break;case"max":output=Math.max(...data);break;case"min":output=Math.min(...data);break;case"percentile":const sorted=data.sort((a,b)=>a-b),proportion=+outputInstructions[1].replace("_",".")/100,position=(data.length-1)*proportion,base=Math.floor(position),delta=position-base;output=void 0!==sorted[base+1]?sorted[base]+delta*(sorted[base+1]-sorted[base]):sorted[base]}return output.toFixed(2)}})},{}],4:[function(require,module,exports){THREE.AmmoDebugConstants={NoDebug:0,DrawWireframe:1,DrawAabb:2,DrawFeaturesText:4,DrawContactPoints:8,NoDeactivation:16,NoHelpText:32,DrawText:64,ProfileTimings:128,EnableSatComparison:256,DisableBulletLCP:512,EnableCCD:1024,DrawConstraints:2048,DrawConstraintLimits:4096,FastWireframe:8192,DrawNormals:16384,DrawOnTop:32768,MAX_DEBUG_DRAW_MODE:4294967295},THREE.AmmoDebugDrawer=function(scene,world,options){this.scene=scene,this.world=world,options=options||{},this.debugDrawMode=options.debugDrawMode||THREE.AmmoDebugConstants.DrawWireframe;var drawOnTop=this.debugDrawMode&THREE.AmmoDebugConstants.DrawOnTop||!1,maxBufferSize=options.maxBufferSize||1e6;this.geometry=new THREE.BufferGeometry;var vertices=new Float32Array(3*maxBufferSize),colors=new Float32Array(3*maxBufferSize);this.geometry.setAttribute("position",new THREE.BufferAttribute(vertices,3).setUsage(THREE.DynamicDrawUsage)),this.geometry.setAttribute("color",new THREE.BufferAttribute(colors,3).setUsage(THREE.DynamicDrawUsage)),this.index=0;var material=new THREE.LineBasicMaterial({vertexColors:!0,depthTest:!drawOnTop});this.mesh=new THREE.LineSegments(this.geometry,material),drawOnTop&&(this.mesh.renderOrder=999),this.mesh.frustumCulled=!1,this.enabled=!1,this.debugDrawer=new Ammo.DebugDrawer,this.debugDrawer.drawLine=this.drawLine.bind(this),this.debugDrawer.drawContactPoint=this.drawContactPoint.bind(this),this.debugDrawer.reportErrorWarning=this.reportErrorWarning.bind(this),this.debugDrawer.draw3dText=this.draw3dText.bind(this),this.debugDrawer.setDebugMode=this.setDebugMode.bind(this),this.debugDrawer.getDebugMode=this.getDebugMode.bind(this),this.debugDrawer.enable=this.enable.bind(this),this.debugDrawer.disable=this.disable.bind(this),this.debugDrawer.update=this.update.bind(this),this.world.setDebugDrawer(this.debugDrawer)},THREE.AmmoDebugDrawer.prototype=function(){return this.debugDrawer},THREE.AmmoDebugDrawer.prototype.enable=function(){this.enabled=!0,this.scene.add(this.mesh)},THREE.AmmoDebugDrawer.prototype.disable=function(){this.enabled=!1,this.scene.remove(this.mesh)},THREE.AmmoDebugDrawer.prototype.update=function(){this.enabled&&(0!=this.index&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0),this.index=0,this.world.debugDrawWorld(),this.geometry.setDrawRange(0,this.index))},THREE.AmmoDebugDrawer.prototype.drawLine=function(from,to,color){const heap=Ammo.HEAPF32,r=heap[(color+0)/4],g=heap[(color+4)/4],b=heap[(color+8)/4],fromX=heap[(from+0)/4],fromY=heap[(from+4)/4],fromZ=heap[(from+8)/4];this.geometry.attributes.position.setXYZ(this.index,fromX,fromY,fromZ),this.geometry.attributes.color.setXYZ(this.index++,r,g,b);const toX=heap[(to+0)/4],toY=heap[(to+4)/4],toZ=heap[(to+8)/4];this.geometry.attributes.position.setXYZ(this.index,toX,toY,toZ),this.geometry.attributes.color.setXYZ(this.index++,r,g,b)},THREE.AmmoDebugDrawer.prototype.drawContactPoint=function(pointOnB,normalOnB,distance,lifeTime,color){const heap=Ammo.HEAPF32,r=heap[(color+0)/4],g=heap[(color+4)/4],b=heap[(color+8)/4],x=heap[(pointOnB+0)/4],y=heap[(pointOnB+4)/4],z=heap[(pointOnB+8)/4];this.geometry.attributes.position.setXYZ(this.index,x,y,z),this.geometry.attributes.color.setXYZ(this.index++,r,g,b);const dx=heap[(normalOnB+0)/4]*distance,dy=heap[(normalOnB+4)/4]*distance,dz=heap[(normalOnB+8)/4]*distance;this.geometry.attributes.position.setXYZ(this.index,x+dx,y+dy,z+dz),this.geometry.attributes.color.setXYZ(this.index++,r,g,b)},THREE.AmmoDebugDrawer.prototype.reportErrorWarning=function(warningString){Ammo.hasOwnProperty("Pointer_stringify")?console.warn(Ammo.Pointer_stringify(warningString)):this.warnedOnce||(this.warnedOnce=!0,console.warn("Cannot print warningString, please rebuild Ammo.js using 'debug' flag"))},THREE.AmmoDebugDrawer.prototype.draw3dText=function(location,textString){console.warn("TODO: draw3dText")},THREE.AmmoDebugDrawer.prototype.setDebugMode=function(debugMode){this.debugDrawMode=debugMode},THREE.AmmoDebugDrawer.prototype.getDebugMode=function(){return this.debugDrawMode}},{}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var ObjectCollisionMatrix=function(){function ObjectCollisionMatrix(){this.matrix={}}var _proto=ObjectCollisionMatrix.prototype;return _proto.get=function(bi,bj){var i=bi.id,j=bj.id;if(j>i){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.copy(root.matrixWorld).invert(),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}}()},{}],7:[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.rbInfo.m_restitution=((num,min,max)=>Math.min(Math.max(num,min),max))(this.data.restitution,0,1),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":20,"three-to-ammo":6}],18:[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.MathUtils.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":5}],19:[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":5}],20:[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"}}},{}],21:[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":22}],22:[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},{}],23:[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"}},{}],24:[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":22,"cannon-es":5}],25:[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":22}],26:[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;ithis.countBodiesAmmo(),local:()=>this.countBodiesCannon(!1),worker:()=>this.countBodiesCannon(!0)},this.bodyTypeToStatsPropertyMap={ammo:{[TYPE.STATIC]:"staticBodies",[TYPE.KINEMATIC]:"kinematicBodies",[TYPE.DYNAMIC]:"dynamicBodies"},cannon:{[CANNON.Body.STATIC]:"staticBodies",[CANNON.Body.DYNAMIC]:"dynamicBodies"}},this.el.sceneEl.setAttribute("stats-collector","inEvent: physics-tick-data;\n properties: before, after, engine, total;\n outputFrequency: 100;\n outEvent: physics-tick-summary;\n outputs: percentile__50, percentile__90, max")}if(this.statsToPanel){const scene=this.el.sceneEl,space="   ";scene.setAttribute("stats-panel",""),scene.setAttribute("stats-group__bodies","label: Physics Bodies"),scene.setAttribute("stats-row__b1","group: bodies;\n event:physics-body-data;\n properties: staticBodies;\n label: Static"),scene.setAttribute("stats-row__b2","group: bodies;\n event:physics-body-data;\n properties: dynamicBodies;\n label: Dynamic"),"local"===this.data.driver||"worker"===this.data.driver?scene.setAttribute("stats-row__b3","group: bodies;\n event:physics-body-data;\n properties: contacts;\n label: Contacts"):"ammo"===this.data.driver&&(scene.setAttribute("stats-row__b3","group: bodies;\n event:physics-body-data;\n properties: kinematicBodies;\n label: Kinematic"),scene.setAttribute("stats-row__b4","group: bodies;\n event: physics-body-data;\n properties: manifolds;\n label: Manifolds"),scene.setAttribute("stats-row__b5","group: bodies;\n event: physics-body-data;\n properties: manifoldContacts;\n label: Contacts"),scene.setAttribute("stats-row__b6","group: bodies;\n event: physics-body-data;\n properties: collisions;\n label: Collisions"),scene.setAttribute("stats-row__b7","group: bodies;\n event: physics-body-data;\n properties: collisionKeys;\n label: Coll Keys")),scene.setAttribute("stats-group__tick",`label: Physics Ticks: Median${space}90th%${space}99th%`),scene.setAttribute("stats-row__1","group: tick;\n event:physics-tick-summary;\n properties: before.percentile__50, \n before.percentile__90, \n before.max;\n label: Before"),scene.setAttribute("stats-row__2","group: tick;\n event:physics-tick-summary;\n properties: after.percentile__50, \n after.percentile__90, \n after.max; \n label: After"),scene.setAttribute("stats-row__3","group: tick; \n event:physics-tick-summary; \n properties: engine.percentile__50, \n engine.percentile__90, \n engine.max;\n label: Engine"),scene.setAttribute("stats-row__4","group: tick;\n event:physics-tick-summary;\n properties: total.percentile__50, \n total.percentile__90, \n total.max;\n label: Total")}},tick:function(t,dt){if(!this.initialized||!dt)return;const beforeStartTime=performance.now();var i,callbacks=this.callbacks;for(i=0;i{const property=this.bodyTypeToStatsPropertyMap.ammo[(el=el,el.components["ammo-body"].data.type)];statsData[property]++})},countBodiesCannon(worker){const statsData=this.statsBodyData;statsData.contacts=worker?this.driver.contacts.length:this.driver.world.contacts.length,statsData.staticBodies=0,statsData.dynamicBodies=0,(worker?Object.values(this.driver.bodies):this.driver.world.bodies).forEach(body=>{const property=this.bodyTypeToStatsPropertyMap.cannon[body.type];statsData[property]++})},setDebug:function(debug){this.debug=debug,"ammo"===this.data.driver&&this.initialized&&(debug&&!this.debugDrawer?(this.debugDrawer=this.driver.getDebugDrawer(this.el.object3D),this.debugDrawer.enable()):this.debugDrawer&&(this.debugDrawer.disable(),this.debugDrawer=null))},addBody:function(body,group,mask){var driver=this.driver;"local"===this.data.driver&&(body.__applyImpulse=body.applyImpulse,body.applyImpulse=function(){driver.applyBodyMethod(body,"applyImpulse",arguments)},body.__applyForce=body.applyForce,body.applyForce=function(){driver.applyBodyMethod(body,"applyForce",arguments)},body.updateProperties=function(){driver.updateBodyProperties(body)},this.listeners[body.id]=function(e){body.el.emit("collide",e)},body.addEventListener("collide",this.listeners[body.id])),this.driver.addBody(body,group,mask)},removeBody:function(body){this.driver.removeBody(body),"local"!==this.data.driver&&"worker"!==this.data.driver||(body.removeEventListener("collide",this.listeners[body.id]),delete this.listeners[body.id],body.applyImpulse=body.__applyImpulse,delete body.__applyImpulse,body.applyForce=body.__applyForce,delete body.__applyForce,delete body.updateProperties)},addConstraint:function(constraint){this.driver.addConstraint(constraint)},removeConstraint:function(constraint){this.driver.removeConstraint(constraint)},addComponent:function(component){var callbacks=this.callbacks;component.beforeStep&&callbacks.beforeStep.push(component),component.step&&callbacks.step.push(component),component.afterStep&&callbacks.afterStep.push(component)},removeComponent:function(component){var callbacks=this.callbacks;component.beforeStep&&callbacks.beforeStep.splice(callbacks.beforeStep.indexOf(component),1),component.step&&callbacks.step.splice(callbacks.step.indexOf(component),1),component.afterStep&&callbacks.afterStep.splice(callbacks.afterStep.indexOf(component),1)},getContacts:function(){return this.driver.getContacts()},getMaterial:function(name){return this.driver.getMaterial(name)}})},{"./constants":20,"./drivers/ammo-driver":21,"./drivers/local-driver":24,"./drivers/network-driver":25,"./drivers/worker-driver":27,"aframe-stats-panel":3,"cannon-es":5}],30:[function(require,module,exports){module.exports.slerp=function(a,b,t){if(t<=0)return a;if(t>=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}},{}],31:[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":30,"cannon-es":5}]},{},[1]); \ No newline at end of file