(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("rogue-engine"), require("three"));
	else if(typeof define === 'function' && define.amd)
		define(["rogue-engine", "three"], factory);
	else if(typeof exports === 'object')
		exports["rogue-engine-user-scripts"] = factory(require("rogue-engine"), require("three"));
	else
		root["rogue-engine-user-scripts"] = factory(root["rogue-engine"], root["three"]);
})(self, (__WEBPACK_EXTERNAL_MODULE_rogue_engine__, __WEBPACK_EXTERNAL_MODULE_three__) => {
return /******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js":
/*!*************************************************************!*\
  !*** ./node_modules/@dimforge/rapier3d-compat/rapier.es.js ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ActiveCollisionTypes: () => (/* binding */ UA),
/* harmony export */   ActiveEvents: () => (/* binding */ FA),
/* harmony export */   ActiveHooks: () => (/* binding */ qA),
/* harmony export */   Ball: () => (/* binding */ EI),
/* harmony export */   BroadPhase: () => (/* binding */ VA),
/* harmony export */   CCDSolver: () => (/* binding */ mA),
/* harmony export */   Capsule: () => (/* binding */ GI),
/* harmony export */   CharacterCollision: () => (/* binding */ tI),
/* harmony export */   CoefficientCombineRule: () => (/* binding */ KA),
/* harmony export */   Collider: () => (/* binding */ qI),
/* harmony export */   ColliderDesc: () => (/* binding */ RI),
/* harmony export */   ColliderSet: () => (/* binding */ sI),
/* harmony export */   Cone: () => (/* binding */ NI),
/* harmony export */   ConvexPolyhedron: () => (/* binding */ KI),
/* harmony export */   Cuboid: () => (/* binding */ DI),
/* harmony export */   Cylinder: () => (/* binding */ UI),
/* harmony export */   DebugRenderBuffers: () => (/* binding */ HI),
/* harmony export */   DebugRenderPipeline: () => (/* binding */ lI),
/* harmony export */   EventQueue: () => (/* binding */ dI),
/* harmony export */   FeatureType: () => (/* binding */ yA),
/* harmony export */   FixedImpulseJoint: () => (/* binding */ pA),
/* harmony export */   FixedMultibodyJoint: () => (/* binding */ bA),
/* harmony export */   HalfSpace: () => (/* binding */ iI),
/* harmony export */   Heightfield: () => (/* binding */ JI),
/* harmony export */   ImpulseJoint: () => (/* binding */ lA),
/* harmony export */   ImpulseJointSet: () => (/* binding */ OA),
/* harmony export */   IntegrationParameters: () => (/* binding */ HA),
/* harmony export */   IslandManager: () => (/* binding */ XA),
/* harmony export */   JointData: () => (/* binding */ TA),
/* harmony export */   JointType: () => (/* binding */ aA),
/* harmony export */   KinematicCharacterController: () => (/* binding */ pI),
/* harmony export */   MassPropsMode: () => (/* binding */ hA),
/* harmony export */   MotorModel: () => (/* binding */ MA),
/* harmony export */   MultibodyJoint: () => (/* binding */ nA),
/* harmony export */   MultibodyJointSet: () => (/* binding */ fA),
/* harmony export */   NarrowPhase: () => (/* binding */ PA),
/* harmony export */   PhysicsPipeline: () => (/* binding */ cI),
/* harmony export */   PointColliderProjection: () => (/* binding */ _A),
/* harmony export */   PointProjection: () => (/* binding */ vA),
/* harmony export */   Polyline: () => (/* binding */ aI),
/* harmony export */   PrismaticImpulseJoint: () => (/* binding */ eA),
/* harmony export */   PrismaticMultibodyJoint: () => (/* binding */ WA),
/* harmony export */   Quaternion: () => (/* binding */ oA),
/* harmony export */   QueryFilterFlags: () => (/* binding */ NA),
/* harmony export */   QueryPipeline: () => (/* binding */ YI),
/* harmony export */   Ray: () => (/* binding */ $A),
/* harmony export */   RayColliderIntersection: () => (/* binding */ II),
/* harmony export */   RayColliderToi: () => (/* binding */ gI),
/* harmony export */   RayIntersection: () => (/* binding */ AI),
/* harmony export */   RevoluteImpulseJoint: () => (/* binding */ rA),
/* harmony export */   RevoluteMultibodyJoint: () => (/* binding */ jA),
/* harmony export */   RigidBody: () => (/* binding */ sA),
/* harmony export */   RigidBodyDesc: () => (/* binding */ cA),
/* harmony export */   RigidBodySet: () => (/* binding */ LA),
/* harmony export */   RigidBodyType: () => (/* binding */ SA),
/* harmony export */   RotationOps: () => (/* binding */ GA),
/* harmony export */   RoundCone: () => (/* binding */ FI),
/* harmony export */   RoundConvexPolyhedron: () => (/* binding */ yI),
/* harmony export */   RoundCuboid: () => (/* binding */ oI),
/* harmony export */   RoundCylinder: () => (/* binding */ hI),
/* harmony export */   RoundTriangle: () => (/* binding */ SI),
/* harmony export */   SdpMatrix3: () => (/* binding */ wA),
/* harmony export */   SdpMatrix3Ops: () => (/* binding */ kA),
/* harmony export */   Segment: () => (/* binding */ wI),
/* harmony export */   SerializationPipeline: () => (/* binding */ LI),
/* harmony export */   Shape: () => (/* binding */ QI),
/* harmony export */   ShapeColliderTOI: () => (/* binding */ BI),
/* harmony export */   ShapeContact: () => (/* binding */ uA),
/* harmony export */   ShapeTOI: () => (/* binding */ CI),
/* harmony export */   ShapeType: () => (/* binding */ JA),
/* harmony export */   SolverFlags: () => (/* binding */ RA),
/* harmony export */   SphericalImpulseJoint: () => (/* binding */ dA),
/* harmony export */   SphericalMultibodyJoint: () => (/* binding */ xA),
/* harmony export */   TempContactForceEvent: () => (/* binding */ rI),
/* harmony export */   TempContactManifold: () => (/* binding */ zA),
/* harmony export */   TriMesh: () => (/* binding */ MI),
/* harmony export */   Triangle: () => (/* binding */ kI),
/* harmony export */   UnitImpulseJoint: () => (/* binding */ tA),
/* harmony export */   UnitMultibodyJoint: () => (/* binding */ ZA),
/* harmony export */   Vector3: () => (/* binding */ iA),
/* harmony export */   VectorOps: () => (/* binding */ DA),
/* harmony export */   World: () => (/* binding */ eI),
/* harmony export */   "default": () => (/* binding */ PI),
/* harmony export */   init: () => (/* binding */ XI),
/* harmony export */   version: () => (/* binding */ VI)
/* harmony export */ });
let A;const I=new Array(32).fill(void 0);function g(A){return I[A]}I.push(void 0,null,!0,!1);let C=I.length;function B(A){const B=g(A);return function(A){A<36||(I[A]=C,C=A)}(A),B}function Q(A){C===I.length&&I.push(I.length+1);const g=C;return C=I[g],I[g]=A,g}function E(A){return null==A}let i=new Float64Array;function D(){return 0===i.byteLength&&(i=new Float64Array(A.memory.buffer)),i}let o=new Int32Array;function G(){return 0===o.byteLength&&(o=new Int32Array(A.memory.buffer)),o}const w=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});w.decode();let k=new Uint8Array;function S(I,g){return w.decode((0===k.byteLength&&(k=new Uint8Array(A.memory.buffer)),k).subarray(I,I+g))}function a(A,I){if(!(A instanceof I))throw new Error(`expected instance of ${I.name}`);return A.ptr}let M=new Float32Array;function K(){return 0===M.byteLength&&(M=new Float32Array(A.memory.buffer)),M}let y=32;function J(A){if(1==y)throw new Error("out of js stack");return I[--y]=A,y}function U(A,I){return K().subarray(A/4,A/4+I)}let h=new Uint32Array;function N(){return 0===h.byteLength&&(h=new Uint32Array(A.memory.buffer)),h}let F=0;function q(A,I){const g=I(4*A.length);return K().set(A,g/4),F=A.length,g}function R(A,I){const g=I(4*A.length);return N().set(A,g/4),F=A.length,g}function s(I,g){try{return I.apply(this,g)}catch(I){A.__wbindgen_exn_store(Q(I))}}Object.freeze({Revolute:0,0:"Revolute",Fixed:1,1:"Fixed",Prismatic:2,2:"Prismatic",Spherical:3,3:"Spherical",Generic:4,4:"Generic"}),Object.freeze({AccelerationBased:0,0:"AccelerationBased",ForceBased:1,1:"ForceBased"});const c=Object.freeze({X:0,0:"X",Y:1,1:"Y",Z:2,2:"Z",AngX:3,3:"AngX",AngY:4,4:"AngY",AngZ:5,5:"AngZ"});Object.freeze({Dynamic:0,0:"Dynamic",Fixed:1,1:"Fixed",KinematicPositionBased:2,2:"KinematicPositionBased",KinematicVelocityBased:3,3:"KinematicVelocityBased"}),Object.freeze({Vertex:0,0:"Vertex",Edge:1,1:"Edge",Face:2,2:"Face",Unknown:3,3:"Unknown"}),Object.freeze({Ball:0,0:"Ball",Cuboid:1,1:"Cuboid",Capsule:2,2:"Capsule",Segment:3,3:"Segment",Polyline:4,4:"Polyline",Triangle:5,5:"Triangle",TriMesh:6,6:"TriMesh",HeightField:7,7:"HeightField",Compound:8,8:"Compound",ConvexPolyhedron:9,9:"ConvexPolyhedron",Cylinder:10,10:"Cylinder",Cone:11,11:"Cone",RoundCuboid:12,12:"RoundCuboid",RoundTriangle:13,13:"RoundTriangle",RoundCylinder:14,14:"RoundCylinder",RoundCone:15,15:"RoundCone",RoundConvexPolyhedron:16,16:"RoundConvexPolyhedron",HalfSpace:17,17:"HalfSpace"});class Y{static __wrap(A){const I=Object.create(Y.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawbroadphase_free(I)}constructor(){const I=A.rawbroadphase_new();return Y.__wrap(I)}}class L{static __wrap(A){const I=Object.create(L.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawccdsolver_free(I)}constructor(){const I=A.rawccdsolver_new();return L.__wrap(I)}}class H{static __wrap(A){const I=Object.create(H.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawcharactercollision_free(I)}constructor(){const I=A.rawcharactercollision_new();return H.__wrap(I)}handle(){return A.rawcharactercollision_handle(this.ptr)}translationApplied(){const I=A.rawcharactercollision_translationApplied(this.ptr);return QA.__wrap(I)}translationRemaining(){const I=A.rawcharactercollision_translationRemaining(this.ptr);return QA.__wrap(I)}toi(){return A.rawcharactercollision_toi(this.ptr)}worldWitness1(){const I=A.rawcharactercollision_worldWitness1(this.ptr);return QA.__wrap(I)}worldWitness2(){const I=A.rawcharactercollision_worldWitness2(this.ptr);return QA.__wrap(I)}worldNormal1(){const I=A.rawcharactercollision_worldNormal1(this.ptr);return QA.__wrap(I)}worldNormal2(){const I=A.rawcharactercollision_worldNormal2(this.ptr);return QA.__wrap(I)}}class l{static __wrap(A){const I=Object.create(l.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawcolliderset_free(I)}coTranslation(I){const g=A.rawcolliderset_coTranslation(this.ptr,I);return QA.__wrap(g)}coRotation(I){const g=A.rawcolliderset_coRotation(this.ptr,I);return _.__wrap(g)}coSetTranslation(I,g,C,B){A.rawcolliderset_coSetTranslation(this.ptr,I,g,C,B)}coSetTranslationWrtParent(I,g,C,B){A.rawcolliderset_coSetTranslationWrtParent(this.ptr,I,g,C,B)}coSetRotation(I,g,C,B,Q){A.rawcolliderset_coSetRotation(this.ptr,I,g,C,B,Q)}coSetRotationWrtParent(I,g,C,B,Q){A.rawcolliderset_coSetRotationWrtParent(this.ptr,I,g,C,B,Q)}coIsSensor(I){return 0!==A.rawcolliderset_coIsSensor(this.ptr,I)}coShapeType(I){return A.rawcolliderset_coShapeType(this.ptr,I)>>>0}coHalfspaceNormal(I){const g=A.rawcolliderset_coHalfspaceNormal(this.ptr,I);return 0===g?void 0:QA.__wrap(g)}coHalfExtents(I){const g=A.rawcolliderset_coHalfExtents(this.ptr,I);return 0===g?void 0:QA.__wrap(g)}coSetHalfExtents(I,g){a(g,QA),A.rawcolliderset_coSetHalfExtents(this.ptr,I,g.ptr)}coRadius(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coRadius(B,this.ptr,I);var g=G()[B/4+0],C=K()[B/4+1];return 0===g?void 0:C}finally{A.__wbindgen_add_to_stack_pointer(16)}}coSetRadius(I,g){A.rawcolliderset_coSetRadius(this.ptr,I,g)}coHalfHeight(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coHalfHeight(B,this.ptr,I);var g=G()[B/4+0],C=K()[B/4+1];return 0===g?void 0:C}finally{A.__wbindgen_add_to_stack_pointer(16)}}coSetHalfHeight(I,g){A.rawcolliderset_coSetHalfHeight(this.ptr,I,g)}coRoundRadius(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coRoundRadius(B,this.ptr,I);var g=G()[B/4+0],C=K()[B/4+1];return 0===g?void 0:C}finally{A.__wbindgen_add_to_stack_pointer(16)}}coSetRoundRadius(I,g){A.rawcolliderset_coSetRoundRadius(this.ptr,I,g)}coVertices(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coVertices(B,this.ptr,I);var g=G()[B/4+0],C=G()[B/4+1];let Q;return 0!==g&&(Q=U(g,C).slice(),A.__wbindgen_free(g,4*C)),Q}finally{A.__wbindgen_add_to_stack_pointer(16)}}coIndices(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coIndices(B,this.ptr,I);var g=G()[B/4+0],C=G()[B/4+1];let Q;return 0!==g&&(Q=function(A,I){return N().subarray(A/4,A/4+I)}(g,C).slice(),A.__wbindgen_free(g,4*C)),Q}finally{A.__wbindgen_add_to_stack_pointer(16)}}coHeightfieldHeights(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coHeightfieldHeights(B,this.ptr,I);var g=G()[B/4+0],C=G()[B/4+1];let Q;return 0!==g&&(Q=U(g,C).slice(),A.__wbindgen_free(g,4*C)),Q}finally{A.__wbindgen_add_to_stack_pointer(16)}}coHeightfieldScale(I){const g=A.rawcolliderset_coHeightfieldScale(this.ptr,I);return 0===g?void 0:QA.__wrap(g)}coHeightfieldNRows(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coHeightfieldNRows(B,this.ptr,I);var g=G()[B/4+0],C=G()[B/4+1];return 0===g?void 0:C>>>0}finally{A.__wbindgen_add_to_stack_pointer(16)}}coHeightfieldNCols(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coHeightfieldNCols(B,this.ptr,I);var g=G()[B/4+0],C=G()[B/4+1];return 0===g?void 0:C>>>0}finally{A.__wbindgen_add_to_stack_pointer(16)}}coParent(I){try{const B=A.__wbindgen_add_to_stack_pointer(-16);A.rawcolliderset_coParent(B,this.ptr,I);var g=G()[B/4+0],C=D()[B/8+1];return 0===g?void 0:C}finally{A.__wbindgen_add_to_stack_pointer(16)}}coSetEnabled(I,g){A.rawcolliderset_coSetEnabled(this.ptr,I,g)}coIsEnabled(I){return 0!==A.rawcolliderset_coIsEnabled(this.ptr,I)}coFriction(I){return A.rawcolliderset_coFriction(this.ptr,I)}coRestitution(I){return A.rawcolliderset_coRestitution(this.ptr,I)}coDensity(I){return A.rawcolliderset_coDensity(this.ptr,I)}coMass(I){return A.rawcolliderset_coMass(this.ptr,I)}coVolume(I){return A.rawcolliderset_coVolume(this.ptr,I)}coCollisionGroups(I){return A.rawcolliderset_coCollisionGroups(this.ptr,I)>>>0}coSolverGroups(I){return A.rawcolliderset_coSolverGroups(this.ptr,I)>>>0}coActiveHooks(I){return A.rawcolliderset_coActiveHooks(this.ptr,I)>>>0}coActiveCollisionTypes(I){return A.rawcolliderset_coActiveCollisionTypes(this.ptr,I)}coActiveEvents(I){return A.rawcolliderset_coActiveEvents(this.ptr,I)>>>0}coContactForceEventThreshold(I){return A.rawcolliderset_coContactForceEventThreshold(this.ptr,I)}coContainsPoint(I,g){a(g,QA);return 0!==A.rawcolliderset_coContainsPoint(this.ptr,I,g.ptr)}coCastShape(I,g,C,B,Q,E,i,D){a(g,QA),a(C,IA),a(B,QA),a(Q,_),a(E,QA);const o=A.rawcolliderset_coCastShape(this.ptr,I,g.ptr,C.ptr,B.ptr,Q.ptr,E.ptr,i,D);return 0===o?void 0:BA.__wrap(o)}coCastCollider(I,g,C,B,Q,E){a(g,QA),a(B,QA);const i=A.rawcolliderset_coCastCollider(this.ptr,I,g.ptr,C,B.ptr,Q,E);return 0===i?void 0:gA.__wrap(i)}coIntersectsShape(I,g,C,B){a(g,IA),a(C,QA),a(B,_);return 0!==A.rawcolliderset_coIntersectsShape(this.ptr,I,g.ptr,C.ptr,B.ptr)}coContactShape(I,g,C,B,Q){a(g,IA),a(C,QA),a(B,_);const E=A.rawcolliderset_coContactShape(this.ptr,I,g.ptr,C.ptr,B.ptr,Q);return 0===E?void 0:CA.__wrap(E)}coContactCollider(I,g,C){const B=A.rawcolliderset_coContactCollider(this.ptr,I,g,C);return 0===B?void 0:CA.__wrap(B)}coProjectPoint(I,g,C){a(g,QA);const B=A.rawcolliderset_coProjectPoint(this.ptr,I,g.ptr,C);return X.__wrap(B)}coIntersectsRay(I,g,C,B){a(g,QA),a(C,QA);return 0!==A.rawcolliderset_coIntersectsRay(this.ptr,I,g.ptr,C.ptr,B)}coCastRay(I,g,C,B,Q){a(g,QA),a(C,QA);return A.rawcolliderset_coCastRay(this.ptr,I,g.ptr,C.ptr,B,Q)}coCastRayAndGetNormal(I,g,C,B,Q){a(g,QA),a(C,QA);const E=A.rawcolliderset_coCastRayAndGetNormal(this.ptr,I,g.ptr,C.ptr,B,Q);return 0===E?void 0:u.__wrap(E)}coSetSensor(I,g){A.rawcolliderset_coSetSensor(this.ptr,I,g)}coSetRestitution(I,g){A.rawcolliderset_coSetRestitution(this.ptr,I,g)}coSetFriction(I,g){A.rawcolliderset_coSetFriction(this.ptr,I,g)}coFrictionCombineRule(I){return A.rawcolliderset_coFrictionCombineRule(this.ptr,I)>>>0}coSetFrictionCombineRule(I,g){A.rawcolliderset_coSetFrictionCombineRule(this.ptr,I,g)}coRestitutionCombineRule(I){return A.rawcolliderset_coRestitutionCombineRule(this.ptr,I)>>>0}coSetRestitutionCombineRule(I,g){A.rawcolliderset_coSetRestitutionCombineRule(this.ptr,I,g)}coSetCollisionGroups(I,g){A.rawcolliderset_coSetCollisionGroups(this.ptr,I,g)}coSetSolverGroups(I,g){A.rawcolliderset_coSetSolverGroups(this.ptr,I,g)}coSetActiveHooks(I,g){A.rawcolliderset_coSetActiveHooks(this.ptr,I,g)}coSetActiveEvents(I,g){A.rawcolliderset_coSetActiveEvents(this.ptr,I,g)}coSetActiveCollisionTypes(I,g){A.rawcolliderset_coSetActiveCollisionTypes(this.ptr,I,g)}coSetShape(I,g){a(g,IA),A.rawcolliderset_coSetShape(this.ptr,I,g.ptr)}coSetContactForceEventThreshold(I,g){A.rawcolliderset_coSetContactForceEventThreshold(this.ptr,I,g)}coSetDensity(I,g){A.rawcolliderset_coSetDensity(this.ptr,I,g)}coSetMass(I,g){A.rawcolliderset_coSetMass(this.ptr,I,g)}coSetMassProperties(I,g,C,B,Q){a(C,QA),a(B,QA),a(Q,_),A.rawcolliderset_coSetMassProperties(this.ptr,I,g,C.ptr,B.ptr,Q.ptr)}constructor(){const I=A.rawcolliderset_new();return l.__wrap(I)}len(){return A.rawcolliderset_len(this.ptr)>>>0}contains(I){return 0!==A.rawcolliderset_contains(this.ptr,I)}createCollider(I,g,C,B,Q,E,i,o,w,k,S,M,K,y,J,U,h,N,F,q,R,s,c,Y){try{const l=A.__wbindgen_add_to_stack_pointer(-16);a(g,IA),a(C,QA),a(B,_),a(i,QA),a(o,QA),a(w,_),a(Y,v),A.rawcolliderset_createCollider(l,this.ptr,I,g.ptr,C.ptr,B.ptr,Q,E,i.ptr,o.ptr,w.ptr,k,S,M,K,y,J,U,h,N,F,q,R,s,c,Y.ptr);var L=G()[l/4+0],H=D()[l/8+1];return 0===L?void 0:H}finally{A.__wbindgen_add_to_stack_pointer(16)}}remove(I,g,C,B){a(g,b),a(C,v),A.rawcolliderset_remove(this.ptr,I,g.ptr,C.ptr,B)}isHandleValid(I){return 0!==A.rawcolliderset_contains(this.ptr,I)}forEachColliderHandle(g){try{A.rawcolliderset_forEachColliderHandle(this.ptr,J(g))}finally{I[y++]=void 0}}}class t{static __wrap(A){const I=Object.create(t.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawcontactforceevent_free(I)}collider1(){return A.rawcharactercollision_handle(this.ptr)}collider2(){return A.rawcontactforceevent_collider2(this.ptr)}total_force(){const I=A.rawcontactforceevent_total_force(this.ptr);return QA.__wrap(I)}total_force_magnitude(){return A.rawcontactforceevent_total_force_magnitude(this.ptr)}max_force_direction(){const I=A.rawcontactforceevent_max_force_direction(this.ptr);return QA.__wrap(I)}max_force_magnitude(){return A.rawcontactforceevent_max_force_magnitude(this.ptr)}}class p{static __wrap(A){const I=Object.create(p.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawcontactmanifold_free(I)}normal(){const I=A.rawcontactmanifold_normal(this.ptr);return QA.__wrap(I)}local_n1(){const I=A.rawcontactmanifold_local_n1(this.ptr);return QA.__wrap(I)}local_n2(){const I=A.rawcontactmanifold_local_n2(this.ptr);return QA.__wrap(I)}subshape1(){return A.rawcontactmanifold_subshape1(this.ptr)>>>0}subshape2(){return A.rawcontactmanifold_subshape2(this.ptr)>>>0}num_contacts(){return A.rawcontactmanifold_num_contacts(this.ptr)>>>0}contact_local_p1(I){const g=A.rawcontactmanifold_contact_local_p1(this.ptr,I);return 0===g?void 0:QA.__wrap(g)}contact_local_p2(I){const g=A.rawcontactmanifold_contact_local_p2(this.ptr,I);return 0===g?void 0:QA.__wrap(g)}contact_dist(I){return A.rawcontactmanifold_contact_dist(this.ptr,I)}contact_fid1(I){return A.rawcontactmanifold_contact_fid1(this.ptr,I)>>>0}contact_fid2(I){return A.rawcontactmanifold_contact_fid2(this.ptr,I)>>>0}contact_impulse(I){return A.rawcontactmanifold_contact_impulse(this.ptr,I)}contact_tangent_impulse_x(I){return A.rawcontactmanifold_contact_tangent_impulse_x(this.ptr,I)}contact_tangent_impulse_y(I){return A.rawcontactmanifold_contact_tangent_impulse_y(this.ptr,I)}num_solver_contacts(){return A.rawcontactmanifold_num_solver_contacts(this.ptr)>>>0}solver_contact_point(I){const g=A.rawcontactmanifold_solver_contact_point(this.ptr,I);return 0===g?void 0:QA.__wrap(g)}solver_contact_dist(I){return A.rawcontactmanifold_solver_contact_dist(this.ptr,I)}solver_contact_friction(I){return A.rawcontactmanifold_solver_contact_friction(this.ptr,I)}solver_contact_restitution(I){return A.rawcontactmanifold_solver_contact_restitution(this.ptr,I)}solver_contact_tangent_velocity(I){const g=A.rawcontactmanifold_solver_contact_tangent_velocity(this.ptr,I);return QA.__wrap(g)}}class e{static __wrap(A){const I=Object.create(e.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawcontactpair_free(I)}collider1(){return A.rawcontactpair_collider1(this.ptr)}collider2(){return A.rawcontactpair_collider2(this.ptr)}numContactManifolds(){return A.rawcontactpair_numContactManifolds(this.ptr)>>>0}contactManifold(I){const g=A.rawcontactpair_contactManifold(this.ptr,I);return 0===g?void 0:p.__wrap(g)}}class r{static __wrap(A){const I=Object.create(r.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawdebugrenderpipeline_free(I)}constructor(){const I=A.rawdebugrenderpipeline_new();return r.__wrap(I)}vertices(){return B(A.rawdebugrenderpipeline_vertices(this.ptr))}colors(){return B(A.rawdebugrenderpipeline_colors(this.ptr))}render(I,g,C,B,Q){a(I,v),a(g,l),a(C,n),a(B,j),a(Q,x),A.rawdebugrenderpipeline_render(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q.ptr)}}class d{static __wrap(A){const I=Object.create(d.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawdeserializedworld_free(I)}takeGravity(){const I=A.rawdeserializedworld_takeGravity(this.ptr);return 0===I?void 0:QA.__wrap(I)}takeIntegrationParameters(){const I=A.rawdeserializedworld_takeIntegrationParameters(this.ptr);return 0===I?void 0:Z.__wrap(I)}takeIslandManager(){const I=A.rawdeserializedworld_takeIslandManager(this.ptr);return 0===I?void 0:b.__wrap(I)}takeBroadPhase(){const I=A.rawdeserializedworld_takeBroadPhase(this.ptr);return 0===I?void 0:Y.__wrap(I)}takeNarrowPhase(){const I=A.rawdeserializedworld_takeNarrowPhase(this.ptr);return 0===I?void 0:x.__wrap(I)}takeBodies(){const I=A.rawdeserializedworld_takeBodies(this.ptr);return 0===I?void 0:v.__wrap(I)}takeColliders(){const I=A.rawdeserializedworld_takeColliders(this.ptr);return 0===I?void 0:l.__wrap(I)}takeImpulseJoints(){const I=A.rawdeserializedworld_takeImpulseJoints(this.ptr);return 0===I?void 0:n.__wrap(I)}takeMultibodyJoints(){const I=A.rawdeserializedworld_takeMultibodyJoints(this.ptr);return 0===I?void 0:j.__wrap(I)}}class T{static __wrap(A){const I=Object.create(T.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_raweventqueue_free(I)}constructor(I){const g=A.raweventqueue_new(I);return T.__wrap(g)}drainCollisionEvents(g){try{A.raweventqueue_drainCollisionEvents(this.ptr,J(g))}finally{I[y++]=void 0}}drainContactForceEvents(g){try{A.raweventqueue_drainContactForceEvents(this.ptr,J(g))}finally{I[y++]=void 0}}clear(){A.raweventqueue_clear(this.ptr)}}class O{static __wrap(A){const I=Object.create(O.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawgenericjoint_free(I)}static spherical(I,g){a(I,QA),a(g,QA);const C=A.rawgenericjoint_spherical(I.ptr,g.ptr);return O.__wrap(C)}static prismatic(I,g,C,B,Q,E){a(I,QA),a(g,QA),a(C,QA);const i=A.rawgenericjoint_prismatic(I.ptr,g.ptr,C.ptr,B,Q,E);return 0===i?void 0:O.__wrap(i)}static fixed(I,g,C,B){a(I,QA),a(g,_),a(C,QA),a(B,_);const Q=A.rawgenericjoint_fixed(I.ptr,g.ptr,C.ptr,B.ptr);return O.__wrap(Q)}static revolute(I,g,C){a(I,QA),a(g,QA),a(C,QA);const B=A.rawgenericjoint_revolute(I.ptr,g.ptr,C.ptr);return 0===B?void 0:O.__wrap(B)}}class n{static __wrap(A){const I=Object.create(n.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawimpulsejointset_free(I)}jointType(I){return A.rawimpulsejointset_jointType(this.ptr,I)>>>0}jointBodyHandle1(I){return A.rawimpulsejointset_jointBodyHandle1(this.ptr,I)}jointBodyHandle2(I){return A.rawimpulsejointset_jointBodyHandle2(this.ptr,I)}jointFrameX1(I){const g=A.rawimpulsejointset_jointFrameX1(this.ptr,I);return _.__wrap(g)}jointFrameX2(I){const g=A.rawimpulsejointset_jointFrameX2(this.ptr,I);return _.__wrap(g)}jointAnchor1(I){const g=A.rawimpulsejointset_jointAnchor1(this.ptr,I);return QA.__wrap(g)}jointAnchor2(I){const g=A.rawimpulsejointset_jointAnchor2(this.ptr,I);return QA.__wrap(g)}jointSetAnchor1(I,g){a(g,QA),A.rawimpulsejointset_jointSetAnchor1(this.ptr,I,g.ptr)}jointSetAnchor2(I,g){a(g,QA),A.rawimpulsejointset_jointSetAnchor2(this.ptr,I,g.ptr)}jointContactsEnabled(I){return 0!==A.rawimpulsejointset_jointContactsEnabled(this.ptr,I)}jointSetContactsEnabled(I,g){A.rawimpulsejointset_jointSetContactsEnabled(this.ptr,I,g)}jointLimitsEnabled(I,g){return 0!==A.rawimpulsejointset_jointLimitsEnabled(this.ptr,I,g)}jointLimitsMin(I,g){return A.rawimpulsejointset_jointLimitsMin(this.ptr,I,g)}jointLimitsMax(I,g){return A.rawimpulsejointset_jointLimitsMax(this.ptr,I,g)}jointSetLimits(I,g,C,B){A.rawimpulsejointset_jointSetLimits(this.ptr,I,g,C,B)}jointConfigureMotorModel(I,g,C){A.rawimpulsejointset_jointConfigureMotorModel(this.ptr,I,g,C)}jointConfigureMotorVelocity(I,g,C,B){A.rawimpulsejointset_jointConfigureMotorVelocity(this.ptr,I,g,C,B)}jointConfigureMotorPosition(I,g,C,B,Q){A.rawimpulsejointset_jointConfigureMotorPosition(this.ptr,I,g,C,B,Q)}jointConfigureMotor(I,g,C,B,Q,E){A.rawimpulsejointset_jointConfigureMotor(this.ptr,I,g,C,B,Q,E)}constructor(){const I=A.rawimpulsejointset_new();return n.__wrap(I)}createJoint(I,g,C,B){a(I,O);return A.rawimpulsejointset_createJoint(this.ptr,I.ptr,g,C,B)}remove(I,g){A.rawimpulsejointset_remove(this.ptr,I,g)}len(){return A.rawimpulsejointset_len(this.ptr)>>>0}contains(I){return 0!==A.rawimpulsejointset_contains(this.ptr,I)}forEachJointHandle(g){try{A.rawimpulsejointset_forEachJointHandle(this.ptr,J(g))}finally{I[y++]=void 0}}forEachJointAttachedToRigidBody(g,C){try{A.rawimpulsejointset_forEachJointAttachedToRigidBody(this.ptr,g,J(C))}finally{I[y++]=void 0}}}class Z{static __wrap(A){const I=Object.create(Z.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawintegrationparameters_free(I)}constructor(){const I=A.rawintegrationparameters_new();return Z.__wrap(I)}get dt(){return A.rawintegrationparameters_dt(this.ptr)}get erp(){return A.rawcharactercollision_toi(this.ptr)}get allowedLinearError(){return A.rawintegrationparameters_allowedLinearError(this.ptr)}get predictionDistance(){return A.rawintegrationparameters_predictionDistance(this.ptr)}get maxVelocityIterations(){return A.rawintegrationparameters_maxVelocityIterations(this.ptr)>>>0}get maxVelocityFrictionIterations(){return A.rawintegrationparameters_maxVelocityFrictionIterations(this.ptr)>>>0}get maxStabilizationIterations(){return A.rawintegrationparameters_maxStabilizationIterations(this.ptr)>>>0}get minIslandSize(){return A.rawintegrationparameters_minIslandSize(this.ptr)>>>0}get maxCcdSubsteps(){return A.rawintegrationparameters_maxCcdSubsteps(this.ptr)>>>0}set dt(I){A.rawintegrationparameters_set_dt(this.ptr,I)}set erp(I){A.rawintegrationparameters_set_erp(this.ptr,I)}set allowedLinearError(I){A.rawintegrationparameters_set_allowedLinearError(this.ptr,I)}set predictionDistance(I){A.rawintegrationparameters_set_predictionDistance(this.ptr,I)}set maxVelocityIterations(I){A.rawintegrationparameters_set_maxVelocityIterations(this.ptr,I)}set maxVelocityFrictionIterations(I){A.rawintegrationparameters_set_maxVelocityFrictionIterations(this.ptr,I)}set maxStabilizationIterations(I){A.rawintegrationparameters_set_maxStabilizationIterations(this.ptr,I)}set minIslandSize(I){A.rawintegrationparameters_set_minIslandSize(this.ptr,I)}set maxCcdSubsteps(I){A.rawintegrationparameters_set_maxCcdSubsteps(this.ptr,I)}}class b{static __wrap(A){const I=Object.create(b.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawislandmanager_free(I)}constructor(){const I=A.rawislandmanager_new();return b.__wrap(I)}forEachActiveRigidBodyHandle(g){try{A.rawislandmanager_forEachActiveRigidBodyHandle(this.ptr,J(g))}finally{I[y++]=void 0}}}class W{static __wrap(A){const I=Object.create(W.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawkinematiccharactercontroller_free(I)}constructor(I){const g=A.rawkinematiccharactercontroller_new(I);return W.__wrap(g)}up(){const I=A.rawkinematiccharactercontroller_up(this.ptr);return QA.__wrap(I)}setUp(I){a(I,QA),A.rawkinematiccharactercontroller_setUp(this.ptr,I.ptr)}offset(){return A.rawkinematiccharactercontroller_offset(this.ptr)}setOffset(I){A.rawkinematiccharactercontroller_setOffset(this.ptr,I)}slideEnabled(){return 0!==A.rawkinematiccharactercontroller_slideEnabled(this.ptr)}setSlideEnabled(I){A.rawkinematiccharactercontroller_setSlideEnabled(this.ptr,I)}autostepMaxHeight(){try{const C=A.__wbindgen_add_to_stack_pointer(-16);A.rawkinematiccharactercontroller_autostepMaxHeight(C,this.ptr);var I=G()[C/4+0],g=K()[C/4+1];return 0===I?void 0:g}finally{A.__wbindgen_add_to_stack_pointer(16)}}autostepMinWidth(){try{const C=A.__wbindgen_add_to_stack_pointer(-16);A.rawkinematiccharactercontroller_autostepMinWidth(C,this.ptr);var I=G()[C/4+0],g=K()[C/4+1];return 0===I?void 0:g}finally{A.__wbindgen_add_to_stack_pointer(16)}}autostepIncludesDynamicBodies(){const I=A.rawkinematiccharactercontroller_autostepIncludesDynamicBodies(this.ptr);return 16777215===I?void 0:0!==I}autostepEnabled(){return 0!==A.rawkinematiccharactercontroller_autostepEnabled(this.ptr)}enableAutostep(I,g,C){A.rawkinematiccharactercontroller_enableAutostep(this.ptr,I,g,C)}disableAutostep(){A.rawkinematiccharactercontroller_disableAutostep(this.ptr)}maxSlopeClimbAngle(){return A.rawkinematiccharactercontroller_maxSlopeClimbAngle(this.ptr)}setMaxSlopeClimbAngle(I){A.rawkinematiccharactercontroller_setMaxSlopeClimbAngle(this.ptr,I)}minSlopeSlideAngle(){return A.rawkinematiccharactercontroller_minSlopeSlideAngle(this.ptr)}setMinSlopeSlideAngle(I){A.rawkinematiccharactercontroller_setMinSlopeSlideAngle(this.ptr,I)}snapToGroundDistance(){try{const C=A.__wbindgen_add_to_stack_pointer(-16);A.rawkinematiccharactercontroller_snapToGroundDistance(C,this.ptr);var I=G()[C/4+0],g=K()[C/4+1];return 0===I?void 0:g}finally{A.__wbindgen_add_to_stack_pointer(16)}}enableSnapToGround(I){A.rawkinematiccharactercontroller_enableSnapToGround(this.ptr,I)}disableSnapToGround(){A.rawkinematiccharactercontroller_disableSnapToGround(this.ptr)}snapToGroundEnabled(){return 0!==A.rawkinematiccharactercontroller_snapToGroundEnabled(this.ptr)}computeColliderMovement(g,C,B,Q,i,D,o,G,w,k,S){try{a(C,v),a(B,l),a(Q,V),a(D,QA),A.rawkinematiccharactercontroller_computeColliderMovement(this.ptr,g,C.ptr,B.ptr,Q.ptr,i,D.ptr,o,!E(G),E(G)?0:G,w,!E(k),E(k)?0:k,J(S))}finally{I[y++]=void 0}}computedMovement(){const I=A.rawkinematiccharactercontroller_computedMovement(this.ptr);return QA.__wrap(I)}computedGrounded(){return 0!==A.rawkinematiccharactercontroller_computedGrounded(this.ptr)}numComputedCollisions(){return A.rawkinematiccharactercontroller_numComputedCollisions(this.ptr)>>>0}computedCollision(I,g){a(g,H);return 0!==A.rawkinematiccharactercontroller_computedCollision(this.ptr,I,g.ptr)}}class j{static __wrap(A){const I=Object.create(j.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawmultibodyjointset_free(I)}jointType(I){return A.rawmultibodyjointset_jointType(this.ptr,I)>>>0}jointFrameX1(I){const g=A.rawmultibodyjointset_jointFrameX1(this.ptr,I);return _.__wrap(g)}jointFrameX2(I){const g=A.rawmultibodyjointset_jointFrameX2(this.ptr,I);return _.__wrap(g)}jointAnchor1(I){const g=A.rawmultibodyjointset_jointAnchor1(this.ptr,I);return QA.__wrap(g)}jointAnchor2(I){const g=A.rawmultibodyjointset_jointAnchor2(this.ptr,I);return QA.__wrap(g)}jointContactsEnabled(I){return 0!==A.rawmultibodyjointset_jointContactsEnabled(this.ptr,I)}jointSetContactsEnabled(I,g){A.rawmultibodyjointset_jointSetContactsEnabled(this.ptr,I,g)}jointLimitsEnabled(I,g){return 0!==A.rawmultibodyjointset_jointLimitsEnabled(this.ptr,I,g)}jointLimitsMin(I,g){return A.rawmultibodyjointset_jointLimitsMin(this.ptr,I,g)}jointLimitsMax(I,g){return A.rawmultibodyjointset_jointLimitsMax(this.ptr,I,g)}constructor(){const I=A.rawmultibodyjointset_new();return j.__wrap(I)}createJoint(I,g,C,B){a(I,O);return A.rawmultibodyjointset_createJoint(this.ptr,I.ptr,g,C,B)}remove(I,g){A.rawmultibodyjointset_remove(this.ptr,I,g)}contains(I){return 0!==A.rawmultibodyjointset_contains(this.ptr,I)}forEachJointHandle(g){try{A.rawmultibodyjointset_forEachJointHandle(this.ptr,J(g))}finally{I[y++]=void 0}}forEachJointAttachedToRigidBody(g,C){try{A.rawmultibodyjointset_forEachJointAttachedToRigidBody(this.ptr,g,J(C))}finally{I[y++]=void 0}}}class x{static __wrap(A){const I=Object.create(x.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawnarrowphase_free(I)}constructor(){const I=A.rawnarrowphase_new();return x.__wrap(I)}contacts_with(I,g){A.rawnarrowphase_contacts_with(this.ptr,I,Q(g))}contact_pair(I,g){const C=A.rawnarrowphase_contact_pair(this.ptr,I,g);return 0===C?void 0:e.__wrap(C)}intersections_with(I,g){A.rawnarrowphase_intersections_with(this.ptr,I,Q(g))}intersection_pair(I,g){return 0!==A.rawnarrowphase_intersection_pair(this.ptr,I,g)}}class f{static __wrap(A){const I=Object.create(f.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawphysicspipeline_free(I)}constructor(){const I=A.rawphysicspipeline_new();return f.__wrap(I)}step(I,g,C,B,Q,E,i,D,o,G){a(I,QA),a(g,Z),a(C,b),a(B,Y),a(Q,x),a(E,v),a(i,l),a(D,n),a(o,j),a(G,L),A.rawphysicspipeline_step(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,E.ptr,i.ptr,D.ptr,o.ptr,G.ptr)}stepWithEvents(I,g,C,B,E,i,D,o,G,w,k,S,M,K){a(I,QA),a(g,Z),a(C,b),a(B,Y),a(E,x),a(i,v),a(D,l),a(o,n),a(G,j),a(w,L),a(k,T),A.rawphysicspipeline_stepWithEvents(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,E.ptr,i.ptr,D.ptr,o.ptr,G.ptr,w.ptr,k.ptr,Q(S),Q(M),Q(K))}}class m{static __wrap(A){const I=Object.create(m.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawpointcolliderprojection_free(I)}colliderHandle(){return A.rawpointcolliderprojection_colliderHandle(this.ptr)}point(){const I=A.rawkinematiccharactercontroller_computedMovement(this.ptr);return QA.__wrap(I)}isInside(){return 0!==A.rawkinematiccharactercontroller_computedGrounded(this.ptr)}featureType(){return A.rawpointcolliderprojection_featureType(this.ptr)>>>0}featureId(){try{const C=A.__wbindgen_add_to_stack_pointer(-16);A.rawpointcolliderprojection_featureId(C,this.ptr);var I=G()[C/4+0],g=G()[C/4+1];return 0===I?void 0:g>>>0}finally{A.__wbindgen_add_to_stack_pointer(16)}}}class X{static __wrap(A){const I=Object.create(X.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawpointprojection_free(I)}point(){const I=A.rawkinematiccharactercontroller_computedMovement(this.ptr);return QA.__wrap(I)}isInside(){return 0!==A.rawkinematiccharactercontroller_computedGrounded(this.ptr)}}class V{static __wrap(A){const I=Object.create(V.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawquerypipeline_free(I)}constructor(){const I=A.rawquerypipeline_new();return V.__wrap(I)}update(I,g){a(I,v),a(g,l),A.rawquerypipeline_update(this.ptr,I.ptr,g.ptr)}castRay(g,C,B,Q,i,D,o,G,w,k,S){try{a(g,v),a(C,l),a(B,QA),a(Q,QA);const M=A.rawquerypipeline_castRay(this.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,i,D,o,!E(G),E(G)?0:G,!E(w),E(w)?0:w,!E(k),E(k)?0:k,J(S));return 0===M?void 0:z.__wrap(M)}finally{I[y++]=void 0}}castRayAndGetNormal(g,C,B,Q,i,D,o,G,w,k,S){try{a(g,v),a(C,l),a(B,QA),a(Q,QA);const M=A.rawquerypipeline_castRayAndGetNormal(this.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,i,D,o,!E(G),E(G)?0:G,!E(w),E(w)?0:w,!E(k),E(k)?0:k,J(S));return 0===M?void 0:P.__wrap(M)}finally{I[y++]=void 0}}intersectionsWithRay(g,C,B,Q,i,D,o,G,w,k,S,M){try{a(g,v),a(C,l),a(B,QA),a(Q,QA),A.rawquerypipeline_intersectionsWithRay(this.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,i,D,J(o),G,!E(w),E(w)?0:w,!E(k),E(k)?0:k,!E(S),E(S)?0:S,J(M))}finally{I[y++]=void 0,I[y++]=void 0}}intersectionWithShape(g,C,B,Q,i,o,w,k,S,M){try{const h=A.__wbindgen_add_to_stack_pointer(-16);a(g,v),a(C,l),a(B,QA),a(Q,_),a(i,IA),A.rawquerypipeline_intersectionWithShape(h,this.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,i.ptr,o,!E(w),E(w)?0:w,!E(k),E(k)?0:k,!E(S),E(S)?0:S,J(M));var K=G()[h/4+0],U=D()[h/8+1];return 0===K?void 0:U}finally{A.__wbindgen_add_to_stack_pointer(16),I[y++]=void 0}}projectPoint(g,C,B,Q,i,D,o,G,w){try{a(g,v),a(C,l),a(B,QA);const k=A.rawquerypipeline_projectPoint(this.ptr,g.ptr,C.ptr,B.ptr,Q,i,!E(D),E(D)?0:D,!E(o),E(o)?0:o,!E(G),E(G)?0:G,J(w));return 0===k?void 0:m.__wrap(k)}finally{I[y++]=void 0}}projectPointAndGetFeature(g,C,B,Q,i,D,o,G){try{a(g,v),a(C,l),a(B,QA);const w=A.rawquerypipeline_projectPointAndGetFeature(this.ptr,g.ptr,C.ptr,B.ptr,Q,!E(i),E(i)?0:i,!E(D),E(D)?0:D,!E(o),E(o)?0:o,J(G));return 0===w?void 0:m.__wrap(w)}finally{I[y++]=void 0}}intersectionsWithPoint(g,C,B,Q,i,D,o,G,w){try{a(g,v),a(C,l),a(B,QA),A.rawquerypipeline_intersectionsWithPoint(this.ptr,g.ptr,C.ptr,B.ptr,J(Q),i,!E(D),E(D)?0:D,!E(o),E(o)?0:o,!E(G),E(G)?0:G,J(w))}finally{I[y++]=void 0,I[y++]=void 0}}castShape(g,C,B,Q,i,D,o,G,w,k,S,M,K){try{a(g,v),a(C,l),a(B,QA),a(Q,_),a(i,QA),a(D,IA);const U=A.rawquerypipeline_castShape(this.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,i.ptr,D.ptr,o,G,w,!E(k),E(k)?0:k,!E(S),E(S)?0:S,!E(M),E(M)?0:M,J(K));return 0===U?void 0:gA.__wrap(U)}finally{I[y++]=void 0}}intersectionsWithShape(g,C,B,Q,i,D,o,G,w,k,S){try{a(g,v),a(C,l),a(B,QA),a(Q,_),a(i,IA),A.rawquerypipeline_intersectionsWithShape(this.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,i.ptr,J(D),o,!E(G),E(G)?0:G,!E(w),E(w)?0:w,!E(k),E(k)?0:k,J(S))}finally{I[y++]=void 0,I[y++]=void 0}}collidersWithAabbIntersectingAabb(g,C,B){try{a(g,QA),a(C,QA),A.rawquerypipeline_collidersWithAabbIntersectingAabb(this.ptr,g.ptr,C.ptr,J(B))}finally{I[y++]=void 0}}}class P{static __wrap(A){const I=Object.create(P.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawraycolliderintersection_free(I)}colliderHandle(){return A.rawcharactercollision_handle(this.ptr)}normal(){const I=A.rawraycolliderintersection_normal(this.ptr);return QA.__wrap(I)}toi(){return A.rawraycolliderintersection_toi(this.ptr)}featureType(){return A.rawraycolliderintersection_featureType(this.ptr)>>>0}featureId(){try{const C=A.__wbindgen_add_to_stack_pointer(-16);A.rawraycolliderintersection_featureId(C,this.ptr);var I=G()[C/4+0],g=G()[C/4+1];return 0===I?void 0:g>>>0}finally{A.__wbindgen_add_to_stack_pointer(16)}}}class z{static __wrap(A){const I=Object.create(z.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawraycollidertoi_free(I)}colliderHandle(){return A.rawcharactercollision_handle(this.ptr)}toi(){return A.rawcharactercollision_toi(this.ptr)}}class u{static __wrap(A){const I=Object.create(u.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawrayintersection_free(I)}normal(){const I=A.rawcharactercollision_worldWitness1(this.ptr);return QA.__wrap(I)}toi(){return A.rawcharactercollision_toi(this.ptr)}featureType(){return A.rawrayintersection_featureType(this.ptr)>>>0}featureId(){try{const C=A.__wbindgen_add_to_stack_pointer(-16);A.rawrayintersection_featureId(C,this.ptr);var I=G()[C/4+0],g=G()[C/4+1];return 0===I?void 0:g>>>0}finally{A.__wbindgen_add_to_stack_pointer(16)}}}class v{static __wrap(A){const I=Object.create(v.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawrigidbodyset_free(I)}rbTranslation(I){const g=A.rawrigidbodyset_rbTranslation(this.ptr,I);return QA.__wrap(g)}rbRotation(I){const g=A.rawrigidbodyset_rbRotation(this.ptr,I);return _.__wrap(g)}rbSleep(I){A.rawrigidbodyset_rbSleep(this.ptr,I)}rbIsSleeping(I){return 0!==A.rawrigidbodyset_rbIsSleeping(this.ptr,I)}rbIsMoving(I){return 0!==A.rawrigidbodyset_rbIsMoving(this.ptr,I)}rbNextTranslation(I){const g=A.rawrigidbodyset_rbNextTranslation(this.ptr,I);return QA.__wrap(g)}rbNextRotation(I){const g=A.rawrigidbodyset_rbNextRotation(this.ptr,I);return _.__wrap(g)}rbSetTranslation(I,g,C,B,Q){A.rawrigidbodyset_rbSetTranslation(this.ptr,I,g,C,B,Q)}rbSetRotation(I,g,C,B,Q,E){A.rawrigidbodyset_rbSetRotation(this.ptr,I,g,C,B,Q,E)}rbSetLinvel(I,g,C){a(g,QA),A.rawrigidbodyset_rbSetLinvel(this.ptr,I,g.ptr,C)}rbSetAngvel(I,g,C){a(g,QA),A.rawrigidbodyset_rbSetAngvel(this.ptr,I,g.ptr,C)}rbSetNextKinematicTranslation(I,g,C,B){A.rawrigidbodyset_rbSetNextKinematicTranslation(this.ptr,I,g,C,B)}rbSetNextKinematicRotation(I,g,C,B,Q){A.rawrigidbodyset_rbSetNextKinematicRotation(this.ptr,I,g,C,B,Q)}rbRecomputeMassPropertiesFromColliders(I,g){a(g,l),A.rawrigidbodyset_rbRecomputeMassPropertiesFromColliders(this.ptr,I,g.ptr)}rbSetAdditionalMass(I,g,C){A.rawrigidbodyset_rbSetAdditionalMass(this.ptr,I,g,C)}rbSetAdditionalMassProperties(I,g,C,B,Q,E){a(C,QA),a(B,QA),a(Q,_),A.rawrigidbodyset_rbSetAdditionalMassProperties(this.ptr,I,g,C.ptr,B.ptr,Q.ptr,E)}rbLinvel(I){const g=A.rawrigidbodyset_rbLinvel(this.ptr,I);return QA.__wrap(g)}rbAngvel(I){const g=A.rawrigidbodyset_rbAngvel(this.ptr,I);return QA.__wrap(g)}rbLockTranslations(I,g,C){A.rawrigidbodyset_rbLockTranslations(this.ptr,I,g,C)}rbSetEnabledTranslations(I,g,C,B,Q){A.rawrigidbodyset_rbSetEnabledTranslations(this.ptr,I,g,C,B,Q)}rbLockRotations(I,g,C){A.rawrigidbodyset_rbLockRotations(this.ptr,I,g,C)}rbSetEnabledRotations(I,g,C,B,Q){A.rawrigidbodyset_rbSetEnabledRotations(this.ptr,I,g,C,B,Q)}rbDominanceGroup(I){return A.rawrigidbodyset_rbDominanceGroup(this.ptr,I)}rbSetDominanceGroup(I,g){A.rawrigidbodyset_rbSetDominanceGroup(this.ptr,I,g)}rbEnableCcd(I,g){A.rawrigidbodyset_rbEnableCcd(this.ptr,I,g)}rbMass(I){return A.rawrigidbodyset_rbMass(this.ptr,I)}rbInvMass(I){return A.rawrigidbodyset_rbInvMass(this.ptr,I)}rbEffectiveInvMass(I){const g=A.rawrigidbodyset_rbEffectiveInvMass(this.ptr,I);return QA.__wrap(g)}rbLocalCom(I){const g=A.rawrigidbodyset_rbLocalCom(this.ptr,I);return QA.__wrap(g)}rbWorldCom(I){const g=A.rawrigidbodyset_rbWorldCom(this.ptr,I);return QA.__wrap(g)}rbInvPrincipalInertiaSqrt(I){const g=A.rawrigidbodyset_rbInvPrincipalInertiaSqrt(this.ptr,I);return QA.__wrap(g)}rbPrincipalInertiaLocalFrame(I){const g=A.rawrigidbodyset_rbPrincipalInertiaLocalFrame(this.ptr,I);return _.__wrap(g)}rbPrincipalInertia(I){const g=A.rawrigidbodyset_rbPrincipalInertia(this.ptr,I);return QA.__wrap(g)}rbEffectiveWorldInvInertiaSqrt(I){const g=A.rawrigidbodyset_rbEffectiveWorldInvInertiaSqrt(this.ptr,I);return $.__wrap(g)}rbEffectiveAngularInertia(I){const g=A.rawrigidbodyset_rbEffectiveAngularInertia(this.ptr,I);return $.__wrap(g)}rbWakeUp(I){A.rawrigidbodyset_rbWakeUp(this.ptr,I)}rbIsCcdEnabled(I){return 0!==A.rawrigidbodyset_rbIsCcdEnabled(this.ptr,I)}rbNumColliders(I){return A.rawrigidbodyset_rbNumColliders(this.ptr,I)>>>0}rbCollider(I,g){return A.rawrigidbodyset_rbCollider(this.ptr,I,g)}rbBodyType(I){return A.rawrigidbodyset_rbBodyType(this.ptr,I)>>>0}rbSetBodyType(I,g,C){A.rawrigidbodyset_rbSetBodyType(this.ptr,I,g,C)}rbIsFixed(I){return 0!==A.rawrigidbodyset_rbIsFixed(this.ptr,I)}rbIsKinematic(I){return 0!==A.rawrigidbodyset_rbIsKinematic(this.ptr,I)}rbIsDynamic(I){return 0!==A.rawrigidbodyset_rbIsDynamic(this.ptr,I)}rbLinearDamping(I){return A.rawrigidbodyset_rbLinearDamping(this.ptr,I)}rbAngularDamping(I){return A.rawrigidbodyset_rbAngularDamping(this.ptr,I)}rbSetLinearDamping(I,g){A.rawrigidbodyset_rbSetLinearDamping(this.ptr,I,g)}rbSetAngularDamping(I,g){A.rawrigidbodyset_rbSetAngularDamping(this.ptr,I,g)}rbSetEnabled(I,g){A.rawrigidbodyset_rbSetEnabled(this.ptr,I,g)}rbIsEnabled(I){return 0!==A.rawrigidbodyset_rbIsEnabled(this.ptr,I)}rbGravityScale(I){return A.rawrigidbodyset_rbGravityScale(this.ptr,I)}rbSetGravityScale(I,g,C){A.rawrigidbodyset_rbSetGravityScale(this.ptr,I,g,C)}rbResetForces(I,g){A.rawrigidbodyset_rbResetForces(this.ptr,I,g)}rbResetTorques(I,g){A.rawrigidbodyset_rbResetTorques(this.ptr,I,g)}rbAddForce(I,g,C){a(g,QA),A.rawrigidbodyset_rbAddForce(this.ptr,I,g.ptr,C)}rbApplyImpulse(I,g,C){a(g,QA),A.rawrigidbodyset_rbApplyImpulse(this.ptr,I,g.ptr,C)}rbAddTorque(I,g,C){a(g,QA),A.rawrigidbodyset_rbAddTorque(this.ptr,I,g.ptr,C)}rbApplyTorqueImpulse(I,g,C){a(g,QA),A.rawrigidbodyset_rbApplyTorqueImpulse(this.ptr,I,g.ptr,C)}rbAddForceAtPoint(I,g,C,B){a(g,QA),a(C,QA),A.rawrigidbodyset_rbAddForceAtPoint(this.ptr,I,g.ptr,C.ptr,B)}rbApplyImpulseAtPoint(I,g,C,B){a(g,QA),a(C,QA),A.rawrigidbodyset_rbApplyImpulseAtPoint(this.ptr,I,g.ptr,C.ptr,B)}rbUserData(I){return A.rawrigidbodyset_rbUserData(this.ptr,I)>>>0}rbSetUserData(I,g){A.rawrigidbodyset_rbSetUserData(this.ptr,I,g)}constructor(){const I=A.rawrigidbodyset_new();return v.__wrap(I)}createRigidBody(I,g,C,B,Q,E,i,D,o,G,w,k,S,M,K,y,J,U,h,N,F,q,R,s){a(g,QA),a(C,_),a(i,QA),a(D,QA),a(o,QA),a(G,QA),a(w,_);return A.rawrigidbodyset_createRigidBody(this.ptr,I,g.ptr,C.ptr,B,Q,E,i.ptr,D.ptr,o.ptr,G.ptr,w.ptr,k,S,M,K,y,J,U,h,N,F,q,R,s)}remove(I,g,C,B,Q){a(g,b),a(C,l),a(B,n),a(Q,j),A.rawrigidbodyset_remove(this.ptr,I,g.ptr,C.ptr,B.ptr,Q.ptr)}len(){return A.rawrigidbodyset_len(this.ptr)>>>0}contains(I){return 0!==A.rawrigidbodyset_contains(this.ptr,I)}forEachRigidBodyHandle(g){try{A.rawrigidbodyset_forEachRigidBodyHandle(this.ptr,J(g))}finally{I[y++]=void 0}}propagateModifiedBodyPositionsToColliders(I){a(I,l),A.rawrigidbodyset_propagateModifiedBodyPositionsToColliders(this.ptr,I.ptr)}}class _{static __wrap(A){const I=Object.create(_.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawrotation_free(I)}constructor(I,g,C,B){const Q=A.rawrotation_new(I,g,C,B);return _.__wrap(Q)}static identity(){const I=A.rawrotation_identity();return _.__wrap(I)}get x(){return A.rawintegrationparameters_dt(this.ptr)}get y(){return A.rawrotation_y(this.ptr)}get z(){return A.rawcharactercollision_toi(this.ptr)}get w(){return A.rawrotation_w(this.ptr)}}class ${static __wrap(A){const I=Object.create($.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawsdpmatrix3_free(I)}elements(){return B(A.rawsdpmatrix3_elements(this.ptr))}}class AA{static __wrap(A){const I=Object.create(AA.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawserializationpipeline_free(I)}constructor(){const I=A.rawserializationpipeline_new();return AA.__wrap(I)}serializeAll(I,g,C,Q,E,i,D,o,G){a(I,QA),a(g,Z),a(C,b),a(Q,Y),a(E,x),a(i,v),a(D,l),a(o,n),a(G,j);return B(A.rawserializationpipeline_serializeAll(this.ptr,I.ptr,g.ptr,C.ptr,Q.ptr,E.ptr,i.ptr,D.ptr,o.ptr,G.ptr))}deserializeAll(I){const g=A.rawserializationpipeline_deserializeAll(this.ptr,Q(I));return 0===g?void 0:d.__wrap(g)}}class IA{static __wrap(A){const I=Object.create(IA.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawshape_free(I)}static cuboid(I,g,C){const B=A.rawshape_cuboid(I,g,C);return IA.__wrap(B)}static roundCuboid(I,g,C,B){const Q=A.rawshape_roundCuboid(I,g,C,B);return IA.__wrap(Q)}static ball(I){const g=A.rawshape_ball(I);return IA.__wrap(g)}static halfspace(I){a(I,QA);const g=A.rawshape_halfspace(I.ptr);return IA.__wrap(g)}static capsule(I,g){const C=A.rawshape_capsule(I,g);return IA.__wrap(C)}static cylinder(I,g){const C=A.rawshape_cylinder(I,g);return IA.__wrap(C)}static roundCylinder(I,g,C){const B=A.rawshape_roundCylinder(I,g,C);return IA.__wrap(B)}static cone(I,g){const C=A.rawshape_cone(I,g);return IA.__wrap(C)}static roundCone(I,g,C){const B=A.rawshape_roundCone(I,g,C);return IA.__wrap(B)}static polyline(I,g){const C=q(I,A.__wbindgen_malloc),B=F,Q=R(g,A.__wbindgen_malloc),E=F,i=A.rawshape_polyline(C,B,Q,E);return IA.__wrap(i)}static trimesh(I,g){const C=q(I,A.__wbindgen_malloc),B=F,Q=R(g,A.__wbindgen_malloc),E=F,i=A.rawshape_trimesh(C,B,Q,E);return IA.__wrap(i)}static heightfield(I,g,C,B){const Q=q(C,A.__wbindgen_malloc),E=F;a(B,QA);const i=A.rawshape_heightfield(I,g,Q,E,B.ptr);return IA.__wrap(i)}static segment(I,g){a(I,QA),a(g,QA);const C=A.rawshape_segment(I.ptr,g.ptr);return IA.__wrap(C)}static triangle(I,g,C){a(I,QA),a(g,QA),a(C,QA);const B=A.rawshape_triangle(I.ptr,g.ptr,C.ptr);return IA.__wrap(B)}static roundTriangle(I,g,C,B){a(I,QA),a(g,QA),a(C,QA);const Q=A.rawshape_roundTriangle(I.ptr,g.ptr,C.ptr,B);return IA.__wrap(Q)}static convexHull(I){const g=q(I,A.__wbindgen_malloc),C=F,B=A.rawshape_convexHull(g,C);return 0===B?void 0:IA.__wrap(B)}static roundConvexHull(I,g){const C=q(I,A.__wbindgen_malloc),B=F,Q=A.rawshape_roundConvexHull(C,B,g);return 0===Q?void 0:IA.__wrap(Q)}static convexMesh(I,g){const C=q(I,A.__wbindgen_malloc),B=F,Q=R(g,A.__wbindgen_malloc),E=F,i=A.rawshape_convexMesh(C,B,Q,E);return 0===i?void 0:IA.__wrap(i)}static roundConvexMesh(I,g,C){const B=q(I,A.__wbindgen_malloc),Q=F,E=R(g,A.__wbindgen_malloc),i=F,D=A.rawshape_roundConvexMesh(B,Q,E,i,C);return 0===D?void 0:IA.__wrap(D)}castShape(I,g,C,B,Q,E,i,D,o){a(I,QA),a(g,_),a(C,QA),a(B,IA),a(Q,QA),a(E,_),a(i,QA);const G=A.rawshape_castShape(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,E.ptr,i.ptr,D,o);return 0===G?void 0:BA.__wrap(G)}intersectsShape(I,g,C,B,Q){a(I,QA),a(g,_),a(C,IA),a(B,QA),a(Q,_);return 0!==A.rawshape_intersectsShape(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q.ptr)}contactShape(I,g,C,B,Q,E){a(I,QA),a(g,_),a(C,IA),a(B,QA),a(Q,_);const i=A.rawshape_contactShape(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q.ptr,E);return 0===i?void 0:CA.__wrap(i)}containsPoint(I,g,C){a(I,QA),a(g,_),a(C,QA);return 0!==A.rawshape_containsPoint(this.ptr,I.ptr,g.ptr,C.ptr)}projectPoint(I,g,C,B){a(I,QA),a(g,_),a(C,QA);const Q=A.rawshape_projectPoint(this.ptr,I.ptr,g.ptr,C.ptr,B);return X.__wrap(Q)}intersectsRay(I,g,C,B,Q){a(I,QA),a(g,_),a(C,QA),a(B,QA);return 0!==A.rawshape_intersectsRay(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q)}castRay(I,g,C,B,Q,E){a(I,QA),a(g,_),a(C,QA),a(B,QA);return A.rawshape_castRay(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q,E)}castRayAndGetNormal(I,g,C,B,Q,E){a(I,QA),a(g,_),a(C,QA),a(B,QA);const i=A.rawshape_castRayAndGetNormal(this.ptr,I.ptr,g.ptr,C.ptr,B.ptr,Q,E);return 0===i?void 0:u.__wrap(i)}}class gA{static __wrap(A){const I=Object.create(gA.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawshapecollidertoi_free(I)}colliderHandle(){return A.rawcharactercollision_handle(this.ptr)}toi(){return A.rawcharactercollision_toi(this.ptr)}witness1(){const I=A.rawcharactercollision_worldWitness1(this.ptr);return QA.__wrap(I)}witness2(){const I=A.rawshapecollidertoi_witness2(this.ptr);return QA.__wrap(I)}normal1(){const I=A.rawcharactercollision_worldNormal1(this.ptr);return QA.__wrap(I)}normal2(){const I=A.rawshapecollidertoi_normal2(this.ptr);return QA.__wrap(I)}}class CA{static __wrap(A){const I=Object.create(CA.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawshapecontact_free(I)}distance(){return A.rawshapecontact_distance(this.ptr)}point1(){const I=A.rawkinematiccharactercontroller_computedMovement(this.ptr);return QA.__wrap(I)}point2(){const I=A.rawcharactercollision_worldWitness1(this.ptr);return QA.__wrap(I)}normal1(){const I=A.rawshapecollidertoi_witness2(this.ptr);return QA.__wrap(I)}normal2(){const I=A.rawcharactercollision_worldNormal1(this.ptr);return QA.__wrap(I)}}class BA{static __wrap(A){const I=Object.create(BA.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawshapetoi_free(I)}toi(){return A.rawintegrationparameters_dt(this.ptr)}witness1(){const I=A.rawshapetoi_witness1(this.ptr);return QA.__wrap(I)}witness2(){const I=A.rawcontactforceevent_total_force(this.ptr);return QA.__wrap(I)}normal1(){const I=A.rawshapetoi_normal1(this.ptr);return QA.__wrap(I)}normal2(){const I=A.rawshapetoi_normal2(this.ptr);return QA.__wrap(I)}}class QA{static __wrap(A){const I=Object.create(QA.prototype);return I.ptr=A,I}__destroy_into_raw(){const A=this.ptr;return this.ptr=0,A}free(){const I=this.__destroy_into_raw();A.__wbg_rawvector_free(I)}static zero(){const I=A.rawvector_zero();return QA.__wrap(I)}constructor(I,g,C){const B=A.rawvector_new(I,g,C);return QA.__wrap(B)}get x(){return A.rawintegrationparameters_dt(this.ptr)}set x(I){A.rawintegrationparameters_set_dt(this.ptr,I)}get y(){return A.rawrotation_y(this.ptr)}set y(I){A.rawvector_set_y(this.ptr,I)}get z(){return A.rawcharactercollision_toi(this.ptr)}set z(I){A.rawintegrationparameters_set_erp(this.ptr,I)}xyz(){const I=A.rawvector_xyz(this.ptr);return QA.__wrap(I)}yxz(){const I=A.rawvector_yxz(this.ptr);return QA.__wrap(I)}zxy(){const I=A.rawvector_zxy(this.ptr);return QA.__wrap(I)}xzy(){const I=A.rawvector_xzy(this.ptr);return QA.__wrap(I)}yzx(){const I=A.rawvector_yzx(this.ptr);return QA.__wrap(I)}zyx(){const I=A.rawvector_zyx(this.ptr);return QA.__wrap(I)}}async function EA(I){void 0===I&&(I=new URL("rapier_wasm3d_bg.wasm","<deleted>"));const C=function(){const I={wbg:{}};return I.wbg.__wbindgen_object_drop_ref=function(A){B(A)},I.wbg.__wbindgen_number_new=function(A){return Q(A)},I.wbg.__wbindgen_number_get=function(A,I){const C=g(I),B="number"==typeof C?C:void 0;D()[A/8+1]=E(B)?0:B,G()[A/4+0]=!E(B)},I.wbg.__wbindgen_boolean_get=function(A){const I=g(A);return"boolean"==typeof I?I?1:0:2},I.wbg.__wbindgen_is_function=function(A){return"function"==typeof g(A)},I.wbg.__wbg_rawraycolliderintersection_new=function(A){return Q(P.__wrap(A))},I.wbg.__wbg_rawcontactforceevent_new=function(A){return Q(t.__wrap(A))},I.wbg.__wbg_call_168da88779e35f61=function(){return s((function(A,I,C){return Q(g(A).call(g(I),g(C)))}),arguments)},I.wbg.__wbg_call_3999bee59e9f7719=function(){return s((function(A,I,C,B){return Q(g(A).call(g(I),g(C),g(B)))}),arguments)},I.wbg.__wbg_call_e1f72c051cdab859=function(){return s((function(A,I,C,B,E){return Q(g(A).call(g(I),g(C),g(B),g(E)))}),arguments)},I.wbg.__wbg_bind_10dfe70e95d2a480=function(A,I,C,B){return Q(g(A).bind(g(I),g(C),g(B)))},I.wbg.__wbg_buffer_3f3d764d4747d564=function(A){return Q(g(A).buffer)},I.wbg.__wbg_newwithbyteoffsetandlength_d9aa266703cb98be=function(A,I,C){return Q(new Uint8Array(g(A),I>>>0,C>>>0))},I.wbg.__wbg_new_8c3f0052272a457a=function(A){return Q(new Uint8Array(g(A)))},I.wbg.__wbg_set_83db9690f9353e79=function(A,I,C){g(A).set(g(I),C>>>0)},I.wbg.__wbg_length_9e1ae1900cb0fbd5=function(A){return g(A).length},I.wbg.__wbg_newwithbyteoffsetandlength_be22e5fcf4f69ab4=function(A,I,C){return Q(new Float32Array(g(A),I>>>0,C>>>0))},I.wbg.__wbg_set_0e0314cf6675c1b9=function(A,I,C){g(A).set(g(I),C>>>0)},I.wbg.__wbg_length_9a2deed95d22668d=function(A){return g(A).length},I.wbg.__wbg_newwithlength_a7168e4a1e8f5e12=function(A){return Q(new Float32Array(A>>>0))},I.wbg.__wbindgen_throw=function(A,I){throw new Error(S(A,I))},I.wbg.__wbindgen_memory=function(){return Q(A.memory)},I}();("string"==typeof I||"function"==typeof Request&&I instanceof Request||"function"==typeof URL&&I instanceof URL)&&(I=fetch(I));const{instance:w,module:a}=await async function(A,I){if("function"==typeof Response&&A instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(A,I)}catch(I){if("application/wasm"==A.headers.get("Content-Type"))throw I;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",I)}const g=await A.arrayBuffer();return await WebAssembly.instantiate(g,I)}{const g=await WebAssembly.instantiate(A,I);return g instanceof WebAssembly.Instance?{instance:g,module:A}:g}}(await I,C);return function(I,g){return A=I.exports,EA.__wbindgen_wasm_module=g,M=new Float32Array,i=new Float64Array,o=new Int32Array,h=new Uint32Array,k=new Uint8Array,A}(w,a)}class iA{constructor(A,I,g){this.x=A,this.y=I,this.z=g}}class DA{static new(A,I,g){return new iA(A,I,g)}static intoRaw(A){return new QA(A.x,A.y,A.z)}static zeros(){return DA.new(0,0,0)}static fromRaw(A){if(!A)return null;let I=DA.new(A.x,A.y,A.z);return A.free(),I}static copy(A,I){A.x=I.x,A.y=I.y,A.z=I.z}}class oA{constructor(A,I,g,C){this.x=A,this.y=I,this.z=g,this.w=C}}class GA{static identity(){return new oA(0,0,0,1)}static fromRaw(A){if(!A)return null;let I=new oA(A.x,A.y,A.z,A.w);return A.free(),I}static intoRaw(A){return new _(A.x,A.y,A.z,A.w)}static copy(A,I){A.x=I.x,A.y=I.y,A.z=I.z,A.w=I.w}}class wA{constructor(A){this.elements=A}get m11(){return this.elements[0]}get m12(){return this.elements[1]}get m21(){return this.m12}get m13(){return this.elements[2]}get m31(){return this.m13}get m22(){return this.elements[3]}get m23(){return this.elements[4]}get m32(){return this.m23}get m33(){return this.elements[5]}}class kA{static fromRaw(A){const I=new wA(A.elements());return A.free(),I}}var SA,aA,MA,KA,yA,JA,UA,hA,NA,FA,qA,RA;!function(A){A[A.Dynamic=0]="Dynamic",A[A.Fixed=1]="Fixed",A[A.KinematicPositionBased=2]="KinematicPositionBased",A[A.KinematicVelocityBased=3]="KinematicVelocityBased"}(SA||(SA={}));class sA{constructor(A,I,g){this.rawSet=A,this.colliderSet=I,this.handle=g}finalizeDeserialization(A){this.colliderSet=A}isValid(){return this.rawSet.contains(this.handle)}lockTranslations(A,I){return this.rawSet.rbLockTranslations(this.handle,A,I)}lockRotations(A,I){return this.rawSet.rbLockRotations(this.handle,A,I)}setEnabledTranslations(A,I,g,C){return this.rawSet.rbSetEnabledTranslations(this.handle,A,I,g,C)}restrictTranslations(A,I,g,C){this.setEnabledTranslations(A,I,g,C)}setEnabledRotations(A,I,g,C){return this.rawSet.rbSetEnabledRotations(this.handle,A,I,g,C)}restrictRotations(A,I,g,C){this.setEnabledRotations(A,I,g,C)}dominanceGroup(){return this.rawSet.rbDominanceGroup(this.handle)}setDominanceGroup(A){this.rawSet.rbSetDominanceGroup(this.handle,A)}enableCcd(A){this.rawSet.rbEnableCcd(this.handle,A)}translation(){let A=this.rawSet.rbTranslation(this.handle);return DA.fromRaw(A)}rotation(){let A=this.rawSet.rbRotation(this.handle);return GA.fromRaw(A)}nextTranslation(){let A=this.rawSet.rbNextTranslation(this.handle);return DA.fromRaw(A)}nextRotation(){let A=this.rawSet.rbNextRotation(this.handle);return GA.fromRaw(A)}setTranslation(A,I){this.rawSet.rbSetTranslation(this.handle,A.x,A.y,A.z,I)}setLinvel(A,I){let g=DA.intoRaw(A);this.rawSet.rbSetLinvel(this.handle,g,I),g.free()}gravityScale(){return this.rawSet.rbGravityScale(this.handle)}setGravityScale(A,I){this.rawSet.rbSetGravityScale(this.handle,A,I)}setRotation(A,I){this.rawSet.rbSetRotation(this.handle,A.x,A.y,A.z,A.w,I)}setAngvel(A,I){let g=DA.intoRaw(A);this.rawSet.rbSetAngvel(this.handle,g,I),g.free()}setNextKinematicTranslation(A){this.rawSet.rbSetNextKinematicTranslation(this.handle,A.x,A.y,A.z)}setNextKinematicRotation(A){this.rawSet.rbSetNextKinematicRotation(this.handle,A.x,A.y,A.z,A.w)}linvel(){return DA.fromRaw(this.rawSet.rbLinvel(this.handle))}angvel(){return DA.fromRaw(this.rawSet.rbAngvel(this.handle))}mass(){return this.rawSet.rbMass(this.handle)}effectiveInvMass(){return DA.fromRaw(this.rawSet.rbEffectiveInvMass(this.handle))}invMass(){return this.rawSet.rbInvMass(this.handle)}localCom(){return DA.fromRaw(this.rawSet.rbLocalCom(this.handle))}worldCom(){return DA.fromRaw(this.rawSet.rbWorldCom(this.handle))}invPrincipalInertiaSqrt(){return DA.fromRaw(this.rawSet.rbInvPrincipalInertiaSqrt(this.handle))}principalInertia(){return DA.fromRaw(this.rawSet.rbPrincipalInertia(this.handle))}principalInertiaLocalFrame(){return GA.fromRaw(this.rawSet.rbPrincipalInertiaLocalFrame(this.handle))}effectiveWorldInvInertiaSqrt(){return kA.fromRaw(this.rawSet.rbEffectiveWorldInvInertiaSqrt(this.handle))}effectiveAngularInertia(){return kA.fromRaw(this.rawSet.rbEffectiveAngularInertia(this.handle))}sleep(){this.rawSet.rbSleep(this.handle)}wakeUp(){this.rawSet.rbWakeUp(this.handle)}isCcdEnabled(){return this.rawSet.rbIsCcdEnabled(this.handle)}numColliders(){return this.rawSet.rbNumColliders(this.handle)}collider(A){return this.colliderSet.get(this.rawSet.rbCollider(this.handle,A))}setEnabled(A){this.rawSet.rbSetEnabled(this.handle,A)}isEnabled(){return this.rawSet.rbIsEnabled(this.handle)}bodyType(){return this.rawSet.rbBodyType(this.handle)}setBodyType(A,I){return this.rawSet.rbSetBodyType(this.handle,A,I)}isSleeping(){return this.rawSet.rbIsSleeping(this.handle)}isMoving(){return this.rawSet.rbIsMoving(this.handle)}isFixed(){return this.rawSet.rbIsFixed(this.handle)}isKinematic(){return this.rawSet.rbIsKinematic(this.handle)}isDynamic(){return this.rawSet.rbIsDynamic(this.handle)}linearDamping(){return this.rawSet.rbLinearDamping(this.handle)}angularDamping(){return this.rawSet.rbAngularDamping(this.handle)}setLinearDamping(A){this.rawSet.rbSetLinearDamping(this.handle,A)}recomputeMassPropertiesFromColliders(){this.rawSet.rbRecomputeMassPropertiesFromColliders(this.handle,this.colliderSet.raw)}setAdditionalMass(A,I){this.rawSet.rbSetAdditionalMass(this.handle,A,I)}setAdditionalMassProperties(A,I,g,C,B){let Q=DA.intoRaw(I),E=DA.intoRaw(g),i=GA.intoRaw(C);this.rawSet.rbSetAdditionalMassProperties(this.handle,A,Q,E,i,B),Q.free(),E.free(),i.free()}setAngularDamping(A){this.rawSet.rbSetAngularDamping(this.handle,A)}resetForces(A){this.rawSet.rbResetForces(this.handle,A)}resetTorques(A){this.rawSet.rbResetTorques(this.handle,A)}addForce(A,I){const g=DA.intoRaw(A);this.rawSet.rbAddForce(this.handle,g,I),g.free()}applyImpulse(A,I){const g=DA.intoRaw(A);this.rawSet.rbApplyImpulse(this.handle,g,I),g.free()}addTorque(A,I){const g=DA.intoRaw(A);this.rawSet.rbAddTorque(this.handle,g,I),g.free()}applyTorqueImpulse(A,I){const g=DA.intoRaw(A);this.rawSet.rbApplyTorqueImpulse(this.handle,g,I),g.free()}addForceAtPoint(A,I,g){const C=DA.intoRaw(A),B=DA.intoRaw(I);this.rawSet.rbAddForceAtPoint(this.handle,C,B,g),C.free(),B.free()}applyImpulseAtPoint(A,I,g){const C=DA.intoRaw(A),B=DA.intoRaw(I);this.rawSet.rbApplyImpulseAtPoint(this.handle,C,B,g),C.free(),B.free()}}class cA{constructor(A){this.enabled=!0,this.status=A,this.translation=DA.zeros(),this.rotation=GA.identity(),this.gravityScale=1,this.linvel=DA.zeros(),this.mass=0,this.massOnly=!1,this.centerOfMass=DA.zeros(),this.translationsEnabledX=!0,this.translationsEnabledY=!0,this.angvel=DA.zeros(),this.principalAngularInertia=DA.zeros(),this.angularInertiaLocalFrame=GA.identity(),this.translationsEnabledZ=!0,this.rotationsEnabledX=!0,this.rotationsEnabledY=!0,this.rotationsEnabledZ=!0,this.linearDamping=0,this.angularDamping=0,this.canSleep=!0,this.sleeping=!1,this.ccdEnabled=!1,this.dominanceGroup=0}static dynamic(){return new cA(SA.Dynamic)}static kinematicPositionBased(){return new cA(SA.KinematicPositionBased)}static kinematicVelocityBased(){return new cA(SA.KinematicVelocityBased)}static fixed(){return new cA(SA.Fixed)}static newDynamic(){return new cA(SA.Dynamic)}static newKinematicPositionBased(){return new cA(SA.KinematicPositionBased)}static newKinematicVelocityBased(){return new cA(SA.KinematicVelocityBased)}static newStatic(){return new cA(SA.Fixed)}setDominanceGroup(A){return this.dominanceGroup=A,this}setEnabled(A){return this.enabled=A,this}setTranslation(A,I,g){if("number"!=typeof A||"number"!=typeof I||"number"!=typeof g)throw TypeError("The translation components must be numbers.");return this.translation={x:A,y:I,z:g},this}setRotation(A){return GA.copy(this.rotation,A),this}setGravityScale(A){return this.gravityScale=A,this}setAdditionalMass(A){return this.mass=A,this.massOnly=!0,this}setLinvel(A,I,g){if("number"!=typeof A||"number"!=typeof I||"number"!=typeof g)throw TypeError("The linvel components must be numbers.");return this.linvel={x:A,y:I,z:g},this}setAngvel(A){return DA.copy(this.angvel,A),this}setAdditionalMassProperties(A,I,g,C){return this.mass=A,DA.copy(this.centerOfMass,I),DA.copy(this.principalAngularInertia,g),GA.copy(this.angularInertiaLocalFrame,C),this.massOnly=!1,this}enabledTranslations(A,I,g){return this.translationsEnabledX=A,this.translationsEnabledY=I,this.translationsEnabledZ=g,this}restrictTranslations(A,I,g){return this.enabledTranslations(A,I,g)}lockTranslations(){return this.enabledTranslations(!1,!1,!1)}enabledRotations(A,I,g){return this.rotationsEnabledX=A,this.rotationsEnabledY=I,this.rotationsEnabledZ=g,this}restrictRotations(A,I,g){return this.enabledRotations(A,I,g)}lockRotations(){return this.restrictRotations(!1,!1,!1)}setLinearDamping(A){return this.linearDamping=A,this}setAngularDamping(A){return this.angularDamping=A,this}setCanSleep(A){return this.canSleep=A,this}setSleeping(A){return this.sleeping=A,this}setCcdEnabled(A){return this.ccdEnabled=A,this}setUserData(A){return this.userData=A,this}}class YA{constructor(){this.fconv=new Float64Array(1),this.uconv=new Uint32Array(this.fconv.buffer),this.data=new Array,this.size=0}set(A,I){let g=this.index(A);for(;this.data.length<=g;)this.data.push(null);null==this.data[g]&&(this.size+=1),this.data[g]=I}len(){return this.size}delete(A){let I=this.index(A);I<this.data.length&&(null!=this.data[I]&&(this.size-=1),this.data[I]=null)}clear(){this.data=new Array}get(A){let I=this.index(A);return I<this.data.length?this.data[I]:null}forEach(A){for(const I of this.data)null!=I&&A(I)}getAll(){return this.data.filter((A=>null!=A))}index(A){return this.fconv[0]=A,this.uconv[0]}}class LA{constructor(A){this.raw=A||new v,this.map=new YA,A&&A.forEachRigidBodyHandle((I=>{this.map.set(I,new sA(A,null,I))}))}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}finalizeDeserialization(A){this.map.forEach((I=>I.finalizeDeserialization(A)))}createRigidBody(A,I){let g=DA.intoRaw(I.translation),C=GA.intoRaw(I.rotation),B=DA.intoRaw(I.linvel),Q=DA.intoRaw(I.centerOfMass),E=DA.intoRaw(I.angvel),i=DA.intoRaw(I.principalAngularInertia),D=GA.intoRaw(I.angularInertiaLocalFrame),o=this.raw.createRigidBody(I.enabled,g,C,I.gravityScale,I.mass,I.massOnly,Q,B,E,i,D,I.translationsEnabledX,I.translationsEnabledY,I.translationsEnabledZ,I.rotationsEnabledX,I.rotationsEnabledY,I.rotationsEnabledZ,I.linearDamping,I.angularDamping,I.status,I.canSleep,I.sleeping,I.ccdEnabled,I.dominanceGroup);g.free(),C.free(),B.free(),Q.free(),E.free(),i.free(),D.free();const G=new sA(this.raw,A,o);return G.userData=I.userData,this.map.set(o,G),G}remove(A,I,g,C,B){for(let I=0;I<this.raw.rbNumColliders(A);I+=1)g.unmap(this.raw.rbCollider(A,I));C.forEachJointHandleAttachedToRigidBody(A,(A=>C.unmap(A))),B.forEachJointHandleAttachedToRigidBody(A,(A=>B.unmap(A))),this.raw.remove(A,I.raw,g.raw,C.raw,B.raw),this.map.delete(A)}len(){return this.map.len()}contains(A){return null!=this.get(A)}get(A){return this.map.get(A)}forEach(A){this.map.forEach(A)}forEachActiveRigidBody(A,I){A.forEachActiveRigidBodyHandle((A=>{I(this.get(A))}))}getAll(){return this.map.getAll()}}class HA{constructor(A){this.raw=A||new Z}free(){this.raw&&this.raw.free(),this.raw=void 0}get dt(){return this.raw.dt}get erp(){return this.raw.erp}get allowedLinearError(){return this.raw.allowedLinearError}get predictionDistance(){return this.raw.predictionDistance}get maxVelocityIterations(){return this.raw.maxVelocityIterations}get maxVelocityFrictionIterations(){return this.raw.maxVelocityFrictionIterations}get maxStabilizationIterations(){return this.raw.maxStabilizationIterations}get minIslandSize(){return this.raw.minIslandSize}get maxCcdSubsteps(){return this.raw.maxCcdSubsteps}set dt(A){this.raw.dt=A}set erp(A){this.raw.erp=A}set allowedLinearError(A){this.raw.allowedLinearError=A}set predictionDistance(A){this.raw.predictionDistance=A}set maxVelocityIterations(A){this.raw.maxVelocityIterations=A}set maxVelocityFrictionIterations(A){this.raw.maxVelocityFrictionIterations=A}set maxStabilizationIterations(A){this.raw.maxStabilizationIterations=A}set minIslandSize(A){this.raw.minIslandSize=A}set maxCcdSubsteps(A){this.raw.maxCcdSubsteps=A}}!function(A){A[A.Revolute=0]="Revolute",A[A.Fixed=1]="Fixed",A[A.Prismatic=2]="Prismatic",A[A.Spherical=3]="Spherical"}(aA||(aA={})),function(A){A[A.AccelerationBased=0]="AccelerationBased",A[A.ForceBased=1]="ForceBased"}(MA||(MA={}));class lA{constructor(A,I,g){this.rawSet=A,this.bodySet=I,this.handle=g}static newTyped(A,I,g){switch(A.jointType(g)){case aA.Revolute:return new rA(A,I,g);case aA.Prismatic:return new eA(A,I,g);case aA.Fixed:return new pA(A,I,g);case aA.Spherical:return new dA(A,I,g);default:return new lA(A,I,g)}}finalizeDeserialization(A){this.bodySet=A}isValid(){return this.rawSet.contains(this.handle)}body1(){return this.bodySet.get(this.rawSet.jointBodyHandle1(this.handle))}body2(){return this.bodySet.get(this.rawSet.jointBodyHandle2(this.handle))}type(){return this.rawSet.jointType(this.handle)}frameX1(){return GA.fromRaw(this.rawSet.jointFrameX1(this.handle))}frameX2(){return GA.fromRaw(this.rawSet.jointFrameX2(this.handle))}anchor1(){return DA.fromRaw(this.rawSet.jointAnchor1(this.handle))}anchor2(){return DA.fromRaw(this.rawSet.jointAnchor2(this.handle))}setAnchor1(A){const I=DA.intoRaw(A);this.rawSet.jointSetAnchor1(this.handle,I),I.free()}setAnchor2(A){const I=DA.intoRaw(A);this.rawSet.jointSetAnchor2(this.handle,I),I.free()}setContactsEnabled(A){this.rawSet.jointSetContactsEnabled(this.handle,A)}contactsEnabled(){return this.rawSet.jointContactsEnabled(this.handle)}}class tA extends lA{limitsEnabled(){return this.rawSet.jointLimitsEnabled(this.handle,this.rawAxis())}limitsMin(){return this.rawSet.jointLimitsMin(this.handle,this.rawAxis())}limitsMax(){return this.rawSet.jointLimitsMax(this.handle,this.rawAxis())}setLimits(A,I){this.rawSet.jointSetLimits(this.handle,this.rawAxis(),A,I)}configureMotorModel(A){this.rawSet.jointConfigureMotorModel(this.handle,this.rawAxis(),A)}configureMotorVelocity(A,I){this.rawSet.jointConfigureMotorVelocity(this.handle,this.rawAxis(),A,I)}configureMotorPosition(A,I,g){this.rawSet.jointConfigureMotorPosition(this.handle,this.rawAxis(),A,I,g)}configureMotor(A,I,g,C){this.rawSet.jointConfigureMotor(this.handle,this.rawAxis(),A,I,g,C)}}class pA extends lA{}class eA extends tA{rawAxis(){return c.X}}class rA extends tA{rawAxis(){return c.AngX}}class dA extends lA{}class TA{constructor(){}static fixed(A,I,g,C){let B=new TA;return B.anchor1=A,B.anchor2=g,B.frame1=I,B.frame2=C,B.jointType=aA.Fixed,B}static spherical(A,I){let g=new TA;return g.anchor1=A,g.anchor2=I,g.jointType=aA.Spherical,g}static prismatic(A,I,g){let C=new TA;return C.anchor1=A,C.anchor2=I,C.axis=g,C.jointType=aA.Prismatic,C}static revolute(A,I,g){let C=new TA;return C.anchor1=A,C.anchor2=I,C.axis=g,C.jointType=aA.Revolute,C}intoRaw(){let A,I,g=DA.intoRaw(this.anchor1),C=DA.intoRaw(this.anchor2),B=!1,Q=0,E=0;switch(this.jointType){case aA.Fixed:let i=GA.intoRaw(this.frame1),D=GA.intoRaw(this.frame2);I=O.fixed(g,i,C,D),i.free(),D.free();break;case aA.Prismatic:A=DA.intoRaw(this.axis),this.limitsEnabled&&(B=!0,Q=this.limits[0],E=this.limits[1]),I=O.prismatic(g,C,A,B,Q,E),A.free();break;case aA.Spherical:I=O.spherical(g,C);break;case aA.Revolute:A=DA.intoRaw(this.axis),I=O.revolute(g,C,A),A.free()}return g.free(),C.free(),I}}class OA{constructor(A){this.raw=A||new n,this.map=new YA,A&&A.forEachJointHandle((I=>{this.map.set(I,lA.newTyped(A,null,I))}))}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}finalizeDeserialization(A){this.map.forEach((I=>I.finalizeDeserialization(A)))}createJoint(A,I,g,C,B){const Q=I.intoRaw(),E=this.raw.createJoint(Q,g,C,B);Q.free();let i=lA.newTyped(this.raw,A,E);return this.map.set(E,i),i}remove(A,I){this.raw.remove(A,I),this.unmap(A)}forEachJointHandleAttachedToRigidBody(A,I){this.raw.forEachJointAttachedToRigidBody(A,I)}unmap(A){this.map.delete(A)}len(){return this.map.len()}contains(A){return null!=this.get(A)}get(A){return this.map.get(A)}forEach(A){this.map.forEach(A)}getAll(){return this.map.getAll()}}class nA{constructor(A,I){this.rawSet=A,this.handle=I}static newTyped(A,I){switch(A.jointType(I)){case aA.Revolute:return new jA(A,I);case aA.Prismatic:return new WA(A,I);case aA.Fixed:return new bA(A,I);case aA.Spherical:return new xA(A,I);default:return new nA(A,I)}}isValid(){return this.rawSet.contains(this.handle)}setContactsEnabled(A){this.rawSet.jointSetContactsEnabled(this.handle,A)}contactsEnabled(){return this.rawSet.jointContactsEnabled(this.handle)}}class ZA extends nA{}class bA extends nA{}class WA extends ZA{rawAxis(){return c.X}}class jA extends ZA{rawAxis(){return c.AngX}}class xA extends nA{}class fA{constructor(A){this.raw=A||new j,this.map=new YA,A&&A.forEachJointHandle((A=>{this.map.set(A,nA.newTyped(this.raw,A))}))}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}createJoint(A,I,g,C){const B=A.intoRaw(),Q=this.raw.createJoint(B,I,g,C);B.free();let E=nA.newTyped(this.raw,Q);return this.map.set(Q,E),E}remove(A,I){this.raw.remove(A,I),this.map.delete(A)}unmap(A){this.map.delete(A)}len(){return this.map.len()}contains(A){return null!=this.get(A)}get(A){return this.map.get(A)}forEach(A){this.map.forEach(A)}forEachJointHandleAttachedToRigidBody(A,I){this.raw.forEachJointAttachedToRigidBody(A,I)}getAll(){return this.map.getAll()}}!function(A){A[A.Average=0]="Average",A[A.Min=1]="Min",A[A.Multiply=2]="Multiply",A[A.Max=3]="Max"}(KA||(KA={}));class mA{constructor(A){this.raw=A||new L}free(){this.raw&&this.raw.free(),this.raw=void 0}}class XA{constructor(A){this.raw=A||new b}free(){this.raw&&this.raw.free(),this.raw=void 0}forEachActiveRigidBodyHandle(A){this.raw.forEachActiveRigidBodyHandle(A)}}class VA{constructor(A){this.raw=A||new Y}free(){this.raw&&this.raw.free(),this.raw=void 0}}class PA{constructor(A){this.raw=A||new x,this.tempManifold=new zA(null)}free(){this.raw&&this.raw.free(),this.raw=void 0}contactsWith(A,I){this.raw.contacts_with(A,I)}intersectionsWith(A,I){this.raw.intersections_with(A,I)}contactPair(A,I,g){const C=this.raw.contact_pair(A,I);if(C){const I=C.collider1()!=A;let B;for(B=0;B<C.numContactManifolds();++B)this.tempManifold.raw=C.contactManifold(B),this.tempManifold.raw&&g(this.tempManifold,I),this.tempManifold.free();C.free()}}intersectionPair(A,I){return this.raw.intersection_pair(A,I)}}class zA{constructor(A){this.raw=A}free(){this.raw&&this.raw.free(),this.raw=void 0}normal(){return DA.fromRaw(this.raw.normal())}localNormal1(){return DA.fromRaw(this.raw.local_n1())}localNormal2(){return DA.fromRaw(this.raw.local_n2())}subshape1(){return this.raw.subshape1()}subshape2(){return this.raw.subshape2()}numContacts(){return this.raw.num_contacts()}localContactPoint1(A){return DA.fromRaw(this.raw.contact_local_p1(A))}localContactPoint2(A){return DA.fromRaw(this.raw.contact_local_p2(A))}contactDist(A){return this.raw.contact_dist(A)}contactFid1(A){return this.raw.contact_fid1(A)}contactFid2(A){return this.raw.contact_fid2(A)}contactImpulse(A){return this.raw.contact_impulse(A)}contactTangentImpulseX(A){return this.raw.contact_tangent_impulse_x(A)}contactTangentImpulseY(A){return this.raw.contact_tangent_impulse_y(A)}numSolverContacts(){return this.raw.num_solver_contacts()}solverContactPoint(A){return DA.fromRaw(this.raw.solver_contact_point(A))}solverContactDist(A){return this.raw.solver_contact_dist(A)}solverContactFriction(A){return this.raw.solver_contact_friction(A)}solverContactRestitution(A){return this.raw.solver_contact_restitution(A)}solverContactTangentVelocity(A){return DA.fromRaw(this.raw.solver_contact_tangent_velocity(A))}}class uA{constructor(A,I,g,C,B){this.distance=A,this.point1=I,this.point2=g,this.normal1=C,this.normal2=B}static fromRaw(A){if(!A)return null;const I=new uA(A.distance(),DA.fromRaw(A.point1()),DA.fromRaw(A.point2()),DA.fromRaw(A.normal1()),DA.fromRaw(A.normal2()));return A.free(),I}}!function(A){A[A.Vertex=0]="Vertex",A[A.Edge=1]="Edge",A[A.Face=2]="Face",A[A.Unknown=3]="Unknown"}(yA||(yA={}));class vA{constructor(A,I){this.point=A,this.isInside=I}static fromRaw(A){if(!A)return null;const I=new vA(DA.fromRaw(A.point()),A.isInside());return A.free(),I}}class _A{constructor(A,I,g,C,B){this.featureType=yA.Unknown,this.featureId=void 0,this.collider=A,this.point=I,this.isInside=g,void 0!==B&&(this.featureId=B),void 0!==C&&(this.featureType=C)}static fromRaw(A,I){if(!I)return null;const g=new _A(A.get(I.colliderHandle()),DA.fromRaw(I.point()),I.isInside(),I.featureType(),I.featureId());return I.free(),g}}class $A{constructor(A,I){this.origin=A,this.dir=I}pointAt(A){return{x:this.origin.x+this.dir.x*A,y:this.origin.y+this.dir.y*A,z:this.origin.z+this.dir.z*A}}}class AI{constructor(A,I,g,C){this.featureType=yA.Unknown,this.featureId=void 0,this.toi=A,this.normal=I,void 0!==C&&(this.featureId=C),void 0!==g&&(this.featureType=g)}static fromRaw(A){if(!A)return null;const I=new AI(A.toi(),DA.fromRaw(A.normal()),A.featureType(),A.featureId());return A.free(),I}}class II{constructor(A,I,g,C,B){this.featureType=yA.Unknown,this.featureId=void 0,this.collider=A,this.toi=I,this.normal=g,void 0!==B&&(this.featureId=B),void 0!==C&&(this.featureType=C)}static fromRaw(A,I){if(!I)return null;const g=new II(A.get(I.colliderHandle()),I.toi(),DA.fromRaw(I.normal()),I.featureType(),I.featureId());return I.free(),g}}class gI{constructor(A,I){this.collider=A,this.toi=I}static fromRaw(A,I){if(!I)return null;const g=new gI(A.get(I.colliderHandle()),I.toi());return I.free(),g}}class CI{constructor(A,I,g,C,B){this.toi=A,this.witness1=I,this.witness2=g,this.normal1=C,this.normal2=B}static fromRaw(A,I){if(!I)return null;const g=new CI(I.toi(),DA.fromRaw(I.witness1()),DA.fromRaw(I.witness2()),DA.fromRaw(I.normal1()),DA.fromRaw(I.normal2()));return I.free(),g}}class BI extends CI{constructor(A,I,g,C,B,Q){super(I,g,C,B,Q),this.collider=A}static fromRaw(A,I){if(!I)return null;const g=new BI(A.get(I.colliderHandle()),I.toi(),DA.fromRaw(I.witness1()),DA.fromRaw(I.witness2()),DA.fromRaw(I.normal1()),DA.fromRaw(I.normal2()));return I.free(),g}}class QI{static fromRaw(A,I){const g=A.coShapeType(I);let C,B,Q,E,i,D,o;switch(g){case JA.Ball:return new EI(A.coRadius(I));case JA.Cuboid:return C=A.coHalfExtents(I),new DI(C.x,C.y,C.z);case JA.RoundCuboid:return C=A.coHalfExtents(I),B=A.coRoundRadius(I),new oI(C.x,C.y,C.z,B);case JA.Capsule:return i=A.coHalfHeight(I),D=A.coRadius(I),new GI(i,D);case JA.Segment:return Q=A.coVertices(I),new wI(DA.new(Q[0],Q[1],Q[2]),DA.new(Q[3],Q[4],Q[5]));case JA.Polyline:return Q=A.coVertices(I),E=A.coIndices(I),new aI(Q,E);case JA.Triangle:return Q=A.coVertices(I),new kI(DA.new(Q[0],Q[1],Q[2]),DA.new(Q[3],Q[4],Q[5]),DA.new(Q[6],Q[7],Q[8]));case JA.RoundTriangle:return Q=A.coVertices(I),B=A.coRoundRadius(I),new SI(DA.new(Q[0],Q[1],Q[2]),DA.new(Q[3],Q[4],Q[5]),DA.new(Q[6],Q[7],Q[8]),B);case JA.HalfSpace:return o=DA.fromRaw(A.coHalfspaceNormal(I)),new iI(o);case JA.TriMesh:return Q=A.coVertices(I),E=A.coIndices(I),new MI(Q,E);case JA.HeightField:const G=A.coHeightfieldScale(I),w=A.coHeightfieldHeights(I),k=A.coHeightfieldNRows(I),S=A.coHeightfieldNCols(I);return new JI(k,S,w,G);case JA.ConvexPolyhedron:return Q=A.coVertices(I),E=A.coIndices(I),new KI(Q,E);case JA.RoundConvexPolyhedron:return Q=A.coVertices(I),E=A.coIndices(I),B=A.coRoundRadius(I),new yI(Q,E,B);case JA.Cylinder:return i=A.coHalfHeight(I),D=A.coRadius(I),new UI(i,D);case JA.RoundCylinder:return i=A.coHalfHeight(I),D=A.coRadius(I),B=A.coRoundRadius(I),new hI(i,D,B);case JA.Cone:return i=A.coHalfHeight(I),D=A.coRadius(I),new NI(i,D);case JA.RoundCone:return i=A.coHalfHeight(I),D=A.coRadius(I),B=A.coRoundRadius(I),new FI(i,D,B);default:throw new Error("unknown shape type: "+g)}}castShape(A,I,g,C,B,Q,E,i,D){let o=DA.intoRaw(A),G=GA.intoRaw(I),w=DA.intoRaw(g),k=DA.intoRaw(B),S=GA.intoRaw(Q),a=DA.intoRaw(E),M=this.intoRaw(),K=C.intoRaw(),y=CI.fromRaw(null,M.castShape(o,G,w,K,k,S,a,i,D));return o.free(),G.free(),w.free(),k.free(),S.free(),a.free(),M.free(),K.free(),y}intersectsShape(A,I,g,C,B){let Q=DA.intoRaw(A),E=GA.intoRaw(I),i=DA.intoRaw(C),D=GA.intoRaw(B),o=this.intoRaw(),G=g.intoRaw(),w=o.intersectsShape(Q,E,G,i,D);return Q.free(),E.free(),i.free(),D.free(),o.free(),G.free(),w}contactShape(A,I,g,C,B,Q){let E=DA.intoRaw(A),i=GA.intoRaw(I),D=DA.intoRaw(C),o=GA.intoRaw(B),G=this.intoRaw(),w=g.intoRaw(),k=uA.fromRaw(G.contactShape(E,i,w,D,o,Q));return E.free(),i.free(),D.free(),o.free(),G.free(),w.free(),k}containsPoint(A,I,g){let C=DA.intoRaw(A),B=GA.intoRaw(I),Q=DA.intoRaw(g),E=this.intoRaw(),i=E.containsPoint(C,B,Q);return C.free(),B.free(),Q.free(),E.free(),i}projectPoint(A,I,g,C){let B=DA.intoRaw(A),Q=GA.intoRaw(I),E=DA.intoRaw(g),i=this.intoRaw(),D=vA.fromRaw(i.projectPoint(B,Q,E,C));return B.free(),Q.free(),E.free(),i.free(),D}intersectsRay(A,I,g,C){let B=DA.intoRaw(I),Q=GA.intoRaw(g),E=DA.intoRaw(A.origin),i=DA.intoRaw(A.dir),D=this.intoRaw(),o=D.intersectsRay(B,Q,E,i,C);return B.free(),Q.free(),E.free(),i.free(),D.free(),o}castRay(A,I,g,C,B){let Q=DA.intoRaw(I),E=GA.intoRaw(g),i=DA.intoRaw(A.origin),D=DA.intoRaw(A.dir),o=this.intoRaw(),G=o.castRay(Q,E,i,D,C,B);return Q.free(),E.free(),i.free(),D.free(),o.free(),G}castRayAndGetNormal(A,I,g,C,B){let Q=DA.intoRaw(I),E=GA.intoRaw(g),i=DA.intoRaw(A.origin),D=DA.intoRaw(A.dir),o=this.intoRaw(),G=AI.fromRaw(o.castRayAndGetNormal(Q,E,i,D,C,B));return Q.free(),E.free(),i.free(),D.free(),o.free(),G}}!function(A){A[A.Ball=0]="Ball",A[A.Cuboid=1]="Cuboid",A[A.Capsule=2]="Capsule",A[A.Segment=3]="Segment",A[A.Polyline=4]="Polyline",A[A.Triangle=5]="Triangle",A[A.TriMesh=6]="TriMesh",A[A.HeightField=7]="HeightField",A[A.ConvexPolyhedron=9]="ConvexPolyhedron",A[A.Cylinder=10]="Cylinder",A[A.Cone=11]="Cone",A[A.RoundCuboid=12]="RoundCuboid",A[A.RoundTriangle=13]="RoundTriangle",A[A.RoundCylinder=14]="RoundCylinder",A[A.RoundCone=15]="RoundCone",A[A.RoundConvexPolyhedron=16]="RoundConvexPolyhedron",A[A.HalfSpace=17]="HalfSpace"}(JA||(JA={}));class EI extends QI{constructor(A){super(),this.type=JA.Ball,this.radius=A}intoRaw(){return IA.ball(this.radius)}}class iI extends QI{constructor(A){super(),this.type=JA.HalfSpace,this.normal=A}intoRaw(){let A=DA.intoRaw(this.normal),I=IA.halfspace(A);return A.free(),I}}class DI extends QI{constructor(A,I,g){super(),this.type=JA.Cuboid,this.halfExtents=DA.new(A,I,g)}intoRaw(){return IA.cuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z)}}class oI extends QI{constructor(A,I,g,C){super(),this.type=JA.RoundCuboid,this.halfExtents=DA.new(A,I,g),this.borderRadius=C}intoRaw(){return IA.roundCuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z,this.borderRadius)}}class GI extends QI{constructor(A,I){super(),this.type=JA.Capsule,this.halfHeight=A,this.radius=I}intoRaw(){return IA.capsule(this.halfHeight,this.radius)}}class wI extends QI{constructor(A,I){super(),this.type=JA.Segment,this.a=A,this.b=I}intoRaw(){let A=DA.intoRaw(this.a),I=DA.intoRaw(this.b),g=IA.segment(A,I);return A.free(),I.free(),g}}class kI extends QI{constructor(A,I,g){super(),this.type=JA.Triangle,this.a=A,this.b=I,this.c=g}intoRaw(){let A=DA.intoRaw(this.a),I=DA.intoRaw(this.b),g=DA.intoRaw(this.c),C=IA.triangle(A,I,g);return A.free(),I.free(),g.free(),C}}class SI extends QI{constructor(A,I,g,C){super(),this.type=JA.RoundTriangle,this.a=A,this.b=I,this.c=g,this.borderRadius=C}intoRaw(){let A=DA.intoRaw(this.a),I=DA.intoRaw(this.b),g=DA.intoRaw(this.c),C=IA.roundTriangle(A,I,g,this.borderRadius);return A.free(),I.free(),g.free(),C}}class aI extends QI{constructor(A,I){super(),this.type=JA.Polyline,this.vertices=A,this.indices=null!=I?I:new Uint32Array(0)}intoRaw(){return IA.polyline(this.vertices,this.indices)}}class MI extends QI{constructor(A,I){super(),this.type=JA.TriMesh,this.vertices=A,this.indices=I}intoRaw(){return IA.trimesh(this.vertices,this.indices)}}class KI extends QI{constructor(A,I){super(),this.type=JA.ConvexPolyhedron,this.vertices=A,this.indices=I}intoRaw(){return this.indices?IA.convexMesh(this.vertices,this.indices):IA.convexHull(this.vertices)}}class yI extends QI{constructor(A,I,g){super(),this.type=JA.RoundConvexPolyhedron,this.vertices=A,this.indices=I,this.borderRadius=g}intoRaw(){return this.indices?IA.roundConvexMesh(this.vertices,this.indices,this.borderRadius):IA.roundConvexHull(this.vertices,this.borderRadius)}}class JI extends QI{constructor(A,I,g,C){super(),this.type=JA.HeightField,this.nrows=A,this.ncols=I,this.heights=g,this.scale=C}intoRaw(){let A=DA.intoRaw(this.scale),I=IA.heightfield(this.nrows,this.ncols,this.heights,A);return A.free(),I}}class UI extends QI{constructor(A,I){super(),this.type=JA.Cylinder,this.halfHeight=A,this.radius=I}intoRaw(){return IA.cylinder(this.halfHeight,this.radius)}}class hI extends QI{constructor(A,I,g){super(),this.type=JA.RoundCylinder,this.borderRadius=g,this.halfHeight=A,this.radius=I}intoRaw(){return IA.roundCylinder(this.halfHeight,this.radius,this.borderRadius)}}class NI extends QI{constructor(A,I){super(),this.type=JA.Cone,this.halfHeight=A,this.radius=I}intoRaw(){return IA.cone(this.halfHeight,this.radius)}}class FI extends QI{constructor(A,I,g){super(),this.type=JA.RoundCone,this.halfHeight=A,this.radius=I,this.borderRadius=g}intoRaw(){return IA.roundCone(this.halfHeight,this.radius,this.borderRadius)}}!function(A){A[A.DYNAMIC_DYNAMIC=1]="DYNAMIC_DYNAMIC",A[A.DYNAMIC_KINEMATIC=12]="DYNAMIC_KINEMATIC",A[A.DYNAMIC_FIXED=2]="DYNAMIC_FIXED",A[A.KINEMATIC_KINEMATIC=52224]="KINEMATIC_KINEMATIC",A[A.KINEMATIC_FIXED=8704]="KINEMATIC_FIXED",A[A.FIXED_FIXED=32]="FIXED_FIXED",A[A.DEFAULT=15]="DEFAULT",A[A.ALL=60943]="ALL"}(UA||(UA={}));class qI{constructor(A,I,g,C){this.colliderSet=A,this.handle=I,this._parent=g,this._shape=C}finalizeDeserialization(A){null!=this.handle&&(this._parent=A.get(this.colliderSet.raw.coParent(this.handle)))}ensureShapeIsCached(){this._shape||(this._shape=QI.fromRaw(this.colliderSet.raw,this.handle))}get shape(){return this.ensureShapeIsCached(),this._shape}isValid(){return this.colliderSet.raw.contains(this.handle)}translation(){return DA.fromRaw(this.colliderSet.raw.coTranslation(this.handle))}rotation(){return GA.fromRaw(this.colliderSet.raw.coRotation(this.handle))}isSensor(){return this.colliderSet.raw.coIsSensor(this.handle)}setSensor(A){this.colliderSet.raw.coSetSensor(this.handle,A)}setShape(A){let I=A.intoRaw();this.colliderSet.raw.coSetShape(this.handle,I),I.free(),this._shape=A}setEnabled(A){this.colliderSet.raw.coSetEnabled(this.handle,A)}isEnabled(){return this.colliderSet.raw.coIsEnabled(this.handle)}setRestitution(A){this.colliderSet.raw.coSetRestitution(this.handle,A)}setFriction(A){this.colliderSet.raw.coSetFriction(this.handle,A)}frictionCombineRule(){return this.colliderSet.raw.coFrictionCombineRule(this.handle)}setFrictionCombineRule(A){this.colliderSet.raw.coSetFrictionCombineRule(this.handle,A)}restitutionCombineRule(){return this.colliderSet.raw.coRestitutionCombineRule(this.handle)}setRestitutionCombineRule(A){this.colliderSet.raw.coSetRestitutionCombineRule(this.handle,A)}setCollisionGroups(A){this.colliderSet.raw.coSetCollisionGroups(this.handle,A)}setSolverGroups(A){this.colliderSet.raw.coSetSolverGroups(this.handle,A)}activeHooks(){return this.colliderSet.raw.coActiveHooks(this.handle)}setActiveHooks(A){this.colliderSet.raw.coSetActiveHooks(this.handle,A)}activeEvents(){return this.colliderSet.raw.coActiveEvents(this.handle)}setActiveEvents(A){this.colliderSet.raw.coSetActiveEvents(this.handle,A)}activeCollisionTypes(){return this.colliderSet.raw.coActiveCollisionTypes(this.handle)}setContactForceEventThreshold(A){return this.colliderSet.raw.coSetContactForceEventThreshold(this.handle,A)}contactForceEventThreshold(){return this.colliderSet.raw.coContactForceEventThreshold(this.handle)}setActiveCollisionTypes(A){this.colliderSet.raw.coSetActiveCollisionTypes(this.handle,A)}setDensity(A){this.colliderSet.raw.coSetDensity(this.handle,A)}setMass(A){this.colliderSet.raw.coSetMass(this.handle,A)}setMassProperties(A,I,g,C){let B=DA.intoRaw(I),Q=DA.intoRaw(g),E=GA.intoRaw(C);this.colliderSet.raw.coSetMassProperties(this.handle,A,B,Q,E),B.free(),Q.free(),E.free()}setTranslation(A){this.colliderSet.raw.coSetTranslation(this.handle,A.x,A.y,A.z)}setTranslationWrtParent(A){this.colliderSet.raw.coSetTranslationWrtParent(this.handle,A.x,A.y,A.z)}setRotation(A){this.colliderSet.raw.coSetRotation(this.handle,A.x,A.y,A.z,A.w)}setRotationWrtParent(A){this.colliderSet.raw.coSetRotationWrtParent(this.handle,A.x,A.y,A.z,A.w)}shapeType(){return this.colliderSet.raw.coShapeType(this.handle)}halfExtents(){return DA.fromRaw(this.colliderSet.raw.coHalfExtents(this.handle))}setHalfExtents(A){const I=DA.intoRaw(A);this.colliderSet.raw.coSetHalfExtents(this.handle,I)}radius(){return this.colliderSet.raw.coRadius(this.handle)}setRadius(A){this.colliderSet.raw.coSetRadius(this.handle,A)}roundRadius(){return this.colliderSet.raw.coRoundRadius(this.handle)}setRoundRadius(A){this.colliderSet.raw.coSetRoundRadius(this.handle,A)}halfHeight(){return this.colliderSet.raw.coHalfHeight(this.handle)}setHalfHeight(A){this.colliderSet.raw.coSetHalfHeight(this.handle,A)}vertices(){return this.colliderSet.raw.coVertices(this.handle)}indices(){return this.colliderSet.raw.coIndices(this.handle)}heightfieldHeights(){return this.colliderSet.raw.coHeightfieldHeights(this.handle)}heightfieldScale(){let A=this.colliderSet.raw.coHeightfieldScale(this.handle);return DA.fromRaw(A)}heightfieldNRows(){return this.colliderSet.raw.coHeightfieldNRows(this.handle)}heightfieldNCols(){return this.colliderSet.raw.coHeightfieldNCols(this.handle)}parent(){return this._parent}friction(){return this.colliderSet.raw.coFriction(this.handle)}restitution(){return this.colliderSet.raw.coRestitution(this.handle)}density(){return this.colliderSet.raw.coDensity(this.handle)}mass(){return this.colliderSet.raw.coMass(this.handle)}volume(){return this.colliderSet.raw.coVolume(this.handle)}collisionGroups(){return this.colliderSet.raw.coCollisionGroups(this.handle)}solverGroups(){return this.colliderSet.raw.coSolverGroups(this.handle)}containsPoint(A){let I=DA.intoRaw(A),g=this.colliderSet.raw.coContainsPoint(this.handle,I);return I.free(),g}projectPoint(A,I){let g=DA.intoRaw(A),C=vA.fromRaw(this.colliderSet.raw.coProjectPoint(this.handle,g,I));return g.free(),C}intersectsRay(A,I){let g=DA.intoRaw(A.origin),C=DA.intoRaw(A.dir),B=this.colliderSet.raw.coIntersectsRay(this.handle,g,C,I);return g.free(),C.free(),B}castShape(A,I,g,C,B,Q,E){let i=DA.intoRaw(A),D=DA.intoRaw(g),o=GA.intoRaw(C),G=DA.intoRaw(B),w=I.intoRaw(),k=CI.fromRaw(this.colliderSet,this.colliderSet.raw.coCastShape(this.handle,i,w,D,o,G,Q,E));return i.free(),D.free(),o.free(),G.free(),w.free(),k}castCollider(A,I,g,C,B){let Q=DA.intoRaw(A),E=DA.intoRaw(g),i=BI.fromRaw(this.colliderSet,this.colliderSet.raw.coCastCollider(this.handle,Q,I.handle,E,C,B));return Q.free(),E.free(),i}intersectsShape(A,I,g){let C=DA.intoRaw(I),B=GA.intoRaw(g),Q=A.intoRaw(),E=this.colliderSet.raw.coIntersectsShape(this.handle,Q,C,B);return C.free(),B.free(),Q.free(),E}contactShape(A,I,g,C){let B=DA.intoRaw(I),Q=GA.intoRaw(g),E=A.intoRaw(),i=uA.fromRaw(this.colliderSet.raw.coContactShape(this.handle,E,B,Q,C));return B.free(),Q.free(),E.free(),i}contactCollider(A,I){return uA.fromRaw(this.colliderSet.raw.coContactCollider(this.handle,A.handle,I))}castRay(A,I,g){let C=DA.intoRaw(A.origin),B=DA.intoRaw(A.dir),Q=this.colliderSet.raw.coCastRay(this.handle,C,B,I,g);return C.free(),B.free(),Q}castRayAndGetNormal(A,I,g){let C=DA.intoRaw(A.origin),B=DA.intoRaw(A.dir),Q=AI.fromRaw(this.colliderSet.raw.coCastRayAndGetNormal(this.handle,C,B,I,g));return C.free(),B.free(),Q}}!function(A){A[A.Density=0]="Density",A[A.Mass=1]="Mass",A[A.MassProps=2]="MassProps"}(hA||(hA={}));class RI{constructor(A){this.enabled=!0,this.shape=A,this.massPropsMode=hA.Density,this.density=1,this.friction=.5,this.restitution=0,this.rotation=GA.identity(),this.translation=DA.zeros(),this.isSensor=!1,this.collisionGroups=4294967295,this.solverGroups=4294967295,this.frictionCombineRule=KA.Average,this.restitutionCombineRule=KA.Average,this.activeCollisionTypes=UA.DEFAULT,this.activeEvents=0,this.activeHooks=0,this.mass=0,this.centerOfMass=DA.zeros(),this.contactForceEventThreshold=0,this.principalAngularInertia=DA.zeros(),this.angularInertiaLocalFrame=GA.identity()}static ball(A){const I=new EI(A);return new RI(I)}static capsule(A,I){const g=new GI(A,I);return new RI(g)}static segment(A,I){const g=new wI(A,I);return new RI(g)}static triangle(A,I,g){const C=new kI(A,I,g);return new RI(C)}static roundTriangle(A,I,g,C){const B=new SI(A,I,g,C);return new RI(B)}static polyline(A,I){const g=new aI(A,I);return new RI(g)}static trimesh(A,I){const g=new MI(A,I);return new RI(g)}static cuboid(A,I,g){const C=new DI(A,I,g);return new RI(C)}static roundCuboid(A,I,g,C){const B=new oI(A,I,g,C);return new RI(B)}static heightfield(A,I,g,C){const B=new JI(A,I,g,C);return new RI(B)}static cylinder(A,I){const g=new UI(A,I);return new RI(g)}static roundCylinder(A,I,g){const C=new hI(A,I,g);return new RI(C)}static cone(A,I){const g=new NI(A,I);return new RI(g)}static roundCone(A,I,g){const C=new FI(A,I,g);return new RI(C)}static convexHull(A){const I=new KI(A,null);return new RI(I)}static convexMesh(A,I){const g=new KI(A,I);return new RI(g)}static roundConvexHull(A,I){const g=new yI(A,null,I);return new RI(g)}static roundConvexMesh(A,I,g){const C=new yI(A,I,g);return new RI(C)}setTranslation(A,I,g){if("number"!=typeof A||"number"!=typeof I||"number"!=typeof g)throw TypeError("The translation components must be numbers.");return this.translation={x:A,y:I,z:g},this}setRotation(A){return GA.copy(this.rotation,A),this}setSensor(A){return this.isSensor=A,this}setEnabled(A){return this.enabled=A,this}setDensity(A){return this.massPropsMode=hA.Density,this.density=A,this}setMass(A){return this.massPropsMode=hA.Mass,this.mass=A,this}setMassProperties(A,I,g,C){return this.massPropsMode=hA.MassProps,this.mass=A,DA.copy(this.centerOfMass,I),DA.copy(this.principalAngularInertia,g),GA.copy(this.angularInertiaLocalFrame,C),this}setRestitution(A){return this.restitution=A,this}setFriction(A){return this.friction=A,this}setFrictionCombineRule(A){return this.frictionCombineRule=A,this}setRestitutionCombineRule(A){return this.restitutionCombineRule=A,this}setCollisionGroups(A){return this.collisionGroups=A,this}setSolverGroups(A){return this.solverGroups=A,this}setActiveHooks(A){return this.activeHooks=A,this}setActiveEvents(A){return this.activeEvents=A,this}setActiveCollisionTypes(A){return this.activeCollisionTypes=A,this}setContactForceEventThreshold(A){return this.contactForceEventThreshold=A,this}}class sI{constructor(A){this.raw=A||new l,this.map=new YA,A&&A.forEachColliderHandle((A=>{this.map.set(A,new qI(this,A,null))}))}free(){this.raw&&this.raw.free(),this.raw=void 0,this.map&&this.map.clear(),this.map=void 0}castClosure(A){return I=>A?A(this.get(I)):void 0}finalizeDeserialization(A){this.map.forEach((I=>I.finalizeDeserialization(A)))}createCollider(A,I,g){let C=null!=g&&null!=g;if(C&&isNaN(g))throw Error("Cannot create a collider with a parent rigid-body handle that is not a number.");let B=I.shape.intoRaw(),Q=DA.intoRaw(I.translation),E=GA.intoRaw(I.rotation),i=DA.intoRaw(I.centerOfMass),D=DA.intoRaw(I.principalAngularInertia),o=GA.intoRaw(I.angularInertiaLocalFrame),G=this.raw.createCollider(I.enabled,B,Q,E,I.massPropsMode,I.mass,i,D,o,I.density,I.friction,I.restitution,I.frictionCombineRule,I.restitutionCombineRule,I.isSensor,I.collisionGroups,I.solverGroups,I.activeCollisionTypes,I.activeHooks,I.activeEvents,I.contactForceEventThreshold,C,C?g:0,A.raw);B.free(),Q.free(),E.free(),i.free(),D.free(),o.free();let w=C?A.get(g):null,k=new qI(this,G,w,I.shape);return this.map.set(G,k),k}remove(A,I,g,C){this.raw.remove(A,I.raw,g.raw,C),this.unmap(A)}unmap(A){this.map.delete(A)}get(A){return this.map.get(A)}len(){return this.map.len()}contains(A){return null!=this.get(A)}forEach(A){this.map.forEach(A)}getAll(){return this.map.getAll()}}class cI{constructor(A){this.raw=A||new f}free(){this.raw&&this.raw.free(),this.raw=void 0}step(A,I,g,C,B,Q,E,i,D,o,G,w){let k=DA.intoRaw(A);G?this.raw.stepWithEvents(k,I.raw,g.raw,C.raw,B.raw,Q.raw,E.raw,i.raw,D.raw,o.raw,G.raw,w,w?w.filterContactPair:null,w?w.filterIntersectionPair:null):this.raw.step(k,I.raw,g.raw,C.raw,B.raw,Q.raw,E.raw,i.raw,D.raw,o.raw),k.free()}}!function(A){A[A.EXCLUDE_FIXED=1]="EXCLUDE_FIXED",A[A.EXCLUDE_KINEMATIC=2]="EXCLUDE_KINEMATIC",A[A.EXCLUDE_DYNAMIC=4]="EXCLUDE_DYNAMIC",A[A.EXCLUDE_SENSORS=8]="EXCLUDE_SENSORS",A[A.EXCLUDE_SOLIDS=16]="EXCLUDE_SOLIDS",A[A.ONLY_DYNAMIC=3]="ONLY_DYNAMIC",A[A.ONLY_KINEMATIC=5]="ONLY_KINEMATIC",A[A.ONLY_FIXED=6]="ONLY_FIXED"}(NA||(NA={}));class YI{constructor(A){this.raw=A||new V}free(){this.raw&&this.raw.free(),this.raw=void 0}update(A,I){this.raw.update(A.raw,I.raw)}castRay(A,I,g,C,B,Q,E,i,D,o){let G=DA.intoRaw(g.origin),w=DA.intoRaw(g.dir),k=gI.fromRaw(I,this.raw.castRay(A.raw,I.raw,G,w,C,B,Q,E,i,D,o));return G.free(),w.free(),k}castRayAndGetNormal(A,I,g,C,B,Q,E,i,D,o){let G=DA.intoRaw(g.origin),w=DA.intoRaw(g.dir),k=II.fromRaw(I,this.raw.castRayAndGetNormal(A.raw,I.raw,G,w,C,B,Q,E,i,D,o));return G.free(),w.free(),k}intersectionsWithRay(A,I,g,C,B,Q,E,i,D,o,G){let w=DA.intoRaw(g.origin),k=DA.intoRaw(g.dir);this.raw.intersectionsWithRay(A.raw,I.raw,w,k,C,B,(A=>Q(II.fromRaw(I,A))),E,i,D,o,G),w.free(),k.free()}intersectionWithShape(A,I,g,C,B,Q,E,i,D,o){let G=DA.intoRaw(g),w=GA.intoRaw(C),k=B.intoRaw(),S=this.raw.intersectionWithShape(A.raw,I.raw,G,w,k,Q,E,i,D,o);return G.free(),w.free(),k.free(),S}projectPoint(A,I,g,C,B,Q,E,i,D){let o=DA.intoRaw(g),G=_A.fromRaw(I,this.raw.projectPoint(A.raw,I.raw,o,C,B,Q,E,i,D));return o.free(),G}projectPointAndGetFeature(A,I,g,C,B,Q,E,i){let D=DA.intoRaw(g),o=_A.fromRaw(I,this.raw.projectPointAndGetFeature(A.raw,I.raw,D,C,B,Q,E,i));return D.free(),o}intersectionsWithPoint(A,I,g,C,B,Q,E,i,D){let o=DA.intoRaw(g);this.raw.intersectionsWithPoint(A.raw,I.raw,o,C,B,Q,E,i,D),o.free()}castShape(A,I,g,C,B,Q,E,i,D,o,G,w,k){let S=DA.intoRaw(g),a=GA.intoRaw(C),M=DA.intoRaw(B),K=Q.intoRaw(),y=BI.fromRaw(I,this.raw.castShape(A.raw,I.raw,S,a,M,K,E,i,D,o,G,w,k));return S.free(),a.free(),M.free(),K.free(),y}intersectionsWithShape(A,I,g,C,B,Q,E,i,D,o,G){let w=DA.intoRaw(g),k=GA.intoRaw(C),S=B.intoRaw();this.raw.intersectionsWithShape(A.raw,I.raw,w,k,S,Q,E,i,D,o,G),w.free(),k.free(),S.free()}collidersWithAabbIntersectingAabb(A,I,g){let C=DA.intoRaw(A),B=DA.intoRaw(I);this.raw.collidersWithAabbIntersectingAabb(C,B,g),C.free(),B.free()}}class LI{constructor(A){this.raw=A||new AA}free(){this.raw&&this.raw.free(),this.raw=void 0}serializeAll(A,I,g,C,B,Q,E,i,D){let o=DA.intoRaw(A);const G=this.raw.serializeAll(o,I.raw,g.raw,C.raw,B.raw,Q.raw,E.raw,i.raw,D.raw);return o.free(),G}deserializeAll(A){return eI.fromRaw(this.raw.deserializeAll(A))}}class HI{constructor(A,I){this.vertices=A,this.colors=I}}class lI{constructor(A){this.raw=A||new r}free(){this.raw&&this.raw.free(),this.raw=void 0,this.vertices=void 0,this.colors=void 0}render(A,I,g,C,B){this.raw.render(A.raw,I.raw,g.raw,C.raw,B.raw),this.vertices=this.raw.vertices(),this.colors=this.raw.colors()}}class tI{}class pI{constructor(A,I,g,C,B){this.params=I,this.bodies=g,this.colliders=C,this.queries=B,this.raw=new W(A),this.rawCharacterCollision=new H,this._applyImpulsesToDynamicBodies=!1,this._characterMass=null}free(){this.raw&&(this.raw.free(),this.rawCharacterCollision.free()),this.raw=void 0,this.rawCharacterCollision=void 0}up(){return this.raw.up()}setUp(A){let I=DA.intoRaw(A);return this.raw.setUp(I)}applyImpulsesToDynamicBodies(){return this._applyImpulsesToDynamicBodies}setApplyImpulsesToDynamicBodies(A){this._applyImpulsesToDynamicBodies=A}characterMass(){return this._characterMass}setCharacterMass(A){this._characterMass=A}offset(){return this.raw.offset()}setOffset(A){this.raw.setOffset(A)}slideEnabled(){return this.raw.slideEnabled()}setSlideEnabled(A){this.raw.setSlideEnabled(A)}autostepMaxHeight(){return this.raw.autostepMaxHeight()}autostepMinWidth(){return this.raw.autostepMinWidth()}autostepIncludesDynamicBodies(){return this.raw.autostepIncludesDynamicBodies()}autostepEnabled(){return this.raw.autostepEnabled()}enableAutostep(A,I,g){this.raw.enableAutostep(A,I,g)}disableAutostep(){return this.raw.disableAutostep()}maxSlopeClimbAngle(){return this.raw.maxSlopeClimbAngle()}setMaxSlopeClimbAngle(A){this.raw.setMaxSlopeClimbAngle(A)}minSlopeSlideAngle(){return this.raw.minSlopeSlideAngle()}setMinSlopeSlideAngle(A){this.raw.setMinSlopeSlideAngle(A)}snapToGroundDistance(){return this.raw.snapToGroundDistance()}enableSnapToGround(A){this.raw.enableSnapToGround(A)}disableSnapToGround(){this.raw.disableSnapToGround()}snapToGroundEnabled(){return this.raw.snapToGroundEnabled()}computeColliderMovement(A,I,g,C,B){let Q=DA.intoRaw(I);this.raw.computeColliderMovement(this.params.dt,this.bodies.raw,this.colliders.raw,this.queries.raw,A.handle,Q,this._applyImpulsesToDynamicBodies,this._characterMass,g,C,this.colliders.castClosure(B)),Q.free()}computedMovement(){return DA.fromRaw(this.raw.computedMovement())}computedGrounded(){return this.raw.computedGrounded()}numComputedCollisions(){return this.raw.numComputedCollisions()}computedCollision(A,I){if(this.raw.computedCollision(A,this.rawCharacterCollision)){let A=this.rawCharacterCollision;return(I=null!=I?I:new tI).translationApplied=DA.fromRaw(A.translationApplied()),I.translationRemaining=DA.fromRaw(A.translationRemaining()),I.toi=A.toi(),I.witness1=DA.fromRaw(A.worldWitness1()),I.witness2=DA.fromRaw(A.worldWitness2()),I.normal1=DA.fromRaw(A.worldNormal1()),I.normal2=DA.fromRaw(A.worldNormal2()),I.collider=this.colliders.get(A.handle()),I}return null}}class eI{constructor(A,I,g,C,B,Q,E,i,D,o,G,w,k,S){this.gravity=A,this.integrationParameters=new HA(I),this.islands=new XA(g),this.broadPhase=new VA(C),this.narrowPhase=new PA(B),this.bodies=new LA(Q),this.colliders=new sI(E),this.impulseJoints=new OA(i),this.multibodyJoints=new fA(D),this.ccdSolver=new mA(o),this.queryPipeline=new YI(G),this.physicsPipeline=new cI(w),this.serializationPipeline=new LI(k),this.debugRenderPipeline=new lI(S),this.characterControllers=new Set,this.impulseJoints.finalizeDeserialization(this.bodies),this.bodies.finalizeDeserialization(this.colliders),this.colliders.finalizeDeserialization(this.bodies)}free(){this.integrationParameters.free(),this.islands.free(),this.broadPhase.free(),this.narrowPhase.free(),this.bodies.free(),this.colliders.free(),this.impulseJoints.free(),this.multibodyJoints.free(),this.ccdSolver.free(),this.queryPipeline.free(),this.physicsPipeline.free(),this.serializationPipeline.free(),this.debugRenderPipeline.free(),this.characterControllers.forEach((A=>A.free())),this.integrationParameters=void 0,this.islands=void 0,this.broadPhase=void 0,this.narrowPhase=void 0,this.bodies=void 0,this.colliders=void 0,this.ccdSolver=void 0,this.impulseJoints=void 0,this.multibodyJoints=void 0,this.queryPipeline=void 0,this.physicsPipeline=void 0,this.serializationPipeline=void 0,this.debugRenderPipeline=void 0,this.characterControllers=void 0}static fromRaw(A){return A?new eI(DA.fromRaw(A.takeGravity()),A.takeIntegrationParameters(),A.takeIslandManager(),A.takeBroadPhase(),A.takeNarrowPhase(),A.takeBodies(),A.takeColliders(),A.takeImpulseJoints(),A.takeMultibodyJoints()):null}takeSnapshot(){return this.serializationPipeline.serializeAll(this.gravity,this.integrationParameters,this.islands,this.broadPhase,this.narrowPhase,this.bodies,this.colliders,this.impulseJoints,this.multibodyJoints)}static restoreSnapshot(A){return(new LI).deserializeAll(A)}debugRender(){return this.debugRenderPipeline.render(this.bodies,this.colliders,this.impulseJoints,this.multibodyJoints,this.narrowPhase),new HI(this.debugRenderPipeline.vertices,this.debugRenderPipeline.colors)}step(A,I){this.physicsPipeline.step(this.gravity,this.integrationParameters,this.islands,this.broadPhase,this.narrowPhase,this.bodies,this.colliders,this.impulseJoints,this.multibodyJoints,this.ccdSolver,A,I),this.queryPipeline.update(this.bodies,this.colliders)}propagateModifiedBodyPositionsToColliders(){this.bodies.raw.propagateModifiedBodyPositionsToColliders(this.colliders.raw)}updateSceneQueries(){this.propagateModifiedBodyPositionsToColliders(),this.queryPipeline.update(this.bodies,this.colliders)}get timestep(){return this.integrationParameters.dt}set timestep(A){this.integrationParameters.dt=A}get maxVelocityIterations(){return this.integrationParameters.maxVelocityIterations}set maxVelocityIterations(A){this.integrationParameters.maxVelocityIterations=A}get maxVelocityFrictionIterations(){return this.integrationParameters.maxVelocityFrictionIterations}set maxVelocityFrictionIterations(A){this.integrationParameters.maxVelocityFrictionIterations=A}get maxStabilizationIterations(){return this.integrationParameters.maxStabilizationIterations}set maxStabilizationIterations(A){this.integrationParameters.maxStabilizationIterations=A}createRigidBody(A){return this.bodies.createRigidBody(this.colliders,A)}createCharacterController(A){let I=new pI(A,this.integrationParameters,this.bodies,this.colliders,this.queryPipeline);return this.characterControllers.add(I),I}removeCharacterController(A){this.characterControllers.delete(A),A.free()}createCollider(A,I){let g=I?I.handle:void 0;return this.colliders.createCollider(this.bodies,A,g)}createImpulseJoint(A,I,g,C){return this.impulseJoints.createJoint(this.bodies,A,I.handle,g.handle,C)}createMultibodyJoint(A,I,g,C){return this.multibodyJoints.createJoint(A,I.handle,g.handle,C)}getRigidBody(A){return this.bodies.get(A)}getCollider(A){return this.colliders.get(A)}getImpulseJoint(A){return this.impulseJoints.get(A)}getMultibodyJoint(A){return this.multibodyJoints.get(A)}removeRigidBody(A){this.bodies&&this.bodies.remove(A.handle,this.islands,this.colliders,this.impulseJoints,this.multibodyJoints)}removeCollider(A,I){this.colliders&&this.colliders.remove(A.handle,this.islands,this.bodies,I)}removeImpulseJoint(A,I){this.impulseJoints&&this.impulseJoints.remove(A.handle,I)}removeMultibodyJoint(A,I){this.impulseJoints&&this.multibodyJoints.remove(A.handle,I)}forEachCollider(A){this.colliders.forEach(A)}forEachRigidBody(A){this.bodies.forEach(A)}forEachActiveRigidBody(A){this.bodies.forEachActiveRigidBody(this.islands,A)}castRay(A,I,g,C,B,Q,E,i){return this.queryPipeline.castRay(this.bodies,this.colliders,A,I,g,C,B,Q?Q.handle:null,E?E.handle:null,this.colliders.castClosure(i))}castRayAndGetNormal(A,I,g,C,B,Q,E,i){return this.queryPipeline.castRayAndGetNormal(this.bodies,this.colliders,A,I,g,C,B,Q?Q.handle:null,E?E.handle:null,this.colliders.castClosure(i))}intersectionsWithRay(A,I,g,C,B,Q,E,i,D){this.queryPipeline.intersectionsWithRay(this.bodies,this.colliders,A,I,g,C,B,Q,E?E.handle:null,i?i.handle:null,this.colliders.castClosure(D))}intersectionWithShape(A,I,g,C,B,Q,E,i){let D=this.queryPipeline.intersectionWithShape(this.bodies,this.colliders,A,I,g,C,B,Q?Q.handle:null,E?E.handle:null,this.colliders.castClosure(i));return null!=D?this.colliders.get(D):null}projectPoint(A,I,g,C,B,Q,E){return this.queryPipeline.projectPoint(this.bodies,this.colliders,A,I,g,C,B?B.handle:null,Q?Q.handle:null,this.colliders.castClosure(E))}projectPointAndGetFeature(A,I,g,C,B,Q){return this.queryPipeline.projectPointAndGetFeature(this.bodies,this.colliders,A,I,g,C?C.handle:null,B?B.handle:null,this.colliders.castClosure(Q))}intersectionsWithPoint(A,I,g,C,B,Q,E){this.queryPipeline.intersectionsWithPoint(this.bodies,this.colliders,A,this.colliders.castClosure(I),g,C,B?B.handle:null,Q?Q.handle:null,this.colliders.castClosure(E))}castShape(A,I,g,C,B,Q,E,i,D,o,G){return this.queryPipeline.castShape(this.bodies,this.colliders,A,I,g,C,B,Q,E,i,D?D.handle:null,o?o.handle:null,this.colliders.castClosure(G))}intersectionsWithShape(A,I,g,C,B,Q,E,i,D){this.queryPipeline.intersectionsWithShape(this.bodies,this.colliders,A,I,g,this.colliders.castClosure(C),B,Q,E?E.handle:null,i?i.handle:null,this.colliders.castClosure(D))}collidersWithAabbIntersectingAabb(A,I,g){this.queryPipeline.collidersWithAabbIntersectingAabb(A,I,this.colliders.castClosure(g))}contactsWith(A,I){this.narrowPhase.contactsWith(A.handle,this.colliders.castClosure(I))}intersectionsWith(A,I){this.narrowPhase.intersectionsWith(A.handle,this.colliders.castClosure(I))}contactPair(A,I,g){this.narrowPhase.contactPair(A.handle,I.handle,g)}intersectionPair(A,I){return this.narrowPhase.intersectionPair(A.handle,I.handle)}}!function(A){A[A.COLLISION_EVENTS=1]="COLLISION_EVENTS",A[A.CONTACT_FORCE_EVENTS=2]="CONTACT_FORCE_EVENTS"}(FA||(FA={}));class rI{free(){this.raw&&this.raw.free(),this.raw=void 0}collider1(){return this.raw.collider1()}collider2(){return this.raw.collider2()}totalForce(){return DA.fromRaw(this.raw.total_force())}totalForceMagnitude(){return this.raw.total_force_magnitude()}maxForceDirection(){return DA.fromRaw(this.raw.max_force_direction())}maxForceMagnitude(){return this.raw.max_force_magnitude()}}class dI{constructor(A,I){this.raw=I||new T(A)}free(){this.raw&&this.raw.free(),this.raw=void 0}drainCollisionEvents(A){this.raw.drainCollisionEvents(A)}drainContactForceEvents(A){let I=new rI;this.raw.drainContactForceEvents((g=>{I.raw=g,A(I),I.free()}))}clear(){this.raw.clear()}}function TI(A,I,g,C){return new(g||(g=Promise))((function(B,Q){function E(A){try{D(C.next(A))}catch(A){Q(A)}}function i(A){try{D(C.throw(A))}catch(A){Q(A)}}function D(A){var I;A.done?B(A.value):(I=A.value,I instanceof g?I:new g((function(A){A(I)}))).then(E,i)}D((C=C.apply(A,I||[])).next())}))}!function(A){A[A.FILTER_CONTACT_PAIRS=1]="FILTER_CONTACT_PAIRS",A[A.FILTER_INTERSECTION_PAIRS=2]="FILTER_INTERSECTION_PAIRS"}(qA||(qA={})),function(A){A[A.EMPTY=0]="EMPTY",A[A.COMPUTE_IMPULSE=1]="COMPUTE_IMPULSE"}(RA||(RA={}));for(var OI={byteLength:function(A){var I=fI(A),g=I[0],C=I[1];return 3*(g+C)/4-C},toByteArray:function(A){var I,g,C=fI(A),B=C[0],Q=C[1],E=new bI(function(A,I,g){return 3*(I+g)/4-g}(0,B,Q)),i=0,D=Q>0?B-4:B;for(g=0;g<D;g+=4)I=ZI[A.charCodeAt(g)]<<18|ZI[A.charCodeAt(g+1)]<<12|ZI[A.charCodeAt(g+2)]<<6|ZI[A.charCodeAt(g+3)],E[i++]=I>>16&255,E[i++]=I>>8&255,E[i++]=255&I;2===Q&&(I=ZI[A.charCodeAt(g)]<<2|ZI[A.charCodeAt(g+1)]>>4,E[i++]=255&I);1===Q&&(I=ZI[A.charCodeAt(g)]<<10|ZI[A.charCodeAt(g+1)]<<4|ZI[A.charCodeAt(g+2)]>>2,E[i++]=I>>8&255,E[i++]=255&I);return E},fromByteArray:function(A){for(var I,g=A.length,C=g%3,B=[],Q=16383,E=0,i=g-C;E<i;E+=Q)B.push(mI(A,E,E+Q>i?i:E+Q));1===C?(I=A[g-1],B.push(nI[I>>2]+nI[I<<4&63]+"==")):2===C&&(I=(A[g-2]<<8)+A[g-1],B.push(nI[I>>10]+nI[I>>4&63]+nI[I<<2&63]+"="));return B.join("")}},nI=[],ZI=[],bI="undefined"!=typeof Uint8Array?Uint8Array:Array,WI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",jI=0,xI=WI.length;jI<xI;++jI)nI[jI]=WI[jI],ZI[WI.charCodeAt(jI)]=jI;function fI(A){var I=A.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var g=A.indexOf("=");return-1===g&&(g=I),[g,g===I?0:4-g%4]}function mI(A,I,g){for(var C,B,Q=[],E=I;E<g;E+=3)C=(A[E]<<16&16711680)+(A[E+1]<<8&65280)+(255&A[E+2]),Q.push(nI[(B=C)>>18&63]+nI[B>>12&63]+nI[B>>6&63]+nI[63&B]);return Q.join("")}function XI(){return TI(this,void 0,void 0,(function*(){yield EA(OI.toByteArray("[encoded data, 1878948 characters]").buffer)}))}function VI(){return function(){try{const C=A.__wbindgen_add_to_stack_pointer(-16);A.version(C);var I=G()[C/4+0],g=G()[C/4+1];return S(I,g)}finally{A.__wbindgen_add_to_stack_pointer(16),A.__wbindgen_free(I,g)}}()}ZI["-".charCodeAt(0)]=62,ZI["_".charCodeAt(0)]=63;var PI=Object.freeze({__proto__:null,version:VI,Vector3:iA,VectorOps:DA,Quaternion:oA,RotationOps:GA,SdpMatrix3:wA,SdpMatrix3Ops:kA,get RigidBodyType(){return SA},RigidBody:sA,RigidBodyDesc:cA,RigidBodySet:LA,IntegrationParameters:HA,get JointType(){return aA},get MotorModel(){return MA},ImpulseJoint:lA,UnitImpulseJoint:tA,FixedImpulseJoint:pA,PrismaticImpulseJoint:eA,RevoluteImpulseJoint:rA,SphericalImpulseJoint:dA,JointData:TA,ImpulseJointSet:OA,MultibodyJoint:nA,UnitMultibodyJoint:ZA,FixedMultibodyJoint:bA,PrismaticMultibodyJoint:WA,RevoluteMultibodyJoint:jA,SphericalMultibodyJoint:xA,MultibodyJointSet:fA,get CoefficientCombineRule(){return KA},CCDSolver:mA,IslandManager:XA,BroadPhase:VA,NarrowPhase:PA,TempContactManifold:zA,Shape:QI,get ShapeType(){return JA},Ball:EI,HalfSpace:iI,Cuboid:DI,RoundCuboid:oI,Capsule:GI,Segment:wI,Triangle:kI,RoundTriangle:SI,Polyline:aI,TriMesh:MI,ConvexPolyhedron:KI,RoundConvexPolyhedron:yI,Heightfield:JI,Cylinder:UI,RoundCylinder:hI,Cone:NI,RoundCone:FI,get ActiveCollisionTypes(){return UA},Collider:qI,get MassPropsMode(){return hA},ColliderDesc:RI,ColliderSet:sI,get FeatureType(){return yA},Ray:$A,RayIntersection:AI,RayColliderIntersection:II,RayColliderToi:gI,PointProjection:vA,PointColliderProjection:_A,ShapeTOI:CI,ShapeColliderTOI:BI,ShapeContact:uA,World:eI,PhysicsPipeline:cI,SerializationPipeline:LI,get ActiveEvents(){return FA},TempContactForceEvent:rI,EventQueue:dI,get ActiveHooks(){return qA},get SolverFlags(){return RA},DebugRenderBuffers:HI,DebugRenderPipeline:lI,get QueryFilterFlags(){return NA},QueryPipeline:YI,init:XI,CharacterCollision:tI,KinematicCharacterController:pI});
//# sourceMappingURL=rapier.es.js.map


/***/ }),

/***/ "./node_modules/cannon-es/dist/cannon-es.js":
/*!**************************************************!*\
  !*** ./node_modules/cannon-es/dist/cannon-es.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AABB: () => (/* binding */ AABB),
/* harmony export */   ArrayCollisionMatrix: () => (/* binding */ ArrayCollisionMatrix),
/* harmony export */   BODY_SLEEP_STATES: () => (/* binding */ BODY_SLEEP_STATES),
/* harmony export */   BODY_TYPES: () => (/* binding */ BODY_TYPES),
/* harmony export */   Body: () => (/* binding */ Body),
/* harmony export */   Box: () => (/* binding */ Box),
/* harmony export */   Broadphase: () => (/* binding */ Broadphase),
/* harmony export */   COLLISION_TYPES: () => (/* binding */ COLLISION_TYPES),
/* harmony export */   ConeTwistConstraint: () => (/* binding */ ConeTwistConstraint),
/* harmony export */   Constraint: () => (/* binding */ Constraint),
/* harmony export */   ContactEquation: () => (/* binding */ ContactEquation),
/* harmony export */   ContactMaterial: () => (/* binding */ ContactMaterial),
/* harmony export */   ConvexPolyhedron: () => (/* binding */ ConvexPolyhedron),
/* harmony export */   Cylinder: () => (/* binding */ Cylinder),
/* harmony export */   DistanceConstraint: () => (/* binding */ DistanceConstraint),
/* harmony export */   Equation: () => (/* binding */ Equation),
/* harmony export */   EventTarget: () => (/* binding */ EventTarget),
/* harmony export */   FrictionEquation: () => (/* binding */ FrictionEquation),
/* harmony export */   GSSolver: () => (/* binding */ GSSolver),
/* harmony export */   GridBroadphase: () => (/* binding */ GridBroadphase),
/* harmony export */   Heightfield: () => (/* binding */ Heightfield),
/* harmony export */   HingeConstraint: () => (/* binding */ HingeConstraint),
/* harmony export */   JacobianElement: () => (/* binding */ JacobianElement),
/* harmony export */   LockConstraint: () => (/* binding */ LockConstraint),
/* harmony export */   Mat3: () => (/* binding */ Mat3),
/* harmony export */   Material: () => (/* binding */ Material),
/* harmony export */   NaiveBroadphase: () => (/* binding */ NaiveBroadphase),
/* harmony export */   Narrowphase: () => (/* binding */ Narrowphase),
/* harmony export */   ObjectCollisionMatrix: () => (/* binding */ ObjectCollisionMatrix),
/* harmony export */   Particle: () => (/* binding */ Particle),
/* harmony export */   Plane: () => (/* binding */ Plane),
/* harmony export */   PointToPointConstraint: () => (/* binding */ PointToPointConstraint),
/* harmony export */   Pool: () => (/* binding */ Pool),
/* harmony export */   Quaternion: () => (/* binding */ Quaternion),
/* harmony export */   RAY_MODES: () => (/* binding */ RAY_MODES),
/* harmony export */   Ray: () => (/* binding */ Ray),
/* harmony export */   RaycastResult: () => (/* binding */ RaycastResult),
/* harmony export */   RaycastVehicle: () => (/* binding */ RaycastVehicle),
/* harmony export */   RigidVehicle: () => (/* binding */ RigidVehicle),
/* harmony export */   RotationalEquation: () => (/* binding */ RotationalEquation),
/* harmony export */   RotationalMotorEquation: () => (/* binding */ RotationalMotorEquation),
/* harmony export */   SAPBroadphase: () => (/* binding */ SAPBroadphase),
/* harmony export */   SHAPE_TYPES: () => (/* binding */ SHAPE_TYPES),
/* harmony export */   SPHSystem: () => (/* binding */ SPHSystem),
/* harmony export */   Shape: () => (/* binding */ Shape),
/* harmony export */   Solver: () => (/* binding */ Solver),
/* harmony export */   Sphere: () => (/* binding */ Sphere),
/* harmony export */   SplitSolver: () => (/* binding */ SplitSolver),
/* harmony export */   Spring: () => (/* binding */ Spring),
/* harmony export */   Transform: () => (/* binding */ Transform),
/* harmony export */   Trimesh: () => (/* binding */ Trimesh),
/* harmony export */   Vec3: () => (/* binding */ Vec3),
/* harmony export */   Vec3Pool: () => (/* binding */ Vec3Pool),
/* harmony export */   WheelInfo: () => (/* binding */ WheelInfo),
/* harmony export */   World: () => (/* binding */ World)
/* harmony export */ });
/**
 * Records what objects are colliding with each other
 */
class ObjectCollisionMatrix {
  /**
   * The matrix storage.
   */

  /**
   * @todo Remove useless constructor
   */
  constructor() {
    this.matrix = void 0;
    this.matrix = {};
  }
  /**
   * get
   */


  get(bi, bj) {
    let {
      id: i
    } = bi;
    let {
      id: j
    } = bj;

    if (j > i) {
      const temp = j;
      j = i;
      i = temp;
    }

    return i + "-" + j in this.matrix;
  }
  /**
   * set
   */


  set(bi, bj, value) {
    let {
      id: i
    } = bi;
    let {
      id: j
    } = bj;

    if (j > i) {
      const temp = j;
      j = i;
      i = temp;
    }

    if (value) {
      this.matrix[i + "-" + j] = true;
    } else {
      delete this.matrix[i + "-" + j];
    }
  }
  /**
   * Empty the matrix
   */


  reset() {
    this.matrix = {};
  }
  /**
   * Set max number of objects
   */


  setNumObjects(n) {}

}

/**
 * A 3x3 matrix.
 * Authored by {@link http://github.com/schteppe/ schteppe}
 */
class Mat3 {
  /**
   * A vector of length 9, containing all matrix elements.
   */

  /**
   * @param elements A vector of length 9, containing all matrix elements.
   */
  constructor(elements = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
    this.elements = void 0;
    this.elements = elements;
  }
  /**
   * Sets the matrix to identity
   * @todo Should perhaps be renamed to `setIdentity()` to be more clear.
   * @todo Create another function that immediately creates an identity matrix eg. `eye()`
   */


  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;
  }
  /**
   * Set all elements to zero
   */


  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;
  }
  /**
   * Sets the matrix diagonal elements from a Vec3
   */


  setTrace(vector) {
    const e = this.elements;
    e[0] = vector.x;
    e[4] = vector.y;
    e[8] = vector.z;
  }
  /**
   * Gets the matrix diagonal elements
   */


  getTrace(target = new Vec3()) {
    const e = this.elements;
    target.x = e[0];
    target.y = e[4];
    target.z = e[8];
    return target;
  }
  /**
   * Matrix-Vector multiplication
   * @param v The vector to multiply with
   * @param target Optional, target to save the result in.
   */


  vmult(v, target = new Vec3()) {
    const e = this.elements;
    const x = v.x;
    const y = v.y;
    const z = v.z;
    target.x = e[0] * x + e[1] * y + e[2] * z;
    target.y = e[3] * x + e[4] * y + e[5] * z;
    target.z = e[6] * x + e[7] * y + e[8] * z;
    return target;
  }
  /**
   * Matrix-scalar multiplication
   */


  smult(s) {
    for (let i = 0; i < this.elements.length; i++) {
      this.elements[i] *= s;
    }
  }
  /**
   * Matrix multiplication
   * @param matrix Matrix to multiply with from left side.
   */


  mmult(matrix, target = new Mat3()) {
    const A = this.elements;
    const B = matrix.elements;
    const T = target.elements;
    const a11 = A[0],
          a12 = A[1],
          a13 = A[2],
          a21 = A[3],
          a22 = A[4],
          a23 = A[5],
          a31 = A[6],
          a32 = A[7],
          a33 = A[8];
    const b11 = B[0],
          b12 = B[1],
          b13 = B[2],
          b21 = B[3],
          b22 = B[4],
          b23 = B[5],
          b31 = B[6],
          b32 = B[7],
          b33 = B[8];
    T[0] = a11 * b11 + a12 * b21 + a13 * b31;
    T[1] = a11 * b12 + a12 * b22 + a13 * b32;
    T[2] = a11 * b13 + a12 * b23 + a13 * b33;
    T[3] = a21 * b11 + a22 * b21 + a23 * b31;
    T[4] = a21 * b12 + a22 * b22 + a23 * b32;
    T[5] = a21 * b13 + a22 * b23 + a23 * b33;
    T[6] = a31 * b11 + a32 * b21 + a33 * b31;
    T[7] = a31 * b12 + a32 * b22 + a33 * b32;
    T[8] = a31 * b13 + a32 * b23 + a33 * b33;
    return target;
  }
  /**
   * Scale each column of the matrix
   */


  scale(vector, target = new Mat3()) {
    const e = this.elements;
    const t = target.elements;

    for (let i = 0; i !== 3; i++) {
      t[3 * i + 0] = vector.x * e[3 * i + 0];
      t[3 * i + 1] = vector.y * e[3 * i + 1];
      t[3 * i + 2] = vector.z * e[3 * i + 2];
    }

    return target;
  }
  /**
   * Solve Ax=b
   * @param b The right hand side
   * @param target Optional. Target vector to save in.
   * @return The solution x
   * @todo should reuse arrays
   */


  solve(b, target = new Vec3()) {
    // Construct equations
    const nr = 3; // num rows

    const nc = 4; // num cols

    const eqns = [];
    let i;
    let j;

    for (i = 0; i < nr * nc; i++) {
      eqns.push(0);
    }

    for (i = 0; i < 3; i++) {
      for (j = 0; j < 3; j++) {
        eqns[i + nc * j] = this.elements[i + 3 * j];
      }
    }

    eqns[3 + 4 * 0] = b.x;
    eqns[3 + 4 * 1] = b.y;
    eqns[3 + 4 * 2] = b.z; // Compute right upper triangular version of the matrix - Gauss elimination

    let n = 3;
    const k = n;
    let np;
    const kp = 4; // num rows

    let p;

    do {
      i = k - n;

      if (eqns[i + nc * i] === 0) {
        // the pivot is null, swap lines
        for (j = i + 1; j < k; j++) {
          if (eqns[i + nc * j] !== 0) {
            np = kp;

            do {
              // do ligne( i ) = ligne( i ) + ligne( k )
              p = kp - np;
              eqns[p + nc * i] += eqns[p + nc * j];
            } while (--np);

            break;
          }
        }
      }

      if (eqns[i + nc * i] !== 0) {
        for (j = i + 1; j < k; j++) {
          const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
          np = kp;

          do {
            // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
            p = kp - np;
            eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
          } while (--np);
        }
      }
    } while (--n); // Get the solution


    target.z = eqns[2 * nc + 3] / eqns[2 * nc + 2];
    target.y = (eqns[1 * nc + 3] - eqns[1 * nc + 2] * target.z) / eqns[1 * nc + 1];
    target.x = (eqns[0 * nc + 3] - eqns[0 * nc + 2] * target.z - eqns[0 * nc + 1] * target.y) / eqns[0 * nc + 0];

    if (isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x === Infinity || target.y === Infinity || target.z === Infinity) {
      throw "Could not solve equation! Got x=[" + target.toString() + "], b=[" + b.toString() + "], A=[" + this.toString() + "]";
    }

    return target;
  }
  /**
   * Get an element in the matrix by index. Index starts at 0, not 1!!!
   * @param value If provided, the matrix element will be set to this value.
   */


  e(row, column, value) {
    if (value === undefined) {
      return this.elements[column + 3 * row];
    } else {
      // Set value
      this.elements[column + 3 * row] = value;
    }
  }
  /**
   * Copy another matrix into this matrix object.
   */


  copy(matrix) {
    for (let i = 0; i < matrix.elements.length; i++) {
      this.elements[i] = matrix.elements[i];
    }

    return this;
  }
  /**
   * Returns a string representation of the matrix.
   */


  toString() {
    let r = '';
    const sep = ',';

    for (let i = 0; i < 9; i++) {
      r += this.elements[i] + sep;
    }

    return r;
  }
  /**
   * reverse the matrix
   * @param target Target matrix to save in.
   * @return The solution x
   */


  reverse(target = new Mat3()) {
    // Construct equations
    const nr = 3; // num rows

    const nc = 6; // num cols

    const eqns = reverse_eqns;
    let i;
    let j;

    for (i = 0; i < 3; i++) {
      for (j = 0; j < 3; j++) {
        eqns[i + nc * j] = this.elements[i + 3 * j];
      }
    }

    eqns[3 + 6 * 0] = 1;
    eqns[3 + 6 * 1] = 0;
    eqns[3 + 6 * 2] = 0;
    eqns[4 + 6 * 0] = 0;
    eqns[4 + 6 * 1] = 1;
    eqns[4 + 6 * 2] = 0;
    eqns[5 + 6 * 0] = 0;
    eqns[5 + 6 * 1] = 0;
    eqns[5 + 6 * 2] = 1; // Compute right upper triangular version of the matrix - Gauss elimination

    let n = 3;
    const k = n;
    let np;
    const kp = nc; // num rows

    let p;

    do {
      i = k - n;

      if (eqns[i + nc * i] === 0) {
        // the pivot is null, swap lines
        for (j = i + 1; j < k; j++) {
          if (eqns[i + nc * j] !== 0) {
            np = kp;

            do {
              // do line( i ) = line( i ) + line( k )
              p = kp - np;
              eqns[p + nc * i] += eqns[p + nc * j];
            } while (--np);

            break;
          }
        }
      }

      if (eqns[i + nc * i] !== 0) {
        for (j = i + 1; j < k; j++) {
          const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
          np = kp;

          do {
            // do line( k ) = line( k ) - multiplier * line( i )
            p = kp - np;
            eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
          } while (--np);
        }
      }
    } while (--n); // eliminate the upper left triangle of the matrix


    i = 2;

    do {
      j = i - 1;

      do {
        const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
        np = nc;

        do {
          p = nc - np;
          eqns[p + nc * j] = eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
        } while (--np);
      } while (j--);
    } while (--i); // operations on the diagonal


    i = 2;

    do {
      const multiplier = 1 / eqns[i + nc * i];
      np = nc;

      do {
        p = nc - np;
        eqns[p + nc * i] = eqns[p + nc * i] * multiplier;
      } while (--np);
    } while (i--);

    i = 2;

    do {
      j = 2;

      do {
        p = eqns[nr + j + nc * i];

        if (isNaN(p) || p === Infinity) {
          throw "Could not reverse! A=[" + this.toString() + "]";
        }

        target.e(i, j, p);
      } while (j--);
    } while (i--);

    return target;
  }
  /**
   * Set the matrix from a quaterion
   */


  setRotationFromQuaternion(q) {
    const x = q.x;
    const y = q.y;
    const z = q.z;
    const w = q.w;
    const x2 = x + x;
    const y2 = y + y;
    const z2 = z + z;
    const xx = x * x2;
    const xy = x * y2;
    const xz = x * z2;
    const yy = y * y2;
    const yz = y * z2;
    const zz = z * z2;
    const wx = w * x2;
    const wy = w * y2;
    const wz = w * z2;
    const e = this.elements;
    e[3 * 0 + 0] = 1 - (yy + zz);
    e[3 * 0 + 1] = xy - wz;
    e[3 * 0 + 2] = xz + wy;
    e[3 * 1 + 0] = xy + wz;
    e[3 * 1 + 1] = 1 - (xx + zz);
    e[3 * 1 + 2] = yz - wx;
    e[3 * 2 + 0] = xz - wy;
    e[3 * 2 + 1] = yz + wx;
    e[3 * 2 + 2] = 1 - (xx + yy);
    return this;
  }
  /**
   * Transpose the matrix
   * @param target Optional. Where to store the result.
   * @return The target Mat3, or a new Mat3 if target was omitted.
   */


  transpose(target = new Mat3()) {
    const M = this.elements;
    const T = target.elements;
    let tmp; //Set diagonals

    T[0] = M[0];
    T[4] = M[4];
    T[8] = M[8];
    tmp = M[1];
    T[1] = M[3];
    T[3] = tmp;
    tmp = M[2];
    T[2] = M[6];
    T[6] = tmp;
    tmp = M[5];
    T[5] = M[7];
    T[7] = tmp;
    return target;
  }

}
const reverse_eqns = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

/**
 * 3-dimensional vector
 * @example
 *     const v = new Vec3(1, 2, 3)
 *     console.log('x=' + v.x) // x=1
 */

class Vec3 {
  constructor(x = 0.0, y = 0.0, z = 0.0) {
    this.x = void 0;
    this.y = void 0;
    this.z = void 0;
    this.x = x;
    this.y = y;
    this.z = z;
  }
  /**
   * Vector cross product
   * @param target Optional target to save in.
   */


  cross(vector, target = new Vec3()) {
    const vx = vector.x;
    const vy = vector.y;
    const vz = vector.z;
    const x = this.x;
    const y = this.y;
    const z = this.z;
    target.x = y * vz - z * vy;
    target.y = z * vx - x * vz;
    target.z = x * vy - y * vx;
    return target;
  }
  /**
   * Set the vectors' 3 elements
   */


  set(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
    return this;
  }
  /**
   * Set all components of the vector to zero.
   */


  setZero() {
    this.x = this.y = this.z = 0;
  }
  /**
   * Vector addition
   */


  vadd(vector, target) {
    if (target) {
      target.x = vector.x + this.x;
      target.y = vector.y + this.y;
      target.z = vector.z + this.z;
    } else {
      return new Vec3(this.x + vector.x, this.y + vector.y, this.z + vector.z);
    }
  }
  /**
   * Vector subtraction
   * @param target Optional target to save in.
   */


  vsub(vector, target) {
    if (target) {
      target.x = this.x - vector.x;
      target.y = this.y - vector.y;
      target.z = this.z - vector.z;
    } else {
      return new Vec3(this.x - vector.x, this.y - vector.y, this.z - vector.z);
    }
  }
  /**
   * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
   *
   * See {@link https://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf Umeå University Lecture}
   */


  crossmat() {
    return new Mat3([0, -this.z, this.y, this.z, 0, -this.x, -this.y, this.x, 0]);
  }
  /**
   * Normalize the vector. Note that this changes the values in the vector.
    * @return Returns the norm of the vector
   */


  normalize() {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    const n = Math.sqrt(x * x + y * y + z * z);

    if (n > 0.0) {
      const invN = 1 / n;
      this.x *= invN;
      this.y *= invN;
      this.z *= invN;
    } else {
      // Make something up
      this.x = 0;
      this.y = 0;
      this.z = 0;
    }

    return n;
  }
  /**
   * Get the version of this vector that is of length 1.
   * @param target Optional target to save in
   * @return Returns the unit vector
   */


  unit(target = new Vec3()) {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    let ninv = Math.sqrt(x * x + y * y + z * z);

    if (ninv > 0.0) {
      ninv = 1.0 / ninv;
      target.x = x * ninv;
      target.y = y * ninv;
      target.z = z * ninv;
    } else {
      target.x = 1;
      target.y = 0;
      target.z = 0;
    }

    return target;
  }
  /**
   * Get the length of the vector
   */


  length() {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    return Math.sqrt(x * x + y * y + z * z);
  }
  /**
   * Get the squared length of the vector.
   */


  lengthSquared() {
    return this.dot(this);
  }
  /**
   * Get distance from this point to another point
   */


  distanceTo(p) {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    const px = p.x;
    const py = p.y;
    const pz = p.z;
    return Math.sqrt((px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z));
  }
  /**
   * Get squared distance from this point to another point
   */


  distanceSquared(p) {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    const px = p.x;
    const py = p.y;
    const pz = p.z;
    return (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z);
  }
  /**
   * Multiply all the components of the vector with a scalar.
   * @param target The vector to save the result in.
   */


  scale(scalar, target = new Vec3()) {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    target.x = scalar * x;
    target.y = scalar * y;
    target.z = scalar * z;
    return target;
  }
  /**
   * Multiply the vector with an other vector, component-wise.
   * @param target The vector to save the result in.
   */


  vmul(vector, target = new Vec3()) {
    target.x = vector.x * this.x;
    target.y = vector.y * this.y;
    target.z = vector.z * this.z;
    return target;
  }
  /**
   * Scale a vector and add it to this vector. Save the result in "target". (target = this + vector * scalar)
   * @param target The vector to save the result in.
   */


  addScaledVector(scalar, vector, target = new Vec3()) {
    target.x = this.x + scalar * vector.x;
    target.y = this.y + scalar * vector.y;
    target.z = this.z + scalar * vector.z;
    return target;
  }
  /**
   * Calculate dot product
   * @param vector
   */


  dot(vector) {
    return this.x * vector.x + this.y * vector.y + this.z * vector.z;
  }

  isZero() {
    return this.x === 0 && this.y === 0 && this.z === 0;
  }
  /**
   * Make the vector point in the opposite direction.
   * @param target Optional target to save in
   */


  negate(target = new Vec3()) {
    target.x = -this.x;
    target.y = -this.y;
    target.z = -this.z;
    return target;
  }
  /**
   * Compute two artificial tangents to the vector
   * @param t1 Vector object to save the first tangent in
   * @param t2 Vector object to save the second tangent in
   */


  tangents(t1, t2) {
    const norm = this.length();

    if (norm > 0.0) {
      const n = Vec3_tangents_n;
      const inorm = 1 / norm;
      n.set(this.x * inorm, this.y * inorm, this.z * inorm);
      const randVec = Vec3_tangents_randVec;

      if (Math.abs(n.x) < 0.9) {
        randVec.set(1, 0, 0);
        n.cross(randVec, t1);
      } else {
        randVec.set(0, 1, 0);
        n.cross(randVec, t1);
      }

      n.cross(t1, t2);
    } else {
      // The normal length is zero, make something up
      t1.set(1, 0, 0);
      t2.set(0, 1, 0);
    }
  }
  /**
   * Converts to a more readable format
   */


  toString() {
    return this.x + "," + this.y + "," + this.z;
  }
  /**
   * Converts to an array
   */


  toArray() {
    return [this.x, this.y, this.z];
  }
  /**
   * Copies value of source to this vector.
   */


  copy(vector) {
    this.x = vector.x;
    this.y = vector.y;
    this.z = vector.z;
    return this;
  }
  /**
   * Do a linear interpolation between two vectors
   * @param t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.
   */


  lerp(vector, t, target) {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    target.x = x + (vector.x - x) * t;
    target.y = y + (vector.y - y) * t;
    target.z = z + (vector.z - z) * t;
  }
  /**
   * Check if a vector equals is almost equal to another one.
   */


  almostEquals(vector, precision = 1e-6) {
    if (Math.abs(this.x - vector.x) > precision || Math.abs(this.y - vector.y) > precision || Math.abs(this.z - vector.z) > precision) {
      return false;
    }

    return true;
  }
  /**
   * Check if a vector is almost zero
   */


  almostZero(precision = 1e-6) {
    if (Math.abs(this.x) > precision || Math.abs(this.y) > precision || Math.abs(this.z) > precision) {
      return false;
    }

    return true;
  }
  /**
   * Check if the vector is anti-parallel to another vector.
   * @param precision Set to zero for exact comparisons
   */


  isAntiparallelTo(vector, precision) {
    this.negate(antip_neg);
    return antip_neg.almostEquals(vector, precision);
  }
  /**
   * Clone the vector
   */


  clone() {
    return new Vec3(this.x, this.y, this.z);
  }

}
Vec3.ZERO = void 0;
Vec3.UNIT_X = void 0;
Vec3.UNIT_Y = void 0;
Vec3.UNIT_Z = void 0;
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();
const Vec3_tangents_randVec = new Vec3();
const antip_neg = new Vec3();

/**
 * Axis aligned bounding box class.
 */
class AABB {
  /**
   * The lower bound of the bounding box
   */

  /**
   * The upper bound of the bounding box
   */
  constructor(options = {}) {
    this.lowerBound = void 0;
    this.upperBound = void 0;
    this.lowerBound = new Vec3();
    this.upperBound = new Vec3();

    if (options.lowerBound) {
      this.lowerBound.copy(options.lowerBound);
    }

    if (options.upperBound) {
      this.upperBound.copy(options.upperBound);
    }
  }
  /**
   * Set the AABB bounds from a set of points.
   * @param points An array of Vec3's.
   * @return The self object
   */


  setFromPoints(points, position, quaternion, skinSize) {
    const l = this.lowerBound;
    const u = this.upperBound;
    const q = quaternion; // Set to the first point

    l.copy(points[0]);

    if (q) {
      q.vmult(l, l);
    }

    u.copy(l);

    for (let i = 1; i < points.length; i++) {
      let p = points[i];

      if (q) {
        q.vmult(p, tmp$1);
        p = tmp$1;
      }

      if (p.x > u.x) {
        u.x = p.x;
      }

      if (p.x < l.x) {
        l.x = p.x;
      }

      if (p.y > u.y) {
        u.y = p.y;
      }

      if (p.y < l.y) {
        l.y = p.y;
      }

      if (p.z > u.z) {
        u.z = p.z;
      }

      if (p.z < l.z) {
        l.z = p.z;
      }
    } // Add offset


    if (position) {
      position.vadd(l, l);
      position.vadd(u, u);
    }

    if (skinSize) {
      l.x -= skinSize;
      l.y -= skinSize;
      l.z -= skinSize;
      u.x += skinSize;
      u.y += skinSize;
      u.z += skinSize;
    }

    return this;
  }
  /**
   * Copy bounds from an AABB to this AABB
   * @param aabb Source to copy from
   * @return The this object, for chainability
   */


  copy(aabb) {
    this.lowerBound.copy(aabb.lowerBound);
    this.upperBound.copy(aabb.upperBound);
    return this;
  }
  /**
   * Clone an AABB
   */


  clone() {
    return new AABB().copy(this);
  }
  /**
   * Extend this AABB so that it covers the given AABB too.
   */


  extend(aabb) {
    this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);
    this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);
    this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);
    this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);
    this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);
    this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);
  }
  /**
   * Returns true if the given AABB overlaps this AABB.
   */


  overlaps(aabb) {
    const l1 = this.lowerBound;
    const u1 = this.upperBound;
    const l2 = aabb.lowerBound;
    const u2 = aabb.upperBound; //      l2        u2
    //      |---------|
    // |--------|
    // l1       u1

    const overlapsX = l2.x <= u1.x && u1.x <= u2.x || l1.x <= u2.x && u2.x <= u1.x;
    const overlapsY = l2.y <= u1.y && u1.y <= u2.y || l1.y <= u2.y && u2.y <= u1.y;
    const overlapsZ = l2.z <= u1.z && u1.z <= u2.z || l1.z <= u2.z && u2.z <= u1.z;
    return overlapsX && overlapsY && overlapsZ;
  } // Mostly for debugging


  volume() {
    const l = this.lowerBound;
    const u = this.upperBound;
    return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);
  }
  /**
   * Returns true if the given AABB is fully contained in this AABB.
   */


  contains(aabb) {
    const l1 = this.lowerBound;
    const u1 = this.upperBound;
    const l2 = aabb.lowerBound;
    const u2 = aabb.upperBound; //      l2        u2
    //      |---------|
    // |---------------|
    // l1              u1

    return l1.x <= l2.x && u1.x >= 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;
    const 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);
  }
  /**
   * Get the representation of an AABB in another frame.
   * @return The "target" AABB object.
   */


  toLocalFrame(frame, target) {
    const corners = transformIntoFrame_corners;
    const a = corners[0];
    const b = corners[1];
    const c = corners[2];
    const d = corners[3];
    const e = corners[4];
    const f = corners[5];
    const g = corners[6];
    const h = corners[7]; // Get corners in current frame

    this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame

    for (let i = 0; i !== 8; i++) {
      const corner = corners[i];
      frame.pointToLocal(corner, corner);
    }

    return target.setFromPoints(corners);
  }
  /**
   * Get the representation of an AABB in the global frame.
   * @return The "target" AABB object.
   */


  toWorldFrame(frame, target) {
    const corners = transformIntoFrame_corners;
    const a = corners[0];
    const b = corners[1];
    const c = corners[2];
    const d = corners[3];
    const e = corners[4];
    const f = corners[5];
    const g = corners[6];
    const h = corners[7]; // Get corners in current frame

    this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame

    for (let i = 0; i !== 8; i++) {
      const corner = corners[i];
      frame.pointToWorld(corner, corner);
    }

    return target.setFromPoints(corners);
  }
  /**
   * Check if the AABB is hit by a ray.
   */


  overlapsRay(ray) {
    const {
      direction,
      from
    } = ray; // const t = 0
    // ray.direction is unit direction vector of ray

    const dirFracX = 1 / direction.x;
    const dirFracY = 1 / direction.y;
    const dirFracZ = 1 / direction.z; // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner

    const t1 = (this.lowerBound.x - from.x) * dirFracX;
    const t2 = (this.upperBound.x - from.x) * dirFracX;
    const t3 = (this.lowerBound.y - from.y) * dirFracY;
    const t4 = (this.upperBound.y - from.y) * dirFracY;
    const t5 = (this.lowerBound.z - from.z) * dirFracZ;
    const t6 = (this.upperBound.z - from.z) * dirFracZ; // const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
    // const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));

    const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
    const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us

    if (tmax < 0) {
      //t = tmax;
      return false;
    } // if tmin > tmax, ray doesn't intersect AABB


    if (tmin > tmax) {
      //t = tmax;
      return false;
    }

    return true;
  }

}
const tmp$1 = new Vec3();
const transformIntoFrame_corners = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];

/**
 * Collision "matrix".
 * It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
 */
class ArrayCollisionMatrix {
  /**
   * The matrix storage.
   */
  constructor() {
    this.matrix = void 0;
    this.matrix = [];
  }
  /**
   * Get an element
   */


  get(bi, bj) {
    let {
      index: i
    } = bi;
    let {
      index: j
    } = bj;

    if (j > i) {
      const temp = j;
      j = i;
      i = temp;
    }

    return this.matrix[(i * (i + 1) >> 1) + j - 1];
  }
  /**
   * Set an element
   */


  set(bi, bj, value) {
    let {
      index: i
    } = bi;
    let {
      index: j
    } = bj;

    if (j > i) {
      const temp = j;
      j = i;
      i = temp;
    }

    this.matrix[(i * (i + 1) >> 1) + j - 1] = value ? 1 : 0;
  }
  /**
   * Sets all elements to zero
   */


  reset() {
    for (let i = 0, l = this.matrix.length; i !== l; i++) {
      this.matrix[i] = 0;
    }
  }
  /**
   * Sets the max number of objects
   */


  setNumObjects(n) {
    this.matrix.length = n * (n - 1) >> 1;
  }

}

/**
 * Base class for objects that dispatches events.
 */
class EventTarget {
  constructor() {
    this._listeners = void 0;
  }

  /**
   * Add an event listener
   * @return The self object, for chainability.
   */
  addEventListener(type, listener) {
    if (this._listeners === undefined) {
      this._listeners = {};
    }

    const listeners = this._listeners;

    if (listeners[type] === undefined) {
      listeners[type] = [];
    }

    if (!listeners[type].includes(listener)) {
      listeners[type].push(listener);
    }

    return this;
  }
  /**
   * Check if an event listener is added
   */


  hasEventListener(type, listener) {
    if (this._listeners === undefined) {
      return false;
    }

    const listeners = this._listeners;

    if (listeners[type] !== undefined && listeners[type].includes(listener)) {
      return true;
    }

    return false;
  }
  /**
   * Check if any event listener of the given type is added
   */


  hasAnyEventListener(type) {
    if (this._listeners === undefined) {
      return false;
    }

    const listeners = this._listeners;
    return listeners[type] !== undefined;
  }
  /**
   * Remove an event listener
   * @return The self object, for chainability.
   */


  removeEventListener(type, listener) {
    if (this._listeners === undefined) {
      return this;
    }

    const listeners = this._listeners;

    if (listeners[type] === undefined) {
      return this;
    }

    const index = listeners[type].indexOf(listener);

    if (index !== -1) {
      listeners[type].splice(index, 1);
    }

    return this;
  }
  /**
   * Emit an event.
   * @return The self object, for chainability.
   */


  dispatchEvent(event) {
    if (this._listeners === undefined) {
      return this;
    }

    const listeners = this._listeners;
    const listenerArray = listeners[event.type];

    if (listenerArray !== undefined) {
      event.target = this;

      for (let i = 0, l = listenerArray.length; i < l; i++) {
        listenerArray[i].call(this, event);
      }
    }

    return this;
  }

}

/**
 * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.
 * @param x Multiplier of the imaginary basis vector i.
 * @param y Multiplier of the imaginary basis vector j.
 * @param z Multiplier of the imaginary basis vector k.
 * @param w Multiplier of the real part.
 * @see http://en.wikipedia.org/wiki/Quaternion
 */

class Quaternion {
  constructor(x = 0, y = 0, z = 0, w = 1) {
    this.x = void 0;
    this.y = void 0;
    this.z = void 0;
    this.w = void 0;
    this.x = x;
    this.y = y;
    this.z = z;
    this.w = w;
  }
  /**
   * Set the value of the quaternion.
   */


  set(x, y, z, w) {
    this.x = x;
    this.y = y;
    this.z = z;
    this.w = w;
    return this;
  }
  /**
   * Convert to a readable format
   * @return "x,y,z,w"
   */


  toString() {
    return this.x + "," + this.y + "," + this.z + "," + this.w;
  }
  /**
   * Convert to an Array
   * @return [x, y, z, w]
   */


  toArray() {
    return [this.x, this.y, this.z, this.w];
  }
  /**
   * Set the quaternion components given an axis and an angle in radians.
   */


  setFromAxisAngle(vector, angle) {
    const s = Math.sin(angle * 0.5);
    this.x = vector.x * s;
    this.y = vector.y * s;
    this.z = vector.z * s;
    this.w = Math.cos(angle * 0.5);
    return this;
  }
  /**
   * Converts the quaternion to [ axis, angle ] representation.
   * @param targetAxis A vector object to reuse for storing the axis.
   * @return An array, first element is the axis and the second is the angle in radians.
   */


  toAxisAngle(targetAxis = new Vec3()) {
    this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised

    const angle = 2 * Math.acos(this.w);
    const s = Math.sqrt(1 - this.w * this.w); // assuming quaternion normalised then w is less than 1, so term always positive.

    if (s < 0.001) {
      // test to avoid divide by zero, s is always positive due to sqrt
      // if s close to zero then direction of axis not important
      targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;

      targetAxis.y = this.y;
      targetAxis.z = this.z;
    } else {
      targetAxis.x = this.x / s; // normalise axis

      targetAxis.y = this.y / s;
      targetAxis.z = this.z / s;
    }

    return [targetAxis, angle];
  }
  /**
   * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
   */


  setFromVectors(u, v) {
    if (u.isAntiparallelTo(v)) {
      const t1 = sfv_t1;
      const t2 = sfv_t2;
      u.tangents(t1, t2);
      this.setFromAxisAngle(t1, Math.PI);
    } else {
      const a = u.cross(v);
      this.x = a.x;
      this.y = a.y;
      this.z = a.z;
      this.w = Math.sqrt(u.length() ** 2 * v.length() ** 2) + u.dot(v);
      this.normalize();
    }

    return this;
  }
  /**
   * Multiply the quaternion with an other quaternion.
   */


  mult(quat, target = new Quaternion()) {
    const ax = this.x;
    const ay = this.y;
    const az = this.z;
    const aw = this.w;
    const bx = quat.x;
    const by = quat.y;
    const bz = quat.z;
    const bw = quat.w;
    target.x = ax * bw + aw * bx + ay * bz - az * by;
    target.y = ay * bw + aw * by + az * bx - ax * bz;
    target.z = az * bw + aw * bz + ax * by - ay * bx;
    target.w = aw * bw - ax * bx - ay * by - az * bz;
    return target;
  }
  /**
   * Get the inverse quaternion rotation.
   */


  inverse(target = new Quaternion()) {
    const x = this.x;
    const y = this.y;
    const z = this.z;
    const w = this.w;
    this.conjugate(target);
    const inorm2 = 1 / (x * x + y * y + z * z + w * w);
    target.x *= inorm2;
    target.y *= inorm2;
    target.z *= inorm2;
    target.w *= inorm2;
    return target;
  }
  /**
   * Get the quaternion conjugate
   */


  conjugate(target = new Quaternion()) {
    target.x = -this.x;
    target.y = -this.y;
    target.z = -this.z;
    target.w = this.w;
    return target;
  }
  /**
   * Normalize the quaternion. Note that this changes the values of the quaternion.
   */


  normalize() {
    let l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);

    if (l === 0) {
      this.x = 0;
      this.y = 0;
      this.z = 0;
      this.w = 0;
    } else {
      l = 1 / l;
      this.x *= l;
      this.y *= l;
      this.z *= l;
      this.w *= l;
    }

    return this;
  }
  /**
   * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
   * @author unphased, https://github.com/unphased
   */


  normalizeFast() {
    const f = (3.0 - (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)) / 2.0;

    if (f === 0) {
      this.x = 0;
      this.y = 0;
      this.z = 0;
      this.w = 0;
    } else {
      this.x *= f;
      this.y *= f;
      this.z *= f;
      this.w *= f;
    }

    return this;
  }
  /**
   * Multiply the quaternion by a vector
   */


  vmult(v, target = new Vec3()) {
    const x = v.x;
    const y = v.y;
    const z = v.z;
    const qx = this.x;
    const qy = this.y;
    const qz = this.z;
    const qw = this.w; // q*v

    const ix = qw * x + qy * z - qz * y;
    const iy = qw * y + qz * x - qx * z;
    const iz = qw * z + qx * y - qy * x;
    const iw = -qx * x - qy * y - qz * z;
    target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
    target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
    target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
    return target;
  }
  /**
   * Copies value of source to this quaternion.
   * @return this
   */


  copy(quat) {
    this.x = quat.x;
    this.y = quat.y;
    this.z = quat.z;
    this.w = quat.w;
    return this;
  }
  /**
   * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: https://www.euclideanspace.com/maths/standards/index.htm
   * @param order Three-character string, defaults to "YZX"
   */


  toEuler(target, order = 'YZX') {
    let heading;
    let attitude;
    let bank;
    const x = this.x;
    const y = this.y;
    const z = this.z;
    const w = this.w;

    switch (order) {
      case 'YZX':
        const test = x * y + z * w;

        if (test > 0.499) {
          // singularity at north pole
          heading = 2 * Math.atan2(x, w);
          attitude = Math.PI / 2;
          bank = 0;
        }

        if (test < -0.499) {
          // singularity at south pole
          heading = -2 * Math.atan2(x, w);
          attitude = -Math.PI / 2;
          bank = 0;
        }

        if (heading === undefined) {
          const sqx = x * x;
          const sqy = y * y;
          const sqz = z * z;
          heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading

          attitude = Math.asin(2 * test); // attitude

          bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
        }

        break;

      default:
        throw new Error("Euler order " + order + " not supported yet.");
    }

    target.y = heading;
    target.z = attitude;
    target.x = bank;
  }
  /**
   * @param order The order to apply angles: 'XYZ' or 'YXZ' or any other combination.
   *
   * See {@link https://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors MathWorks} reference
   */


  setFromEuler(x, y, z, order = 'XYZ') {
    const c1 = Math.cos(x / 2);
    const c2 = Math.cos(y / 2);
    const c3 = Math.cos(z / 2);
    const s1 = Math.sin(x / 2);
    const s2 = Math.sin(y / 2);
    const s3 = Math.sin(z / 2);

    if (order === 'XYZ') {
      this.x = s1 * c2 * c3 + c1 * s2 * s3;
      this.y = c1 * s2 * c3 - s1 * c2 * s3;
      this.z = c1 * c2 * s3 + s1 * s2 * c3;
      this.w = c1 * c2 * c3 - s1 * s2 * s3;
    } else if (order === 'YXZ') {
      this.x = s1 * c2 * c3 + c1 * s2 * s3;
      this.y = c1 * s2 * c3 - s1 * c2 * s3;
      this.z = c1 * c2 * s3 - s1 * s2 * c3;
      this.w = c1 * c2 * c3 + s1 * s2 * s3;
    } else if (order === 'ZXY') {
      this.x = s1 * c2 * c3 - c1 * s2 * s3;
      this.y = c1 * s2 * c3 + s1 * c2 * s3;
      this.z = c1 * c2 * s3 + s1 * s2 * c3;
      this.w = c1 * c2 * c3 - s1 * s2 * s3;
    } else if (order === 'ZYX') {
      this.x = s1 * c2 * c3 - c1 * s2 * s3;
      this.y = c1 * s2 * c3 + s1 * c2 * s3;
      this.z = c1 * c2 * s3 - s1 * s2 * c3;
      this.w = c1 * c2 * c3 + s1 * s2 * s3;
    } else if (order === 'YZX') {
      this.x = s1 * c2 * c3 + c1 * s2 * s3;
      this.y = c1 * s2 * c3 + s1 * c2 * s3;
      this.z = c1 * c2 * s3 - s1 * s2 * c3;
      this.w = c1 * c2 * c3 - s1 * s2 * s3;
    } else if (order === 'XZY') {
      this.x = s1 * c2 * c3 - c1 * s2 * s3;
      this.y = c1 * s2 * c3 - s1 * c2 * s3;
      this.z = c1 * c2 * s3 + s1 * s2 * c3;
      this.w = c1 * c2 * c3 + s1 * s2 * s3;
    }

    return this;
  }

  clone() {
    return new Quaternion(this.x, this.y, this.z, this.w);
  }
  /**
   * Performs a spherical linear interpolation between two quat
   *
   * @param toQuat second operand
   * @param t interpolation amount between the self quaternion and toQuat
   * @param target A quaternion to store the result in. If not provided, a new one will be created.
   * @returns {Quaternion} The "target" object
   */


  slerp(toQuat, t, target = new Quaternion()) {
    const ax = this.x;
    const ay = this.y;
    const az = this.z;
    const aw = this.w;
    let bx = toQuat.x;
    let by = toQuat.y;
    let bz = toQuat.z;
    let bw = toQuat.w;
    let omega;
    let cosom;
    let sinom;
    let scale0;
    let scale1; // calc cosine

    cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)

    if (cosom < 0.0) {
      cosom = -cosom;
      bx = -bx;
      by = -by;
      bz = -bz;
      bw = -bw;
    } // calculate coefficients


    if (1.0 - cosom > 0.000001) {
      // standard case (slerp)
      omega = Math.acos(cosom);
      sinom = Math.sin(omega);
      scale0 = Math.sin((1.0 - t) * omega) / sinom;
      scale1 = Math.sin(t * omega) / sinom;
    } else {
      // "from" and "to" quaternions are very close
      //  ... so we can do a linear interpolation
      scale0 = 1.0 - t;
      scale1 = t;
    } // calculate final values


    target.x = scale0 * ax + scale1 * bx;
    target.y = scale0 * ay + scale1 * by;
    target.z = scale0 * az + scale1 * bz;
    target.w = scale0 * aw + scale1 * bw;
    return target;
  }
  /**
   * Rotate an absolute orientation quaternion given an angular velocity and a time step.
   */


  integrate(angularVelocity, dt, angularFactor, 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;
    const half_dt = dt * 0.5;
    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);
    return target;
  }

}
const sfv_t1 = new Vec3();
const sfv_t2 = new Vec3();

/**
 * The available shape types.
 */
const SHAPE_TYPES = {
  /** SPHERE */
  SPHERE: 1,

  /** PLANE */
  PLANE: 2,

  /** BOX */
  BOX: 4,

  /** COMPOUND */
  COMPOUND: 8,

  /** CONVEXPOLYHEDRON */
  CONVEXPOLYHEDRON: 16,

  /** HEIGHTFIELD */
  HEIGHTFIELD: 32,

  /** PARTICLE */
  PARTICLE: 64,

  /** CYLINDER */
  CYLINDER: 128,

  /** TRIMESH */
  TRIMESH: 256
};
/**
 * ShapeType
 */

/**
 * Base class for shapes
 */
class Shape {
  /**
   * Identifier of the Shape.
   */

  /**
   * The type of this shape. Must be set to an int > 0 by subclasses.
   */

  /**
   * The local bounding sphere radius of this shape.
   */

  /**
   * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
   * @default true
   */

  /**
   * @default 1
   */

  /**
   * @default -1
   */

  /**
   * Optional material of the shape that regulates contact properties.
   */

  /**
   * The body to which the shape is added to.
   */

  /**
   * All the Shape types.
   */
  constructor(options = {}) {
    this.id = void 0;
    this.type = void 0;
    this.boundingSphereRadius = void 0;
    this.collisionResponse = void 0;
    this.collisionFilterGroup = void 0;
    this.collisionFilterMask = void 0;
    this.material = void 0;
    this.body = void 0;
    this.id = Shape.idCounter++;
    this.type = options.type || 0;
    this.boundingSphereRadius = 0;
    this.collisionResponse = options.collisionResponse ? options.collisionResponse : true;
    this.collisionFilterGroup = options.collisionFilterGroup !== undefined ? options.collisionFilterGroup : 1;
    this.collisionFilterMask = options.collisionFilterMask !== undefined ? options.collisionFilterMask : -1;
    this.material = options.material ? options.material : null;
    this.body = null;
  }
  /**
   * Computes the bounding sphere radius.
   * The result is stored in the property `.boundingSphereRadius`
   */


  updateBoundingSphereRadius() {
    throw "computeBoundingSphereRadius() not implemented for shape type " + this.type;
  }
  /**
   * Get the volume of this shape
   */


  volume() {
    throw "volume() not implemented for shape type " + this.type;
  }
  /**
   * Calculates the inertia in the local frame for this shape.
   * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
   */


  calculateLocalInertia(mass, target) {
    throw "calculateLocalInertia() not implemented for shape type " + this.type;
  }
  /**
   * @todo use abstract for these kind of methods
   */


  calculateWorldAABB(pos, quat, min, max) {
    throw "calculateWorldAABB() not implemented for shape type " + this.type;
  }

}
Shape.idCounter = 0;
Shape.types = SHAPE_TYPES;

/**
 * Transformation utilities.
 */
class Transform {
  /**
   * position
   */

  /**
   * quaternion
   */
  constructor(options = {}) {
    this.position = void 0;
    this.quaternion = void 0;
    this.position = new Vec3();
    this.quaternion = new Quaternion();

    if (options.position) {
      this.position.copy(options.position);
    }

    if (options.quaternion) {
      this.quaternion.copy(options.quaternion);
    }
  }
  /**
   * Get a global point in local transform coordinates.
   */


  pointToLocal(worldPoint, result) {
    return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  }
  /**
   * Get a local point in global transform coordinates.
   */


  pointToWorld(localPoint, result) {
    return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  }
  /**
   * vectorToWorldFrame
   */


  vectorToWorldFrame(localVector, result = new Vec3()) {
    this.quaternion.vmult(localVector, result);
    return result;
  }
  /**
   * pointToLocalFrame
   */


  static pointToLocalFrame(position, quaternion, worldPoint, result = new Vec3()) {
    worldPoint.vsub(position, result);
    quaternion.conjugate(tmpQuat$1);
    tmpQuat$1.vmult(result, result);
    return result;
  }
  /**
   * pointToWorldFrame
   */


  static pointToWorldFrame(position, quaternion, localPoint, result = new Vec3()) {
    quaternion.vmult(localPoint, result);
    result.vadd(position, result);
    return result;
  }
  /**
   * vectorToWorldFrame
   */


  static vectorToWorldFrame(quaternion, localVector, result = new Vec3()) {
    quaternion.vmult(localVector, result);
    return result;
  }
  /**
   * vectorToLocalFrame
   */


  static vectorToLocalFrame(position, quaternion, worldVector, result = new Vec3()) {
    quaternion.w *= -1;
    quaternion.vmult(worldVector, result);
    quaternion.w *= -1;
    return result;
  }

}
const tmpQuat$1 = new Quaternion();

/**
 * A set of polygons describing a convex shape.
 *
 * The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
 * in the same 3D plane), instead these should be merged into one polygon.
 *
 * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
 * @author schteppe / https://github.com/schteppe
 * @see https://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
 *
 * @todo Move the clipping functions to ContactGenerator?
 * @todo Automatically merge coplanar polygons in constructor.
 * @example
 *     const convexShape = new CANNON.ConvexPolyhedron({ vertices, faces })
 *     const convexBody = new CANNON.Body({ mass: 1, shape: convexShape })
 *     world.addBody(convexBody)
 */
class ConvexPolyhedron extends Shape {
  /** vertices */

  /**
   * Array of integer arrays, indicating which vertices each face consists of
   */

  /** faceNormals */

  /** worldVertices */

  /** worldVerticesNeedsUpdate */

  /** worldFaceNormals */

  /** worldFaceNormalsNeedsUpdate */

  /**
   * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
   */

  /** uniqueEdges */

  /**
   * @param vertices An array of Vec3's
   * @param faces Array of integer arrays, describing which vertices that is included in each face.
   */
  constructor(props = {}) {
    const {
      vertices = [],
      faces = [],
      normals = [],
      axes,
      boundingSphereRadius
    } = props;
    super({
      type: Shape.types.CONVEXPOLYHEDRON
    });
    this.vertices = void 0;
    this.faces = void 0;
    this.faceNormals = void 0;
    this.worldVertices = void 0;
    this.worldVerticesNeedsUpdate = void 0;
    this.worldFaceNormals = void 0;
    this.worldFaceNormalsNeedsUpdate = void 0;
    this.uniqueAxes = void 0;
    this.uniqueEdges = void 0;
    this.vertices = vertices;
    this.faces = faces;
    this.faceNormals = normals;

    if (this.faceNormals.length === 0) {
      this.computeNormals();
    }

    if (!boundingSphereRadius) {
      this.updateBoundingSphereRadius();
    } else {
      this.boundingSphereRadius = boundingSphereRadius;
    }

    this.worldVertices = []; // World transformed version of .vertices

    this.worldVerticesNeedsUpdate = true;
    this.worldFaceNormals = []; // World transformed version of .faceNormals

    this.worldFaceNormalsNeedsUpdate = true;
    this.uniqueAxes = axes ? axes.slice() : null;
    this.uniqueEdges = [];
    this.computeEdges();
  }
  /**
   * Computes uniqueEdges
   */


  computeEdges() {
    const faces = this.faces;
    const vertices = this.vertices;
    const edges = this.uniqueEdges;
    edges.length = 0;
    const edge = new Vec3();

    for (let i = 0; i !== faces.length; i++) {
      const face = faces[i];
      const 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 = false;

        for (let p = 0; p !== edges.length; p++) {
          if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)) {
            found = true;
            break;
          }
        }

        if (!found) {
          edges.push(edge.clone());
        }
      }
    }
  }
  /**
   * Compute the normals of the faces.
   * Will reuse existing Vec3 objects in the `faceNormals` array if they exist.
   */


  computeNormals() {
    this.faceNormals.length = this.faces.length; // Generate normals

    for (let i = 0; i < this.faces.length; i++) {
      // Check so all vertices exists for this face
      for (let j = 0; j < this.faces[i].length; j++) {
        if (!this.vertices[this.faces[i][j]]) {
          throw new Error("Vertex " + this.faces[i][j] + " not found!");
        }
      }

      const n = this.faceNormals[i] || new Vec3();
      this.getFaceNormal(i, n);
      n.negate(n);
      this.faceNormals[i] = n;
      const vertex = this.vertices[this.faces[i][0]];

      if (n.dot(vertex) < 0) {
        console.error(".faceNormals[" + i + "] = Vec3(" + n.toString() + ") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");

        for (let j = 0; j < this.faces[i].length; j++) {
          console.warn(".vertices[" + this.faces[i][j] + "] = Vec3(" + this.vertices[this.faces[i][j]].toString() + ")");
        }
      }
    }
  }
  /**
   * Compute the normal of a face from its vertices
   */


  getFaceNormal(i, target) {
    const f = this.faces[i];
    const va = this.vertices[f[0]];
    const vb = this.vertices[f[1]];
    const vc = this.vertices[f[2]];
    ConvexPolyhedron.computeNormal(va, vb, vc, target);
  }
  /**
   * Get face normal given 3 vertices
   */


  static computeNormal(va, vb, vc, target) {
    const cb = new Vec3();
    const ab = new Vec3();
    vb.vsub(va, ab);
    vc.vsub(vb, cb);
    cb.cross(ab, target);

    if (!target.isZero()) {
      target.normalize();
    }
  }
  /**
   * @param minDist Clamp distance
   * @param result The an array of contact point objects, see clipFaceAgainstHull
   */


  clipAgainstHull(posA, quatA, hullB, posB, quatB, separatingNormal, minDist, maxDist, result) {
    const WorldNormal = new Vec3();
    let closestFaceB = -1;
    let dmax = -Number.MAX_VALUE;

    for (let face = 0; face < hullB.faces.length; face++) {
      WorldNormal.copy(hullB.faceNormals[face]);
      quatB.vmult(WorldNormal, WorldNormal);
      const d = WorldNormal.dot(separatingNormal);

      if (d > dmax) {
        dmax = d;
        closestFaceB = face;
      }
    }

    const worldVertsB1 = [];

    for (let i = 0; i < hullB.faces[closestFaceB].length; i++) {
      const b = hullB.vertices[hullB.faces[closestFaceB][i]];
      const worldb = new Vec3();
      worldb.copy(b);
      quatB.vmult(worldb, worldb);
      posB.vadd(worldb, worldb);
      worldVertsB1.push(worldb);
    }

    if (closestFaceB >= 0) {
      this.clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result);
    }
  }
  /**
   * Find the separating axis between this hull and another
   * @param target The target vector to save the axis in
   * @return Returns false if a separation is found, else true
   */


  findSeparatingAxis(hullB, posA, quatA, posB, quatB, target, faceListA, faceListB) {
    const faceANormalWS3 = new Vec3();
    const Worldnormal1 = new Vec3();
    const deltaC = new Vec3();
    const worldEdge0 = new Vec3();
    const worldEdge1 = new Vec3();
    const Cross = new Vec3();
    let dmin = Number.MAX_VALUE;
    const hullA = this;

    if (!hullA.uniqueAxes) {
      const numFacesA = faceListA ? faceListA.length : hullA.faces.length; // Test face normals from hullA

      for (let i = 0; i < numFacesA; i++) {
        const fi = faceListA ? faceListA[i] : i; // Get world face normal

        faceANormalWS3.copy(hullA.faceNormals[fi]);
        quatA.vmult(faceANormalWS3, faceANormalWS3);
        const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);

        if (d === false) {
          return false;
        }

        if (d < dmin) {
          dmin = d;
          target.copy(faceANormalWS3);
        }
      }
    } else {
      // Test unique axes
      for (let i = 0; i !== hullA.uniqueAxes.length; i++) {
        // Get world axis
        quatA.vmult(hullA.uniqueAxes[i], faceANormalWS3);
        const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);

        if (d === false) {
          return false;
        }

        if (d < dmin) {
          dmin = d;
          target.copy(faceANormalWS3);
        }
      }
    }

    if (!hullB.uniqueAxes) {
      // Test face normals from hullB
      const numFacesB = faceListB ? faceListB.length : hullB.faces.length;

      for (let i = 0; i < numFacesB; i++) {
        const fi = faceListB ? faceListB[i] : i;
        Worldnormal1.copy(hullB.faceNormals[fi]);
        quatB.vmult(Worldnormal1, Worldnormal1);
        const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);

        if (d === false) {
          return false;
        }

        if (d < dmin) {
          dmin = d;
          target.copy(Worldnormal1);
        }
      }
    } else {
      // Test unique axes in B
      for (let i = 0; i !== hullB.uniqueAxes.length; i++) {
        quatB.vmult(hullB.uniqueAxes[i], Worldnormal1);
        const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);

        if (d === false) {
          return false;
        }

        if (d < dmin) {
          dmin = d;
          target.copy(Worldnormal1);
        }
      }
    } // Test edges


    for (let e0 = 0; e0 !== hullA.uniqueEdges.length; e0++) {
      // Get world edge
      quatA.vmult(hullA.uniqueEdges[e0], worldEdge0);

      for (let e1 = 0; e1 !== hullB.uniqueEdges.length; e1++) {
        // Get world edge 2
        quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
        worldEdge0.cross(worldEdge1, Cross);

        if (!Cross.almostZero()) {
          Cross.normalize();
          const dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);

          if (dist === false) {
            return false;
          }

          if (dist < dmin) {
            dmin = dist;
            target.copy(Cross);
          }
        }
      }
    }

    posB.vsub(posA, deltaC);

    if (deltaC.dot(target) > 0.0) {
      target.negate(target);
    }

    return true;
  }
  /**
   * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
   * @return The overlap depth, or FALSE if no penetration.
   */


  testSepAxis(axis, hullB, posA, quatA, posB, quatB) {
    const hullA = this;
    ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
    ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
    const maxA = maxminA[0];
    const minA = maxminA[1];
    const maxB = maxminB[0];
    const minB = maxminB[1];

    if (maxA < minB || maxB < minA) {
      return false; // Separated
    }

    const d0 = maxA - minB;
    const d1 = maxB - minA;
    const depth = d0 < d1 ? d0 : d1;
    return depth;
  }
  /**
   * calculateLocalInertia
   */


  calculateLocalInertia(mass, target) {
    // Approximate with box inertia
    // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
    const aabbmax = new Vec3();
    const aabbmin = new Vec3();
    this.computeLocalAABB(aabbmin, aabbmax);
    const x = aabbmax.x - aabbmin.x;
    const y = aabbmax.y - aabbmin.y;
    const z = aabbmax.z - aabbmin.z;
    target.x = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z);
    target.y = 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z);
    target.z = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x);
  }
  /**
   * @param face_i Index of the face
   */


  getPlaneConstantOfFace(face_i) {
    const f = this.faces[face_i];
    const n = this.faceNormals[face_i];
    const v = this.vertices[f[0]];
    const c = -n.dot(v);
    return c;
  }
  /**
   * Clip a face against a hull.
   * @param worldVertsB1 An array of Vec3 with vertices in the world frame.
   * @param minDist Distance clamping
   * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
   */


  clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result) {
    const faceANormalWS = new Vec3();
    const edge0 = new Vec3();
    const WorldEdge0 = new Vec3();
    const worldPlaneAnormal1 = new Vec3();
    const planeNormalWS1 = new Vec3();
    const worldA1 = new Vec3();
    const localPlaneNormal = new Vec3();
    const planeNormalWS = new Vec3();
    const hullA = this;
    const worldVertsB2 = [];
    const pVtxIn = worldVertsB1;
    const pVtxOut = worldVertsB2;
    let closestFaceA = -1;
    let dmin = Number.MAX_VALUE; // Find the face with normal closest to the separating axis

    for (let face = 0; face < hullA.faces.length; face++) {
      faceANormalWS.copy(hullA.faceNormals[face]);
      quatA.vmult(faceANormalWS, faceANormalWS);
      const d = faceANormalWS.dot(separatingNormal);

      if (d < dmin) {
        dmin = d;
        closestFaceA = face;
      }
    }

    if (closestFaceA < 0) {
      return;
    } // Get the face and construct connected faces


    const polyA = hullA.faces[closestFaceA];
    polyA.connectedFaces = [];

    for (let i = 0; i < hullA.faces.length; i++) {
      for (let j = 0; j < hullA.faces[i].length; j++) {
        if (
        /* Sharing a vertex*/
        polyA.indexOf(hullA.faces[i][j]) !== -1 &&
        /* Not the one we are looking for connections from */
        i !== closestFaceA &&
        /* Not already added */
        polyA.connectedFaces.indexOf(i) === -1) {
          polyA.connectedFaces.push(i);
        }
      }
    } // Clip the polygon to the back of the planes of all faces of hull A,
    // that are adjacent to the witness face


    const numVerticesA = polyA.length;

    for (let i = 0; i < numVerticesA; i++) {
      const a = hullA.vertices[polyA[i]];
      const b = hullA.vertices[polyA[(i + 1) % numVerticesA]];
      a.vsub(b, edge0);
      WorldEdge0.copy(edge0);
      quatA.vmult(WorldEdge0, WorldEdge0);
      posA.vadd(WorldEdge0, WorldEdge0);
      worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);
      quatA.vmult(worldPlaneAnormal1, worldPlaneAnormal1);
      posA.vadd(worldPlaneAnormal1, worldPlaneAnormal1);
      WorldEdge0.cross(worldPlaneAnormal1, planeNormalWS1);
      planeNormalWS1.negate(planeNormalWS1);
      worldA1.copy(a);
      quatA.vmult(worldA1, worldA1);
      posA.vadd(worldA1, worldA1);
      const otherFace = polyA.connectedFaces[i];
      localPlaneNormal.copy(this.faceNormals[otherFace]);
      const localPlaneEq = this.getPlaneConstantOfFace(otherFace);
      planeNormalWS.copy(localPlaneNormal);
      quatA.vmult(planeNormalWS, planeNormalWS);
      const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); // Clip face against our constructed plane

      this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS); // Throw away all clipped points, but save the remaining until next clip

      while (pVtxIn.length) {
        pVtxIn.shift();
      }

      while (pVtxOut.length) {
        pVtxIn.push(pVtxOut.shift());
      }
    } // only keep contact points that are behind the witness face


    localPlaneNormal.copy(this.faceNormals[closestFaceA]);
    const localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
    planeNormalWS.copy(localPlaneNormal);
    quatA.vmult(planeNormalWS, planeNormalWS);
    const planeEqWS = localPlaneEq - planeNormalWS.dot(posA);

    for (let i = 0; i < pVtxIn.length; i++) {
      let depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; // ???

      if (depth <= minDist) {
        console.log("clamped: depth=" + depth + " to minDist=" + minDist);
        depth = minDist;
      }

      if (depth <= maxDist) {
        const point = pVtxIn[i];

        if (depth <= 1e-6) {
          const p = {
            point,
            normal: planeNormalWS,
            depth
          };
          result.push(p);
        }
      }
    }
  }
  /**
   * Clip a face in a hull against the back of a plane.
   * @param planeConstant The constant in the mathematical plane equation
   */


  clipFaceAgainstPlane(inVertices, outVertices, planeNormal, planeConstant) {
    let n_dot_first;
    let n_dot_last;
    const numVerts = inVertices.length;

    if (numVerts < 2) {
      return outVertices;
    }

    let firstVertex = inVertices[inVertices.length - 1];
    let lastVertex = inVertices[0];
    n_dot_first = planeNormal.dot(firstVertex) + planeConstant;

    for (let vi = 0; vi < numVerts; vi++) {
      lastVertex = inVertices[vi];
      n_dot_last = planeNormal.dot(lastVertex) + planeConstant;

      if (n_dot_first < 0) {
        if (n_dot_last < 0) {
          // Start < 0, end < 0, so output lastVertex
          const newv = new Vec3();
          newv.copy(lastVertex);
          outVertices.push(newv);
        } else {
          // Start < 0, end >= 0, so output intersection
          const newv = new Vec3();
          firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
          outVertices.push(newv);
        }
      } else {
        if (n_dot_last < 0) {
          // Start >= 0, end < 0 so output intersection and end
          const newv = new Vec3();
          firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
          outVertices.push(newv);
          outVertices.push(lastVertex);
        }
      }

      firstVertex = lastVertex;
      n_dot_first = n_dot_last;
    }

    return outVertices;
  }
  /**
   * Updates `.worldVertices` and sets `.worldVerticesNeedsUpdate` to false.
   */


  computeWorldVertices(position, quat) {
    while (this.worldVertices.length < this.vertices.length) {
      this.worldVertices.push(new Vec3());
    }

    const verts = this.vertices;
    const worldVerts = this.worldVertices;

    for (let i = 0; i !== this.vertices.length; i++) {
      quat.vmult(verts[i], worldVerts[i]);
      position.vadd(worldVerts[i], worldVerts[i]);
    }

    this.worldVerticesNeedsUpdate = false;
  }

  computeLocalAABB(aabbmin, aabbmax) {
    const vertices = this.vertices;
    aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);

    for (let i = 0; i < this.vertices.length; i++) {
      const v = vertices[i];

      if (v.x < aabbmin.x) {
        aabbmin.x = v.x;
      } else if (v.x > aabbmax.x) {
        aabbmax.x = v.x;
      }

      if (v.y < aabbmin.y) {
        aabbmin.y = v.y;
      } else if (v.y > aabbmax.y) {
        aabbmax.y = v.y;
      }

      if (v.z < aabbmin.z) {
        aabbmin.z = v.z;
      } else if (v.z > aabbmax.z) {
        aabbmax.z = v.z;
      }
    }
  }
  /**
   * Updates `worldVertices` and sets `worldVerticesNeedsUpdate` to false.
   */


  computeWorldFaceNormals(quat) {
    const N = this.faceNormals.length;

    while (this.worldFaceNormals.length < N) {
      this.worldFaceNormals.push(new Vec3());
    }

    const normals = this.faceNormals;
    const worldNormals = this.worldFaceNormals;

    for (let i = 0; i !== N; i++) {
      quat.vmult(normals[i], worldNormals[i]);
    }

    this.worldFaceNormalsNeedsUpdate = false;
  }
  /**
   * updateBoundingSphereRadius
   */


  updateBoundingSphereRadius() {
    // Assume points are distributed with local (0,0,0) as center
    let max2 = 0;
    const verts = this.vertices;

    for (let i = 0; i !== verts.length; i++) {
      const norm2 = verts[i].lengthSquared();

      if (norm2 > max2) {
        max2 = norm2;
      }
    }

    this.boundingSphereRadius = Math.sqrt(max2);
  }
  /**
   * calculateWorldAABB
   */


  calculateWorldAABB(pos, quat, min, max) {
    const verts = this.vertices;
    let minx;
    let miny;
    let minz;
    let maxx;
    let maxy;
    let maxz;
    let tempWorldVertex = new Vec3();

    for (let i = 0; i < verts.length; i++) {
      tempWorldVertex.copy(verts[i]);
      quat.vmult(tempWorldVertex, tempWorldVertex);
      pos.vadd(tempWorldVertex, tempWorldVertex);
      const v = tempWorldVertex;

      if (minx === undefined || v.x < minx) {
        minx = v.x;
      }

      if (maxx === undefined || v.x > maxx) {
        maxx = v.x;
      }

      if (miny === undefined || v.y < miny) {
        miny = v.y;
      }

      if (maxy === undefined || v.y > maxy) {
        maxy = v.y;
      }

      if (minz === undefined || v.z < minz) {
        minz = v.z;
      }

      if (maxz === undefined || v.z > maxz) {
        maxz = v.z;
      }
    }

    min.set(minx, miny, minz);
    max.set(maxx, maxy, maxz);
  }
  /**
   * Get approximate convex volume
   */


  volume() {
    return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  }
  /**
   * Get an average of all the vertices positions
   */


  getAveragePointLocal(target = new Vec3()) {
    const verts = this.vertices;

    for (let i = 0; i < verts.length; i++) {
      target.vadd(verts[i], target);
    }

    target.scale(1 / verts.length, target);
    return target;
  }
  /**
   * Transform all local points. Will change the .vertices
   */


  transformAllPoints(offset, quat) {
    const n = this.vertices.length;
    const verts = this.vertices; // Apply rotation

    if (quat) {
      // Rotate vertices
      for (let i = 0; i < n; i++) {
        const v = verts[i];
        quat.vmult(v, v);
      } // Rotate face normals


      for (let i = 0; i < this.faceNormals.length; i++) {
        const v = this.faceNormals[i];
        quat.vmult(v, v);
      }
      /*
            // Rotate edges
            for(let i=0; i<this.uniqueEdges.length; i++){
                const v = this.uniqueEdges[i];
                quat.vmult(v,v);
            }*/

    } // Apply offset


    if (offset) {
      for (let i = 0; i < n; i++) {
        const v = verts[i];
        v.vadd(offset, v);
      }
    }
  }
  /**
   * Checks whether p is inside the polyhedra. Must be in local coords.
   * The point lies outside of the convex hull of the other points if and only if the direction
   * of all the vectors from it to those other points are on less than one half of a sphere around it.
   * @param p A point given in local coordinates
   */


  pointIsInside(p) {
    const verts = this.vertices;
    const faces = this.faces;
    const normals = this.faceNormals;
    const pointInside = new Vec3();
    this.getAveragePointLocal(pointInside);

    for (let i = 0; i < this.faces.length; i++) {
      let n = normals[i];
      const v = verts[faces[i][0]]; // We only need one point in the face
      // This dot product determines which side of the edge the point is

      const vToP = new Vec3();
      p.vsub(v, vToP);
      const r1 = n.dot(vToP);
      const vToPointInside = new Vec3();
      pointInside.vsub(v, vToPointInside);
      const r2 = n.dot(vToPointInside);

      if (r1 < 0 && r2 > 0 || r1 > 0 && r2 < 0) {
        return false; // Encountered some other sign. Exit.
      }
    } // If we got here, all dot products were of the same sign.


    return -1;
  }
  /**
   * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis.
   * Results are saved in the array maxmin.
   * @param result result[0] and result[1] will be set to maximum and minimum, respectively.
   */


  static project(shape, axis, pos, quat, result) {
    const n = shape.vertices.length;
    const localAxis = project_localAxis;
    let max = 0;
    let min = 0;
    const localOrigin = project_localOrigin;
    const vs = shape.vertices;
    localOrigin.setZero(); // Transform the axis to local

    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; i < n; i++) {
      const val = vs[i].dot(localAxis);

      if (val > max) {
        max = val;
      }

      if (val < min) {
        min = val;
      }
    }

    min -= add;
    max -= add;

    if (min > max) {
      // Inconsistent - swap
      const temp = min;
      min = max;
      max = temp;
    } // Output


    result[0] = max;
    result[1] = min;
  }

}
const maxminA = [];
const maxminB = [];
const project_localAxis = new Vec3();
const project_localOrigin = new Vec3();

/**
 * A 3d box shape.
 * @example
 *     const size = 1
 *     const halfExtents = new CANNON.Vec3(size, size, size)
 *     const boxShape = new CANNON.Box(halfExtents)
 *     const boxBody = new CANNON.Body({ mass: 1, shape: boxShape })
 *     world.addBody(boxBody)
 */
class Box extends Shape {
  /**
   * The half extents of the box.
   */

  /**
   * Used by the contact generator to make contacts with other convex polyhedra for example.
   */
  constructor(halfExtents) {
    super({
      type: Shape.types.BOX
    });
    this.halfExtents = void 0;
    this.convexPolyhedronRepresentation = void 0;
    this.halfExtents = halfExtents;
    this.convexPolyhedronRepresentation = null;
    this.updateConvexPolyhedronRepresentation();
    this.updateBoundingSphereRadius();
  }
  /**
   * Updates the local convex polyhedron representation used for some collisions.
   */


  updateConvexPolyhedronRepresentation() {
    const sx = this.halfExtents.x;
    const sy = this.halfExtents.y;
    const sz = this.halfExtents.z;
    const V = Vec3;
    const 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)];
    const faces = [[3, 2, 1, 0], // -z
    [4, 5, 6, 7], // +z
    [5, 4, 0, 1], // -y
    [2, 3, 7, 6], // +y
    [0, 4, 7, 3], // -x
    [1, 2, 6, 5] // +x
    ];
    const axes = [new V(0, 0, 1), new V(0, 1, 0), new V(1, 0, 0)];
    const h = new ConvexPolyhedron({
      vertices,
      faces,
      axes
    });
    this.convexPolyhedronRepresentation = h;
    h.material = this.material;
  }
  /**
   * Calculate the inertia of the box.
   */


  calculateLocalInertia(mass, target = new Vec3()) {
    Box.calculateInertia(this.halfExtents, mass, target);
    return target;
  }

  static calculateInertia(halfExtents, mass, target) {
    const e = halfExtents;
    target.x = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.z * 2 * e.z);
    target.y = 1.0 / 12.0 * mass * (2 * e.x * 2 * e.x + 2 * e.z * 2 * e.z);
    target.z = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.x * 2 * e.x);
  }
  /**
   * Get the box 6 side normals
   * @param sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
   * @param quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
   */


  getSideNormals(sixTargetVectors, quat) {
    const sides = sixTargetVectors;
    const ex = this.halfExtents;
    sides[0].set(ex.x, 0, 0);
    sides[1].set(0, ex.y, 0);
    sides[2].set(0, 0, ex.z);
    sides[3].set(-ex.x, 0, 0);
    sides[4].set(0, -ex.y, 0);
    sides[5].set(0, 0, -ex.z);

    if (quat !== undefined) {
      for (let i = 0; i !== sides.length; i++) {
        quat.vmult(sides[i], sides[i]);
      }
    }

    return sides;
  }
  /**
   * Returns the volume of the box.
   */


  volume() {
    return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  }
  /**
   * updateBoundingSphereRadius
   */


  updateBoundingSphereRadius() {
    this.boundingSphereRadius = this.halfExtents.length();
  }
  /**
   * forEachWorldCorner
   */


  forEachWorldCorner(pos, quat, callback) {
    const e = this.halfExtents;
    const 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; i < corners.length; i++) {
      worldCornerTempPos.set(corners[i][0], corners[i][1], corners[i][2]);
      quat.vmult(worldCornerTempPos, worldCornerTempPos);
      pos.vadd(worldCornerTempPos, worldCornerTempPos);
      callback(worldCornerTempPos.x, worldCornerTempPos.y, worldCornerTempPos.z);
    }
  }
  /**
   * calculateWorldAABB
   */


  calculateWorldAABB(pos, quat, min, max) {
    const e = this.halfExtents;
    worldCornersTemp[0].set(e.x, e.y, e.z);
    worldCornersTemp[1].set(-e.x, e.y, e.z);
    worldCornersTemp[2].set(-e.x, -e.y, e.z);
    worldCornersTemp[3].set(-e.x, -e.y, -e.z);
    worldCornersTemp[4].set(e.x, -e.y, -e.z);
    worldCornersTemp[5].set(e.x, e.y, -e.z);
    worldCornersTemp[6].set(-e.x, e.y, -e.z);
    worldCornersTemp[7].set(e.x, -e.y, e.z);
    const wc = worldCornersTemp[0];
    quat.vmult(wc, wc);
    pos.vadd(wc, wc);
    max.copy(wc);
    min.copy(wc);

    for (let i = 1; i < 8; i++) {
      const wc = worldCornersTemp[i];
      quat.vmult(wc, wc);
      pos.vadd(wc, wc);
      const x = wc.x;
      const y = wc.y;
      const z = wc.z;

      if (x > max.x) {
        max.x = x;
      }

      if (y > max.y) {
        max.y = y;
      }

      if (z > max.z) {
        max.z = z;
      }

      if (x < min.x) {
        min.x = x;
      }

      if (y < min.y) {
        min.y = y;
      }

      if (z < min.z) {
        min.z = z;
      }
    } // Get each axis max
    // min.set(Infinity,Infinity,Infinity);
    // max.set(-Infinity,-Infinity,-Infinity);
    // this.forEachWorldCorner(pos,quat,function(x,y,z){
    //     if(x > max.x){
    //         max.x = x;
    //     }
    //     if(y > max.y){
    //         max.y = y;
    //     }
    //     if(z > max.z){
    //         max.z = z;
    //     }
    //     if(x < min.x){
    //         min.x = x;
    //     }
    //     if(y < min.y){
    //         min.y = y;
    //     }
    //     if(z < min.z){
    //         min.z = z;
    //     }
    // });

  }

}
const worldCornerTempPos = new Vec3();
const worldCornersTemp = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];

/**
 * BODY_TYPES
 */
const BODY_TYPES = {
  /** DYNAMIC */
  DYNAMIC: 1,

  /** STATIC */
  STATIC: 2,

  /** KINEMATIC */
  KINEMATIC: 4
};
/**
 * BodyType
 */

/**
 * BODY_SLEEP_STATES
 */
const BODY_SLEEP_STATES = {
  /** AWAKE */
  AWAKE: 0,

  /** SLEEPY */
  SLEEPY: 1,

  /** SLEEPING */
  SLEEPING: 2
};
/**
 * BodySleepState
 */

/**
 * Base class for all body types.
 * @example
 *     const shape = new CANNON.Sphere(1)
 *     const body = new CANNON.Body({
 *       mass: 1,
 *       shape,
 *     })
 *     world.addBody(body)
 */
class Body extends EventTarget {
  /**
   * Dispatched after two bodies collide. This event is dispatched on each
   * of the two bodies involved in the collision.
   * @event collide
   * @param body The body that was involved in the collision.
   * @param contact The details of the collision.
   */

  /**
   * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
   */

  /**
   * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
   */

  /**
   * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
   */

  /**
   * AWAKE
   */

  /**
   * SLEEPY
   */

  /**
   * SLEEPING
   */

  /**
   * Dispatched after a sleeping body has woken up.
   * @event wakeup
   */

  /**
   * Dispatched after a body has gone in to the sleepy state.
   * @event sleepy
   */

  /**
   * Dispatched after a body has fallen asleep.
   * @event sleep
   */

  /**
   * Identifier of the body.
   */

  /**
   * Position of body in World.bodies. Updated by World and used in ArrayCollisionMatrix.
   */

  /**
   * Reference to the world the body is living in.
   */

  /**
   * Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object. Deprecated - use World events instead.
   * @deprecated Use World events instead
   */

  /**
   * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object. Deprecated - use World events instead.
   * @deprecated Use World events instead
   */

  /**
   * The collision group the body belongs to.
   * @default 1
   */

  /**
   * The collision group the body can collide with.
   * @default -1
   */

  /**
   * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled - i.e. "collide" events will be raised, but forces will not be altered.
   */

  /**
   * World space position of the body.
   */

  /**
   * Interpolated position of the body.
   */

  /**
   * Initial position of the body.
   */

  /**
   * World space velocity of the body.
   */

  /**
   * Initial velocity of the body.
   */

  /**
   * Linear force on the body in world space.
   */

  /**
   * The mass of the body.
   * @default 0
   */

  /**
   * The physics material of the body. It defines the body interaction with other bodies.
   */

  /**
   * How much to damp the body velocity each step. It can go from 0 to 1.
   * @default 0.01
   */

  /**
   * One of: `Body.DYNAMIC`, `Body.STATIC` and `Body.KINEMATIC`.
   */

  /**
   * If true, the body will automatically fall to sleep.
   * @default true
   */

  /**
   * Current sleep state.
   */

  /**
   * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
   * @default 0.1
   */

  /**
   * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
   * @default 1
   */

  /**
   * World space rotational force on the body, around center of mass.
   */

  /**
   * World space orientation of the body.
   */

  /**
   * Initial quaternion of the body.
   */

  /**
   * Interpolated orientation of the body.
   */

  /**
   * Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates.
   */

  /**
   * Initial angular velocity of the body.
   */

  /**
   * List of Shapes that have been added to the body.
   */

  /**
   * Position of each Shape in the body, given in local Body space.
   */

  /**
   * Orientation of each Shape, given in local Body space.
   */

  /**
   * The inertia of the body.
   */

  /**
   * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() if you change this after the body creation.
   * @default false
   */

  /**
   * How much to damp the body angular velocity each step. It can go from 0 to 1.
   * @default 0.01
   */

  /**
   * Use this property to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none.
   */

  /**
   * Use this property to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none.
   */

  /**
   * World space bounding box of the body and its shapes.
   */

  /**
   * Indicates if the AABB needs to be updated before use.
   */

  /**
   * Total bounding radius of the Body including its shapes, relative to body.position.
   */

  /**
   * When true the body behaves like a trigger. It does not collide
   * with other bodies but collision events are still triggered.
   * @default false
   */
  constructor(options = {}) {
    super();
    this.id = void 0;
    this.index = void 0;
    this.world = void 0;
    this.preStep = void 0;
    this.postStep = void 0;
    this.vlambda = void 0;
    this.collisionFilterGroup = void 0;
    this.collisionFilterMask = void 0;
    this.collisionResponse = void 0;
    this.position = void 0;
    this.previousPosition = void 0;
    this.interpolatedPosition = void 0;
    this.initPosition = void 0;
    this.velocity = void 0;
    this.initVelocity = void 0;
    this.force = void 0;
    this.mass = void 0;
    this.invMass = void 0;
    this.material = void 0;
    this.linearDamping = void 0;
    this.type = void 0;
    this.allowSleep = void 0;
    this.sleepState = void 0;
    this.sleepSpeedLimit = void 0;
    this.sleepTimeLimit = void 0;
    this.timeLastSleepy = void 0;
    this.wakeUpAfterNarrowphase = void 0;
    this.torque = void 0;
    this.quaternion = void 0;
    this.initQuaternion = void 0;
    this.previousQuaternion = void 0;
    this.interpolatedQuaternion = void 0;
    this.angularVelocity = void 0;
    this.initAngularVelocity = void 0;
    this.shapes = void 0;
    this.shapeOffsets = void 0;
    this.shapeOrientations = void 0;
    this.inertia = void 0;
    this.invInertia = void 0;
    this.invInertiaWorld = void 0;
    this.invMassSolve = void 0;
    this.invInertiaSolve = void 0;
    this.invInertiaWorldSolve = void 0;
    this.fixedRotation = void 0;
    this.angularDamping = void 0;
    this.linearFactor = void 0;
    this.angularFactor = void 0;
    this.aabb = void 0;
    this.aabbNeedsUpdate = void 0;
    this.boundingRadius = void 0;
    this.wlambda = void 0;
    this.isTrigger = void 0;
    this.id = Body.idCounter++;
    this.index = -1;
    this.world = null;
    this.preStep = null;
    this.postStep = null;
    this.vlambda = new Vec3();
    this.collisionFilterGroup = typeof options.collisionFilterGroup === 'number' ? options.collisionFilterGroup : 1;
    this.collisionFilterMask = typeof options.collisionFilterMask === 'number' ? options.collisionFilterMask : -1;
    this.collisionResponse = typeof options.collisionResponse === 'boolean' ? options.collisionResponse : true;
    this.position = new Vec3();
    this.previousPosition = new Vec3();
    this.interpolatedPosition = new Vec3();
    this.initPosition = new Vec3();

    if (options.position) {
      this.position.copy(options.position);
      this.previousPosition.copy(options.position);
      this.interpolatedPosition.copy(options.position);
      this.initPosition.copy(options.position);
    }

    this.velocity = new Vec3();

    if (options.velocity) {
      this.velocity.copy(options.velocity);
    }

    this.initVelocity = new Vec3();
    this.force = new Vec3();
    const mass = typeof options.mass === 'number' ? options.mass : 0;
    this.mass = mass;
    this.invMass = mass > 0 ? 1.0 / mass : 0;
    this.material = options.material || null;
    this.linearDamping = typeof options.linearDamping === 'number' ? options.linearDamping : 0.01;
    this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC;

    if (typeof options.type === typeof Body.STATIC) {
      this.type = options.type;
    }

    this.allowSleep = typeof options.allowSleep !== 'undefined' ? options.allowSleep : true;
    this.sleepState = Body.AWAKE;
    this.sleepSpeedLimit = typeof options.sleepSpeedLimit !== 'undefined' ? options.sleepSpeedLimit : 0.1;
    this.sleepTimeLimit = typeof options.sleepTimeLimit !== 'undefined' ? options.sleepTimeLimit : 1;
    this.timeLastSleepy = 0;
    this.wakeUpAfterNarrowphase = false;
    this.torque = new Vec3();
    this.quaternion = new Quaternion();
    this.initQuaternion = new Quaternion();
    this.previousQuaternion = new Quaternion();
    this.interpolatedQuaternion = new Quaternion();

    if (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();

    if (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 = typeof options.fixedRotation !== 'undefined' ? options.fixedRotation : false;
    this.angularDamping = typeof options.angularDamping !== 'undefined' ? options.angularDamping : 0.01;
    this.linearFactor = new Vec3(1, 1, 1);

    if (options.linearFactor) {
      this.linearFactor.copy(options.linearFactor);
    }

    this.angularFactor = new Vec3(1, 1, 1);

    if (options.angularFactor) {
      this.angularFactor.copy(options.angularFactor);
    }

    this.aabb = new AABB();
    this.aabbNeedsUpdate = true;
    this.boundingRadius = 0;
    this.wlambda = new Vec3();
    this.isTrigger = Boolean(options.isTrigger);

    if (options.shape) {
      this.addShape(options.shape);
    }

    this.updateMassProperties();
  }
  /**
   * Wake the body up.
   */


  wakeUp() {
    const prevState = this.sleepState;
    this.sleepState = Body.AWAKE;
    this.wakeUpAfterNarrowphase = false;

    if (prevState === Body.SLEEPING) {
      this.dispatchEvent(Body.wakeupEvent);
    }
  }
  /**
   * Force body sleep
   */


  sleep() {
    this.sleepState = Body.SLEEPING;
    this.velocity.set(0, 0, 0);
    this.angularVelocity.set(0, 0, 0);
    this.wakeUpAfterNarrowphase = false;
  }
  /**
   * Called every timestep to update internal sleep timer and change sleep state if needed.
   * @param time The world time in seconds
   */


  sleepTick(time) {
    if (this.allowSleep) {
      const sleepState = this.sleepState;
      const speedSquared = this.velocity.lengthSquared() + this.angularVelocity.lengthSquared();
      const speedLimitSquared = this.sleepSpeedLimit ** 2;

      if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) {
        this.sleepState = Body.SLEEPY; // Sleepy

        this.timeLastSleepy = time;
        this.dispatchEvent(Body.sleepyEvent);
      } else if (sleepState === Body.SLEEPY && speedSquared > speedLimitSquared) {
        this.wakeUp(); // Wake up
      } else if (sleepState === Body.SLEEPY && time - this.timeLastSleepy > this.sleepTimeLimit) {
        this.sleep(); // Sleeping

        this.dispatchEvent(Body.sleepEvent);
      }
    }
  }
  /**
   * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
   */


  updateSolveMassProperties() {
    if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) {
      this.invMassSolve = 0;
      this.invInertiaSolve.setZero();
      this.invInertiaWorldSolve.setZero();
    } else {
      this.invMassSolve = this.invMass;
      this.invInertiaSolve.copy(this.invInertia);
      this.invInertiaWorldSolve.copy(this.invInertiaWorld);
    }
  }
  /**
   * Convert a world point to local body frame.
   */


  pointToLocalFrame(worldPoint, result = new Vec3()) {
    worldPoint.vsub(this.position, result);
    this.quaternion.conjugate().vmult(result, result);
    return result;
  }
  /**
   * Convert a world vector to local body frame.
   */


  vectorToLocalFrame(worldVector, result = new Vec3()) {
    this.quaternion.conjugate().vmult(worldVector, result);
    return result;
  }
  /**
   * Convert a local body point to world frame.
   */


  pointToWorldFrame(localPoint, result = new Vec3()) {
    this.quaternion.vmult(localPoint, result);
    result.vadd(this.position, result);
    return result;
  }
  /**
   * Convert a local body point to world frame.
   */


  vectorToWorldFrame(localVector, result = new Vec3()) {
    this.quaternion.vmult(localVector, result);
    return result;
  }
  /**
   * Add a shape to the body with a local offset and orientation.
   * @return The body object, for chainability.
   */


  addShape(shape, _offset, _orientation) {
    const offset = new Vec3();
    const orientation = new Quaternion();

    if (_offset) {
      offset.copy(_offset);
    }

    if (_orientation) {
      orientation.copy(_orientation);
    }

    this.shapes.push(shape);
    this.shapeOffsets.push(offset);
    this.shapeOrientations.push(orientation);
    this.updateMassProperties();
    this.updateBoundingRadius();
    this.aabbNeedsUpdate = true;
    shape.body = this;
    return this;
  }
  /**
   * Remove a shape from the body.
   * @return The body object, for chainability.
   */


  removeShape(shape) {
    const index = this.shapes.indexOf(shape);

    if (index === -1) {
      console.warn('Shape does not belong to the body');
      return this;
    }

    this.shapes.splice(index, 1);
    this.shapeOffsets.splice(index, 1);
    this.shapeOrientations.splice(index, 1);
    this.updateMassProperties();
    this.updateBoundingRadius();
    this.aabbNeedsUpdate = true;
    shape.body = null;
    return this;
  }
  /**
   * Update the bounding radius of the body. Should be done if any of the shapes are changed.
   */


  updateBoundingRadius() {
    const shapes = this.shapes;
    const shapeOffsets = this.shapeOffsets;
    const N = shapes.length;
    let radius = 0;

    for (let i = 0; i !== N; i++) {
      const shape = shapes[i];
      shape.updateBoundingSphereRadius();
      const offset = shapeOffsets[i].length();
      const r = shape.boundingSphereRadius;

      if (offset + r > radius) {
        radius = offset + r;
      }
    }

    this.boundingRadius = radius;
  }
  /**
   * Updates the .aabb
   */


  updateAABB() {
    const shapes = this.shapes;
    const shapeOffsets = this.shapeOffsets;
    const shapeOrientations = this.shapeOrientations;
    const N = shapes.length;
    const offset = tmpVec;
    const orientation = tmpQuat;
    const bodyQuat = this.quaternion;
    const aabb = this.aabb;
    const shapeAABB = updateAABB_shapeAABB;

    for (let i = 0; i !== N; i++) {
      const shape = shapes[i]; // Get shape world position

      bodyQuat.vmult(shapeOffsets[i], offset);
      offset.vadd(this.position, offset); // Get shape world quaternion

      bodyQuat.mult(shapeOrientations[i], orientation); // Get shape AABB

      shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);

      if (i === 0) {
        aabb.copy(shapeAABB);
      } else {
        aabb.extend(shapeAABB);
      }
    }

    this.aabbNeedsUpdate = false;
  }
  /**
   * Update `.inertiaWorld` and `.invInertiaWorld`
   */


  updateInertiaWorld(force) {
    const I = this.invInertia;

    if (I.x === I.y && I.y === I.z && !force) ; else {
      const m1 = uiw_m1;
      const m2 = uiw_m2;
      m1.setRotationFromQuaternion(this.quaternion);
      m1.transpose(m2);
      m1.scale(I, m1);
      m1.mmult(m2, this.invInertiaWorld);
    }
  }
  /**
   * Apply force to a point of the body. This could for example be a point on the Body surface.
   * Applying force this way will add to Body.force and Body.torque.
   * @param force The amount of force to add.
   * @param relativePoint A point relative to the center of mass to apply the force on.
   */


  applyForce(force, relativePoint = new Vec3()) {
    // Needed?
    if (this.type !== Body.DYNAMIC) {
      return;
    }

    if (this.sleepState === Body.SLEEPING) {
      this.wakeUp();
    } // Compute produced rotational force


    const rotForce = Body_applyForce_rotForce;
    relativePoint.cross(force, rotForce); // Add linear force

    this.force.vadd(force, this.force); // Add rotational force

    this.torque.vadd(rotForce, this.torque);
  }
  /**
   * Apply force to a local point in the body.
   * @param force The force vector to apply, defined locally in the body frame.
   * @param localPoint A local point in the body to apply the force on.
   */


  applyLocalForce(localForce, localPoint = new Vec3()) {
    if (this.type !== Body.DYNAMIC) {
      return;
    }

    const worldForce = Body_applyLocalForce_worldForce;
    const relativePointWorld = Body_applyLocalForce_relativePointWorld; // Transform the force vector to world space

    this.vectorToWorldFrame(localForce, worldForce);
    this.vectorToWorldFrame(localPoint, relativePointWorld);
    this.applyForce(worldForce, relativePointWorld);
  }
  /**
   * Apply torque to the body.
   * @param torque The amount of torque to add.
   */


  applyTorque(torque) {
    if (this.type !== Body.DYNAMIC) {
      return;
    }

    if (this.sleepState === Body.SLEEPING) {
      this.wakeUp();
    } // Add rotational force


    this.torque.vadd(torque, this.torque);
  }
  /**
   * Apply impulse to a point of the body. This could for example be a point on the Body surface.
   * An impulse is a force added to a body during a short period of time (impulse = force * time).
   * Impulses will be added to Body.velocity and Body.angularVelocity.
   * @param impulse The amount of impulse to add.
   * @param relativePoint A point relative to the center of mass to apply the force on.
   */


  applyImpulse(impulse, relativePoint = new Vec3()) {
    if (this.type !== Body.DYNAMIC) {
      return;
    }

    if (this.sleepState === Body.SLEEPING) {
      this.wakeUp();
    } // Compute point position relative to the body center


    const r = relativePoint; // Compute produced central impulse velocity

    const velo = Body_applyImpulse_velo;
    velo.copy(impulse);
    velo.scale(this.invMass, velo); // Add linear impulse

    this.velocity.vadd(velo, this.velocity); // Compute produced rotational impulse velocity

    const rotVelo = Body_applyImpulse_rotVelo;
    r.cross(impulse, rotVelo);
    /*
     rotVelo.x *= this.invInertia.x;
     rotVelo.y *= this.invInertia.y;
     rotVelo.z *= this.invInertia.z;
     */

    this.invInertiaWorld.vmult(rotVelo, rotVelo); // Add rotational Impulse

    this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  }
  /**
   * Apply locally-defined impulse to a local point in the body.
   * @param force The force vector to apply, defined locally in the body frame.
   * @param localPoint A local point in the body to apply the force on.
   */


  applyLocalImpulse(localImpulse, localPoint = new Vec3()) {
    if (this.type !== Body.DYNAMIC) {
      return;
    }

    const worldImpulse = Body_applyLocalImpulse_worldImpulse;
    const relativePointWorld = Body_applyLocalImpulse_relativePoint; // Transform the force vector to world space

    this.vectorToWorldFrame(localImpulse, worldImpulse);
    this.vectorToWorldFrame(localPoint, relativePointWorld);
    this.applyImpulse(worldImpulse, relativePointWorld);
  }
  /**
   * Should be called whenever you change the body shape or mass.
   */


  updateMassProperties() {
    const halfExtents = Body_updateMassProperties_halfExtents;
    this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
    const I = this.inertia;
    const fixed = this.fixedRotation; // Approximate with AABB box

    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.0 / I.x : 0, I.y > 0 && !fixed ? 1.0 / I.y : 0, I.z > 0 && !fixed ? 1.0 / I.z : 0);
    this.updateInertiaWorld(true);
  }
  /**
   * Get world velocity of a point in the body.
   * @param worldPoint
   * @param result
   * @return The result vector.
   */


  getVelocityAtWorldPoint(worldPoint, result) {
    const r = new Vec3();
    worldPoint.vsub(this.position, r);
    this.angularVelocity.cross(r, result);
    this.velocity.vadd(result, result);
    return result;
  }
  /**
   * Move the body forward in time.
   * @param dt Time step
   * @param quatNormalize Set to true to normalize the body quaternion
   * @param quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization
   */


  integrate(dt, quatNormalize, quatNormalizeFast) {
    // Save previous position
    this.previousPosition.copy(this.position);
    this.previousQuaternion.copy(this.quaternion);

    if (!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING) {
      // Only for dynamic
      return;
    }

    const velo = this.velocity;
    const angularVelo = this.angularVelocity;
    const pos = this.position;
    const force = this.force;
    const torque = this.torque;
    const quat = this.quaternion;
    const invMass = this.invMass;
    const invInertia = this.invInertiaWorld;
    const linearFactor = this.linearFactor;
    const 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;
    const angularFactor = this.angularFactor;
    const tx = torque.x * angularFactor.x;
    const ty = torque.y * angularFactor.y;
    const 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); // Use new velocity  - leap frog

    pos.x += velo.x * dt;
    pos.y += velo.y * dt;
    pos.z += velo.z * dt;
    quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);

    if (quatNormalize) {
      if (quatNormalizeFast) {
        quat.normalizeFast();
      } else {
        quat.normalize();
      }
    }

    this.aabbNeedsUpdate = true; // Update world inertia

    this.updateInertiaWorld();
  }

}
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();
const tmpQuat = new Quaternion();
const updateAABB_shapeAABB = new AABB();
const uiw_m1 = new Mat3();
const uiw_m2 = new Mat3();
const Body_applyForce_rotForce = new Vec3();
const Body_applyLocalForce_worldForce = new Vec3();
const Body_applyLocalForce_relativePointWorld = new Vec3();
const Body_applyImpulse_velo = new Vec3();
const Body_applyImpulse_rotVelo = new Vec3();
const Body_applyLocalImpulse_worldImpulse = new Vec3();
const Body_applyLocalImpulse_relativePoint = new Vec3();
const Body_updateMassProperties_halfExtents = new Vec3();

/**
 * Base class for broadphase implementations
 * @author schteppe
 */
class Broadphase {
  /**
   * The world to search for collisions in.
   */

  /**
   * If set to true, the broadphase uses bounding boxes for intersection tests, else it uses bounding spheres.
   */

  /**
   * Set to true if the objects in the world moved.
   */
  constructor() {
    this.world = void 0;
    this.useBoundingBoxes = void 0;
    this.dirty = void 0;
    this.world = null;
    this.useBoundingBoxes = false;
    this.dirty = true;
  }
  /**
   * Get the collision pairs from the world
   * @param world The world to search in
   * @param p1 Empty array to be filled with body objects
   * @param p2 Empty array to be filled with body objects
   */


  collisionPairs(world, p1, p2) {
    throw new Error('collisionPairs not implemented for this BroadPhase class!');
  }
  /**
   * Check if a body pair needs to be intersection tested at all.
   */


  needBroadphaseCollision(bodyA, bodyB) {
    // Check collision filter masks
    if ((bodyA.collisionFilterGroup & bodyB.collisionFilterMask) === 0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask) === 0) {
      return false;
    } // Check types


    if (((bodyA.type & Body.STATIC) !== 0 || bodyA.sleepState === Body.SLEEPING) && ((bodyB.type & Body.STATIC) !== 0 || bodyB.sleepState === Body.SLEEPING)) {
      // Both bodies are static or sleeping. Skip.
      return false;
    }

    return true;
  }
  /**
   * Check if the bounding volumes of two bodies intersect.
   */


  intersectionTest(bodyA, bodyB, pairs1, pairs2) {
    if (this.useBoundingBoxes) {
      this.doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2);
    } else {
      this.doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2);
    }
  }
  /**
   * Check if the bounding spheres of two bodies are intersecting.
   * @param pairs1 bodyA is appended to this array if intersection
   * @param pairs2 bodyB is appended to this array if intersection
   */


  doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2) {
    const r = Broadphase_collisionPairs_r;
    bodyB.position.vsub(bodyA.position, r);
    const boundingRadiusSum2 = (bodyA.boundingRadius + bodyB.boundingRadius) ** 2;
    const norm2 = r.lengthSquared();

    if (norm2 < boundingRadiusSum2) {
      pairs1.push(bodyA);
      pairs2.push(bodyB);
    }
  }
  /**
   * Check if the bounding boxes of two bodies are intersecting.
   */


  doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2) {
    if (bodyA.aabbNeedsUpdate) {
      bodyA.updateAABB();
    }

    if (bodyB.aabbNeedsUpdate) {
      bodyB.updateAABB();
    } // Check AABB / AABB


    if (bodyA.aabb.overlaps(bodyB.aabb)) {
      pairs1.push(bodyA);
      pairs2.push(bodyB);
    }
  }
  /**
   * Removes duplicate pairs from the pair arrays.
   */


  makePairsUnique(pairs1, pairs2) {
    const t = Broadphase_makePairsUnique_temp;
    const p1 = Broadphase_makePairsUnique_p1;
    const p2 = Broadphase_makePairsUnique_p2;
    const N = pairs1.length;

    for (let i = 0; i !== N; i++) {
      p1[i] = pairs1[i];
      p2[i] = pairs2[i];
    }

    pairs1.length = 0;
    pairs2.length = 0;

    for (let i = 0; i !== N; i++) {
      const id1 = p1[i].id;
      const id2 = p2[i].id;
      const key = id1 < id2 ? id1 + "," + id2 : id2 + "," + id1;
      t[key] = i;
      t.keys.push(key);
    }

    for (let i = 0; i !== t.keys.length; i++) {
      const key = t.keys.pop();
      const pairIndex = t[key];
      pairs1.push(p1[pairIndex]);
      pairs2.push(p2[pairIndex]);
      delete t[key];
    }
  }
  /**
   * To be implemented by subcasses
   */


  setWorld(world) {}
  /**
   * Check if the bounding spheres of two bodies overlap.
   */


  static boundingSphereCheck(bodyA, bodyB) {
    const dist = new Vec3(); // bsc_dist;

    bodyA.position.vsub(bodyB.position, dist);
    const sa = bodyA.shapes[0];
    const sb = bodyB.shapes[0];
    return Math.pow(sa.boundingSphereRadius + sb.boundingSphereRadius, 2) > dist.lengthSquared();
  }
  /**
   * Returns all the bodies within the AABB.
   */


  aabbQuery(world, aabb, result) {
    console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
    return [];
  }

} // Temp objects

const Broadphase_collisionPairs_r = new Vec3();
const Broadphase_makePairsUnique_temp = {
  keys: []
};
const Broadphase_makePairsUnique_p1 = [];
const Broadphase_makePairsUnique_p2 = [];

/**
 * Axis aligned uniform grid broadphase.
 * @todo Needs support for more than just planes and spheres.
 */
class GridBroadphase extends Broadphase {
  /**
   * Number of boxes along x
   */

  /**
   * Number of boxes along y
   */

  /**
   * Number of boxes along z
   */

  /**
   * aabbMin
   */

  /**
   * aabbMax
   */

  /**
   * bins
   */

  /**
   * binLengths
   */

  /**
   * @param nx Number of boxes along x.
   * @param ny Number of boxes along y.
   * @param nz Number of boxes along z.
   */
  constructor(aabbMin = new Vec3(100, 100, 100), aabbMax = new Vec3(-100, -100, -100), nx = 10, ny = 10, nz = 10) {
    super();
    this.nx = void 0;
    this.ny = void 0;
    this.nz = void 0;
    this.aabbMin = void 0;
    this.aabbMax = void 0;
    this.bins = void 0;
    this.binLengths = void 0;
    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 = []; // Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow

    this.bins.length = nbins;
    this.binLengths.length = nbins;

    for (let i = 0; i < nbins; i++) {
      this.bins[i] = [];
      this.binLengths[i] = 0;
    }
  }
  /**
   * Get all the collision pairs in the physics world
   */


  collisionPairs(world, pairs1, pairs2) {
    const N = world.numObjects();
    const bodies = world.bodies;
    const max = this.aabbMax;
    const min = this.aabbMin;
    const nx = this.nx;
    const ny = this.ny;
    const nz = this.nz;
    const xstep = ny * nz;
    const ystep = nz;
    const zstep = 1;
    const xmax = max.x;
    const ymax = max.y;
    const zmax = max.z;
    const xmin = min.x;
    const ymin = min.y;
    const zmin = min.z;
    const xmult = nx / (xmax - xmin);
    const ymult = ny / (ymax - ymin);
    const zmult = nz / (zmax - zmin);
    const binsizeX = (xmax - xmin) / nx;
    const binsizeY = (ymax - ymin) / ny;
    const binsizeZ = (zmax - zmin) / nz;
    const binRadius = Math.sqrt(binsizeX * binsizeX + binsizeY * binsizeY + binsizeZ * binsizeZ) * 0.5;
    const types = Shape.types;
    const SPHERE = types.SPHERE;
    const PLANE = types.PLANE;
    types.BOX;
    types.COMPOUND;
    types.CONVEXPOLYHEDRON;
    const bins = this.bins;
    const binLengths = this.binLengths;
    const Nbins = this.bins.length; // Reset bins

    for (let i = 0; i !== Nbins; i++) {
      binLengths[i] = 0;
    }

    const ceil = Math.ceil;

    function addBoxToBins(x0, y0, z0, x1, y1, z1, bi) {
      let xoff0 = (x0 - xmin) * xmult | 0;
      let yoff0 = (y0 - ymin) * ymult | 0;
      let zoff0 = (z0 - zmin) * zmult | 0;
      let xoff1 = ceil((x1 - xmin) * xmult);
      let yoff1 = ceil((y1 - ymin) * ymult);
      let zoff1 = ceil((z1 - zmin) * zmult);

      if (xoff0 < 0) {
        xoff0 = 0;
      } else if (xoff0 >= nx) {
        xoff0 = nx - 1;
      }

      if (yoff0 < 0) {
        yoff0 = 0;
      } else if (yoff0 >= ny) {
        yoff0 = ny - 1;
      }

      if (zoff0 < 0) {
        zoff0 = 0;
      } else if (zoff0 >= nz) {
        zoff0 = nz - 1;
      }

      if (xoff1 < 0) {
        xoff1 = 0;
      } else if (xoff1 >= nx) {
        xoff1 = nx - 1;
      }

      if (yoff1 < 0) {
        yoff1 = 0;
      } else if (yoff1 >= ny) {
        yoff1 = ny - 1;
      }

      if (zoff1 < 0) {
        zoff1 = 0;
      } else if (zoff1 >= nz) {
        zoff1 = nz - 1;
      }

      xoff0 *= xstep;
      yoff0 *= ystep;
      zoff0 *= zstep;
      xoff1 *= xstep;
      yoff1 *= ystep;
      zoff1 *= zstep;

      for (let xoff = xoff0; 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;
          }
        }
      }
    } // Put all bodies into the bins


    for (let i = 0; i !== N; i++) {
      const bi = bodies[i];
      const si = bi.shapes[0];

      switch (si.type) {
        case SPHERE:
          {
            const shape = si; // Put in bin
            // check if overlap with other bins

            const x = bi.position.x;
            const y = bi.position.y;
            const z = bi.position.z;
            const r = shape.radius;
            addBoxToBins(x - r, y - r, z - r, x + r, y + r, z + r, bi);
            break;
          }

        case PLANE:
          {
            const shape = si;

            if (shape.worldNormalNeedsUpdate) {
              shape.computeWorldNormal(bi.quaternion);
            }

            const planeNormal = shape.worldNormal; //Relative position from origin of plane object to the first bin
            //Incremented as we iterate through the bins

            const xreset = xmin + binsizeX * 0.5 - bi.position.x;
            const yreset = ymin + binsizeY * 0.5 - bi.position.y;
            const zreset = zmin + binsizeZ * 0.5 - bi.position.z;
            const 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) < binRadius) {
                    const idx = xoff + yoff + zoff;
                    bins[idx][binLengths[idx]++] = bi;
                  }
                }
              }
            }

            break;
          }

        default:
          {
            if (bi.aabbNeedsUpdate) {
              bi.updateAABB();
            }

            addBoxToBins(bi.aabb.lowerBound.x, bi.aabb.lowerBound.y, bi.aabb.lowerBound.z, bi.aabb.upperBound.x, bi.aabb.upperBound.y, bi.aabb.upperBound.z, bi);
            break;
          }
      }
    } // Check each bin


    for (let i = 0; i !== Nbins; i++) {
      const binLength = binLengths[i]; //Skip bins with no potential collisions

      if (binLength > 1) {
        const bin = bins[i]; // Do N^2 broadphase inside

        for (let xi = 0; xi !== binLength; xi++) {
          const bi = bin[xi];

          for (let yi = 0; yi !== xi; yi++) {
            const bj = bin[yi];

            if (this.needBroadphaseCollision(bi, bj)) {
              this.intersectionTest(bi, bj, pairs1, pairs2);
            }
          }
        }
      }
    } //	for (let zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
    //		console.log("layer "+zi);
    //		for (let yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
    //			const row = '';
    //			for (let xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
    //				const idx = xoff + yoff + zoff;
    //				row += ' ' + binLengths[idx];
    //			}
    //			console.log(row);
    //		}
    //	}


    this.makePairsUnique(pairs1, pairs2);
  }

}
const GridBroadphase_collisionPairs_d = new Vec3();

/**
 * Naive broadphase implementation, used in lack of better ones.
 *
 * The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_
 */
class NaiveBroadphase extends Broadphase {
  /**
   * @todo Remove useless constructor
   */
  constructor() {
    super();
  }
  /**
   * Get all the collision pairs in the physics world
   */


  collisionPairs(world, pairs1, pairs2) {
    const bodies = world.bodies;
    const n = bodies.length;
    let bi;
    let bj; // Naive N^2 ftw!

    for (let i = 0; i !== n; i++) {
      for (let j = 0; j !== i; j++) {
        bi = bodies[i];
        bj = bodies[j];

        if (!this.needBroadphaseCollision(bi, bj)) {
          continue;
        }

        this.intersectionTest(bi, bj, pairs1, pairs2);
      }
    }
  }
  /**
   * Returns all the bodies within an AABB.
   * @param result An array to store resulting bodies in.
   */


  aabbQuery(world, aabb, result = []) {
    for (let i = 0; i < world.bodies.length; i++) {
      const b = world.bodies[i];

      if (b.aabbNeedsUpdate) {
        b.updateAABB();
      } // Ugly hack until Body gets aabb


      if (b.aabb.overlaps(aabb)) {
        result.push(b);
      }
    }

    return result;
  }

}

/**
 * Storage for Ray casting data
 */
class RaycastResult {
  /**
   * rayFromWorld
   */

  /**
   * rayToWorld
   */

  /**
   * hitNormalWorld
   */

  /**
   * hitPointWorld
   */

  /**
   * hasHit
   */

  /**
   * shape
   */

  /**
   * body
   */

  /**
   * The index of the hit triangle, if the hit shape was a trimesh
   */

  /**
   * Distance to the hit. Will be set to -1 if there was no hit
   */

  /**
   * If the ray should stop traversing the bodies
   */
  constructor() {
    this.rayFromWorld = void 0;
    this.rayToWorld = void 0;
    this.hitNormalWorld = void 0;
    this.hitPointWorld = void 0;
    this.hasHit = void 0;
    this.shape = void 0;
    this.body = void 0;
    this.hitFaceIndex = void 0;
    this.distance = void 0;
    this.shouldStop = void 0;
    this.rayFromWorld = new Vec3();
    this.rayToWorld = new Vec3();
    this.hitNormalWorld = new Vec3();
    this.hitPointWorld = new Vec3();
    this.hasHit = false;
    this.shape = null;
    this.body = null;
    this.hitFaceIndex = -1;
    this.distance = -1;
    this.shouldStop = false;
  }
  /**
   * Reset all result data.
   */


  reset() {
    this.rayFromWorld.setZero();
    this.rayToWorld.setZero();
    this.hitNormalWorld.setZero();
    this.hitPointWorld.setZero();
    this.hasHit = false;
    this.shape = null;
    this.body = null;
    this.hitFaceIndex = -1;
    this.distance = -1;
    this.shouldStop = false;
  }
  /**
   * abort
   */


  abort() {
    this.shouldStop = true;
  }
  /**
   * Set result data.
   */


  set(rayFromWorld, rayToWorld, hitNormalWorld, hitPointWorld, shape, body, distance) {
    this.rayFromWorld.copy(rayFromWorld);
    this.rayToWorld.copy(rayToWorld);
    this.hitNormalWorld.copy(hitNormalWorld);
    this.hitPointWorld.copy(hitPointWorld);
    this.shape = shape;
    this.body = body;
    this.distance = distance;
  }

}

let _Shape$types$SPHERE, _Shape$types$PLANE, _Shape$types$BOX, _Shape$types$CYLINDER, _Shape$types$CONVEXPO, _Shape$types$HEIGHTFI, _Shape$types$TRIMESH;

/**
 * RAY_MODES
 */
const RAY_MODES = {
  /** CLOSEST */
  CLOSEST: 1,

  /** ANY */
  ANY: 2,

  /** ALL */
  ALL: 4
};
/**
 * RayMode
 */

_Shape$types$SPHERE = Shape.types.SPHERE;
_Shape$types$PLANE = Shape.types.PLANE;
_Shape$types$BOX = Shape.types.BOX;
_Shape$types$CYLINDER = Shape.types.CYLINDER;
_Shape$types$CONVEXPO = Shape.types.CONVEXPOLYHEDRON;
_Shape$types$HEIGHTFI = Shape.types.HEIGHTFIELD;
_Shape$types$TRIMESH = Shape.types.TRIMESH;

/**
 * A line in 3D space that intersects bodies and return points.
 */
class Ray {
  /**
   * from
   */

  /**
   * to
   */

  /**
   * direction
   */

  /**
   * The precision of the ray. Used when checking parallelity etc.
   * @default 0.0001
   */

  /**
   * Set to `false` if you don't want the Ray to take `collisionResponse` flags into account on bodies and shapes.
   * @default true
   */

  /**
   * If set to `true`, the ray skips any hits with normal.dot(rayDirection) < 0.
   * @default false
   */

  /**
   * collisionFilterMask
   * @default -1
   */

  /**
   * collisionFilterGroup
   * @default -1
   */

  /**
   * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
   * @default RAY.ANY
   */

  /**
   * Current result object.
   */

  /**
   * Will be set to `true` during intersectWorld() if the ray hit anything.
   */

  /**
   * User-provided result callback. Will be used if mode is Ray.ALL.
   */

  /**
   * CLOSEST
   */

  /**
   * ANY
   */

  /**
   * ALL
   */
  get [_Shape$types$SPHERE]() {
    return this._intersectSphere;
  }

  get [_Shape$types$PLANE]() {
    return this._intersectPlane;
  }

  get [_Shape$types$BOX]() {
    return this._intersectBox;
  }

  get [_Shape$types$CYLINDER]() {
    return this._intersectConvex;
  }

  get [_Shape$types$CONVEXPO]() {
    return this._intersectConvex;
  }

  get [_Shape$types$HEIGHTFI]() {
    return this._intersectHeightfield;
  }

  get [_Shape$types$TRIMESH]() {
    return this._intersectTrimesh;
  }

  constructor(from = new Vec3(), to = new Vec3()) {
    this.from = void 0;
    this.to = void 0;
    this.direction = void 0;
    this.precision = void 0;
    this.checkCollisionResponse = void 0;
    this.skipBackfaces = void 0;
    this.collisionFilterMask = void 0;
    this.collisionFilterGroup = void 0;
    this.mode = void 0;
    this.result = void 0;
    this.hasHit = void 0;
    this.callback = void 0;
    this.from = from.clone();
    this.to = to.clone();
    this.direction = new Vec3();
    this.precision = 0.0001;
    this.checkCollisionResponse = true;
    this.skipBackfaces = false;
    this.collisionFilterMask = -1;
    this.collisionFilterGroup = -1;
    this.mode = Ray.ANY;
    this.result = new RaycastResult();
    this.hasHit = false;

    this.callback = result => {};
  }
  /**
   * Do itersection against all bodies in the given World.
   * @return True if the ray hit anything, otherwise false.
   */


  intersectWorld(world, options) {
    this.mode = options.mode || Ray.ANY;
    this.result = options.result || new RaycastResult();
    this.skipBackfaces = !!options.skipBackfaces;
    this.collisionFilterMask = typeof options.collisionFilterMask !== 'undefined' ? options.collisionFilterMask : -1;
    this.collisionFilterGroup = typeof options.collisionFilterGroup !== 'undefined' ? options.collisionFilterGroup : -1;
    this.checkCollisionResponse = typeof options.checkCollisionResponse !== 'undefined' ? options.checkCollisionResponse : true;

    if (options.from) {
      this.from.copy(options.from);
    }

    if (options.to) {
      this.to.copy(options.to);
    }

    this.callback = options.callback || (() => {});

    this.hasHit = false;
    this.result.reset();
    this.updateDirection();
    this.getAABB(tmpAABB$1);
    tmpArray.length = 0;
    world.broadphase.aabbQuery(world, tmpAABB$1, tmpArray);
    this.intersectBodies(tmpArray);
    return this.hasHit;
  }
  /**
   * Shoot a ray at a body, get back information about the hit.
   * @deprecated @param result set the result property of the Ray instead.
   */


  intersectBody(body, result) {
    if (result) {
      this.result = result;
      this.updateDirection();
    }

    const checkCollisionResponse = this.checkCollisionResponse;

    if (checkCollisionResponse && !body.collisionResponse) {
      return;
    }

    if ((this.collisionFilterGroup & body.collisionFilterMask) === 0 || (body.collisionFilterGroup & this.collisionFilterMask) === 0) {
      return;
    }

    const xi = intersectBody_xi;
    const qi = intersectBody_qi;

    for (let i = 0, N = body.shapes.length; i < N; i++) {
      const shape = body.shapes[i];

      if (checkCollisionResponse && !shape.collisionResponse) {
        continue; // Skip
      }

      body.quaternion.mult(body.shapeOrientations[i], qi);
      body.quaternion.vmult(body.shapeOffsets[i], xi);
      xi.vadd(body.position, xi);
      this.intersectShape(shape, qi, xi, body);

      if (this.result.shouldStop) {
        break;
      }
    }
  }
  /**
   * Shoot a ray at an array bodies, get back information about the hit.
   * @param bodies An array of Body objects.
   * @deprecated @param result set the result property of the Ray instead.
   *
   */


  intersectBodies(bodies, result) {
    if (result) {
      this.result = result;
      this.updateDirection();
    }

    for (let i = 0, l = bodies.length; !this.result.shouldStop && i < l; i++) {
      this.intersectBody(bodies[i]);
    }
  }
  /**
   * Updates the direction vector.
   */


  updateDirection() {
    this.to.vsub(this.from, this.direction);
    this.direction.normalize();
  }

  intersectShape(shape, quat, position, body) {
    const from = this.from; // Checking boundingSphere

    const distance = distanceFromIntersection(from, this.direction, position);

    if (distance > shape.boundingSphereRadius) {
      return;
    }

    const intersectMethod = this[shape.type];

    if (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;
    const to = this.to;
    const direction = this.direction; // Get plane normal

    const worldNormal = new Vec3(0, 0, 1);
    quat.vmult(worldNormal, worldNormal);
    const len = new Vec3();
    from.vsub(position, len);
    const planeToFrom = len.dot(worldNormal);
    to.vsub(position, len);
    const planeToTo = len.dot(worldNormal);

    if (planeToFrom * planeToTo > 0) {
      // "from" and "to" are on the same side of the plane... bail out
      return;
    }

    if (from.distanceTo(to) < planeToFrom) {
      return;
    }

    const n_dot_dir = worldNormal.dot(direction);

    if (Math.abs(n_dot_dir) < this.precision) {
      // No intersection
      return;
    }

    const planePointToFrom = new Vec3();
    const dir_scaled_with_t = new Vec3();
    const hitPointWorld = new Vec3();
    from.vsub(position, planePointToFrom);
    const t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
    direction.scale(t, dir_scaled_with_t);
    from.vadd(dir_scaled_with_t, hitPointWorld);
    this.reportIntersection(worldNormal, hitPointWorld, reportedShape, body, -1);
  }
  /**
   * Get the world AABB of the ray.
   */


  getAABB(aabb) {
    const {
      lowerBound,
      upperBound
    } = aabb;
    const to = this.to;
    const from = this.from;
    lowerBound.x = Math.min(to.x, from.x);
    lowerBound.y = Math.min(to.y, from.y);
    lowerBound.z = Math.min(to.z, from.z);
    upperBound.x = Math.max(to.x, from.x);
    upperBound.y = Math.max(to.y, from.y);
    upperBound.z = Math.max(to.z, from.z);
  }

  _intersectHeightfield(shape, quat, position, body, reportedShape) {
    shape.data;
    shape.elementSize; // Convert the ray to local heightfield coordinates

    const localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to);

    localRay.from.copy(this.from);
    localRay.to.copy(this.to);
    Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
    Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
    localRay.updateDirection(); // Get the index of the data points to test against

    const index = intersectHeightfield_index;
    let iMinX;
    let iMinY;
    let iMaxX;
    let iMaxY; // Set to max

    iMinX = iMinY = 0;
    iMaxX = iMaxY = shape.data.length - 1;
    const aabb = new AABB();
    localRay.getAABB(aabb);
    shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true);
    iMinX = Math.max(iMinX, index[0]);
    iMinY = Math.max(iMinY, index[1]);
    shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true);
    iMaxX = Math.min(iMaxX, index[0] + 1);
    iMaxY = Math.min(iMaxY, index[1] + 1);

    for (let i = iMinX; i < iMaxX; i++) {
      for (let j = iMinY; j < iMaxY; j++) {
        if (this.result.shouldStop) {
          return;
        }

        shape.getAabbAtIndex(i, j, aabb);

        if (!aabb.overlapsRay(localRay)) {
          continue;
        } // Lower triangle


        shape.getConvexTrianglePillar(i, j, false);
        Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);

        this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);

        if (this.result.shouldStop) {
          return;
        } // Upper triangle


        shape.getConvexTrianglePillar(i, j, true);
        Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);

        this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
      }
    }
  }

  _intersectSphere(sphere, quat, position, body, reportedShape) {
    const from = this.from;
    const to = this.to;
    const r = sphere.radius;
    const a = (to.x - from.x) ** 2 + (to.y - from.y) ** 2 + (to.z - from.z) ** 2;
    const b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));
    const c = (from.x - position.x) ** 2 + (from.y - position.y) ** 2 + (from.z - position.z) ** 2 - r ** 2;
    const delta = b ** 2 - 4 * a * c;
    const intersectionPoint = Ray_intersectSphere_intersectionPoint;
    const normal = Ray_intersectSphere_normal;

    if (delta < 0) {
      // No intersection
      return;
    } else if (delta === 0) {
      // single intersection point
      from.lerp(to, delta, intersectionPoint);
      intersectionPoint.vsub(position, normal);
      normal.normalize();
      this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
    } else {
      const d1 = (-b - Math.sqrt(delta)) / (2 * a);
      const d2 = (-b + Math.sqrt(delta)) / (2 * a);

      if (d1 >= 0 && d1 <= 1) {
        from.lerp(to, d1, intersectionPoint);
        intersectionPoint.vsub(position, normal);
        normal.normalize();
        this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
      }

      if (this.result.shouldStop) {
        return;
      }

      if (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;
    const vector = intersectConvex_vector;
    const faceList = options && options.faceList || null; // Checking faces

    const faces = shape.faces;
    const vertices = shape.vertices;
    const normals = shape.faceNormals;
    const direction = this.direction;
    const from = this.from;
    const to = this.to;
    const fromToDistance = from.distanceTo(to);
    const Nfaces = faceList ? faceList.length : faces.length;
    const result = this.result;

    for (let j = 0; !result.shouldStop && j < Nfaces; j++) {
      const fi = faceList ? faceList[j] : j;
      const face = faces[fi];
      const faceNormal = normals[fi];
      const q = quat;
      const x = position; // determine if ray intersects the plane of the face
      // note: this works regardless of the direction of the face normal
      // Get plane point in world coordinates...

      vector.copy(vertices[face[0]]);
      q.vmult(vector, vector);
      vector.vadd(x, vector); // ...but make it relative to the ray from. We'll fix this later.

      vector.vsub(from, vector); // Get plane normal

      q.vmult(faceNormal, normal); // If this dot product is negative, we have something interesting

      const dot = direction.dot(normal); // Bail out if ray and plane are parallel

      if (Math.abs(dot) < this.precision) {
        continue;
      } // calc distance to plane


      const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray

      if (scalar < 0) {
        continue;
      } // if (dot < 0) {
      // Intersection point is from + direction * scalar


      direction.scale(scalar, intersectPoint);
      intersectPoint.vadd(from, intersectPoint); // a is the point we compare points b and c with.

      a.copy(vertices[face[0]]);
      q.vmult(a, a);
      x.vadd(a, a);

      for (let i = 1; !result.shouldStop && i < face.length - 1; i++) {
        // Transform 3 vertices to world coords
        b.copy(vertices[face[i]]);
        c.copy(vertices[face[i + 1]]);
        q.vmult(b, b);
        q.vmult(c, c);
        x.vadd(b, b);
        x.vadd(c, c);
        const distance = intersectPoint.distanceTo(from);

        if (!(Ray.pointInTriangle(intersectPoint, a, b, c) || Ray.pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance) {
          continue;
        }

        this.reportIntersection(normal, intersectPoint, reportedShape, body, fi);
      } // }

    }
  }
  /**
   * @todo Optimize by transforming the world to local space first.
   * @todo Use Octree lookup
   */


  _intersectTrimesh(mesh, quat, position, body, reportedShape, options) {
    const normal = intersectTrimesh_normal;
    const triangles = intersectTrimesh_triangles;
    const treeTransform = intersectTrimesh_treeTransform;
    const vector = intersectConvex_vector;
    const localDirection = intersectTrimesh_localDirection;
    const localFrom = intersectTrimesh_localFrom;
    const localTo = intersectTrimesh_localTo;
    const worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
    const worldNormal = intersectTrimesh_worldNormal; // Checking faces

    const indices = mesh.indices;
    mesh.vertices; // const normals = mesh.faceNormals

    const from = this.from;
    const to = this.to;
    const direction = this.direction;
    treeTransform.position.copy(position);
    treeTransform.quaternion.copy(quat); // Transform ray to local space!

    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); // determine if ray intersects the plane of the face
      // note: this works regardless of the direction of the face normal
      // Get plane point in world coordinates...

      mesh.getVertex(indices[trianglesIndex * 3], a); // ...but make it relative to the ray from. We'll fix this later.

      a.vsub(localFrom, vector); // If this dot product is negative, we have something interesting

      const dot = localDirection.dot(normal); // Bail out if ray and plane are parallel
      // if (Math.abs( dot ) < this.precision){
      //     continue;
      // }
      // calc distance to plane

      const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray

      if (scalar < 0) {
        continue;
      } // Intersection point is from + direction * scalar


      localDirection.scale(scalar, intersectPoint);
      intersectPoint.vadd(localFrom, intersectPoint); // Get triangle vertices

      mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
      mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
      const squaredDistance = intersectPoint.distanceSquared(localFrom);

      if (!(Ray.pointInTriangle(intersectPoint, b, a, c) || Ray.pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared) {
        continue;
      } // transform intersectpoint and normal to world


      Transform.vectorToWorldFrame(quat, normal, worldNormal);
      Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
      this.reportIntersection(worldNormal, worldIntersectPoint, reportedShape, body, trianglesIndex);
    }

    triangles.length = 0;
  }
  /**
   * @return True if the intersections should continue
   */


  reportIntersection(normal, hitPointWorld, shape, body, hitFaceIndex) {
    const from = this.from;
    const to = this.to;
    const distance = from.distanceTo(hitPointWorld);
    const result = this.result; // Skip back faces?

    if (this.skipBackfaces && normal.dot(this.direction) > 0) {
      return;
    }

    result.hitFaceIndex = typeof hitFaceIndex !== 'undefined' ? hitFaceIndex : -1;

    switch (this.mode) {
      case Ray.ALL:
        this.hasHit = true;
        result.set(from, to, normal, hitPointWorld, shape, body, distance);
        result.hasHit = true;
        this.callback(result);
        break;

      case Ray.CLOSEST:
        // Store if closer than current closest
        if (distance < result.distance || !result.hasHit) {
          this.hasHit = true;
          result.hasHit = true;
          result.set(from, to, normal, hitPointWorld, shape, body, distance);
        }

        break;

      case Ray.ANY:
        // Report and stop.
        this.hasHit = true;
        result.hasHit = true;
        result.set(from, to, normal, hitPointWorld, shape, body, distance);
        result.shouldStop = true;
        break;
    }
  }
  /**
   * As per "Barycentric Technique" as named
   * {@link https://www.blackpawn.com/texts/pointinpoly/default.html here} but without the division
   */


  static pointInTriangle(p, a, b, c) {
    c.vsub(a, v0);
    b.vsub(a, v1);
    p.vsub(a, v2);
    const dot00 = v0.dot(v0);
    const dot01 = v0.dot(v1);
    const dot02 = v0.dot(v2);
    const dot11 = v1.dot(v1);
    const dot12 = v1.dot(v2);
    let u;
    let v;
    return (u = dot11 * dot02 - dot01 * dot12) >= 0 && (v = dot00 * dot12 - dot01 * dot02) >= 0 && u + v < dot00 * dot11 - dot01 * dot01;
  }

}
Ray.CLOSEST = RAY_MODES.CLOSEST;
Ray.ANY = RAY_MODES.ANY;
Ray.ALL = RAY_MODES.ALL;
const tmpAABB$1 = new AABB();
const tmpArray = [];
const v1 = new Vec3();
const v2 = new Vec3();
const intersectBody_xi = new Vec3();
const intersectBody_qi = new Quaternion();
const intersectPoint = new Vec3();
const a = new Vec3();
const b = new Vec3();
const c = new Vec3();
const intersectConvexOptions = {
  faceList: [0]
};
const worldPillarOffset = new Vec3();
const intersectHeightfield_localRay = new Ray();
const intersectHeightfield_index = [];
const Ray_intersectSphere_intersectionPoint = new Vec3();
const Ray_intersectSphere_normal = new Vec3();
const intersectConvex_normal = new Vec3();
const intersectConvex_vector = new Vec3();
const intersectTrimesh_normal = new Vec3();
const intersectTrimesh_localDirection = new Vec3();
const intersectTrimesh_localFrom = new Vec3();
const intersectTrimesh_localTo = new Vec3();
const intersectTrimesh_worldNormal = new Vec3();
const intersectTrimesh_worldIntersectPoint = new Vec3();
new AABB();
const intersectTrimesh_triangles = [];
const intersectTrimesh_treeTransform = new Transform();
const v0 = new Vec3();
const intersect = new Vec3();

function distanceFromIntersection(from, direction, position) {
  // v0 is vector from from to position
  position.vsub(from, v0);
  const dot = v0.dot(direction); // intersect = direction*dot + from

  direction.scale(dot, intersect);
  intersect.vadd(from, intersect);
  const distance = position.distanceTo(intersect);
  return distance;
}

/**
 * Sweep and prune broadphase along one axis.
 */
class SAPBroadphase extends Broadphase {
  /**
   * List of bodies currently in the broadphase.
   */

  /**
   * The world to search in.
   */

  /**
   * Axis to sort the bodies along.
   * Set to 0 for x axis, and 1 for y axis.
   * For best performance, pick the axis where bodies are most distributed.
   */

  /**
   * Check if the bounds of two bodies overlap, along the given SAP axis.
   */
  static checkBounds(bi, bj, axisIndex) {
    let biPos;
    let bjPos;

    if (axisIndex === 0) {
      biPos = bi.position.x;
      bjPos = bj.position.x;
    } else if (axisIndex === 1) {
      biPos = bi.position.y;
      bjPos = bj.position.y;
    } else if (axisIndex === 2) {
      biPos = bi.position.z;
      bjPos = bj.position.z;
    }

    const ri = bi.boundingRadius,
          rj = bj.boundingRadius,
          boundA2 = biPos + ri,
          boundB1 = bjPos - rj;
    return boundB1 < boundA2;
  } // Note: these are identical, save for x/y/z lowerbound

  /**
   * insertionSortX
   */


  static insertionSortX(a) {
    for (let i = 1, l = a.length; i < l; i++) {
      const v = a[i];
      let j;

      for (j = i - 1; j >= 0; j--) {
        if (a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x) {
          break;
        }

        a[j + 1] = a[j];
      }

      a[j + 1] = v;
    }

    return a;
  }
  /**
   * insertionSortY
   */


  static insertionSortY(a) {
    for (let i = 1, l = a.length; i < l; i++) {
      const v = a[i];
      let j;

      for (j = i - 1; j >= 0; j--) {
        if (a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y) {
          break;
        }

        a[j + 1] = a[j];
      }

      a[j + 1] = v;
    }

    return a;
  }
  /**
   * insertionSortZ
   */


  static insertionSortZ(a) {
    for (let i = 1, l = a.length; i < l; i++) {
      const v = a[i];
      let j;

      for (j = i - 1; j >= 0; j--) {
        if (a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z) {
          break;
        }

        a[j + 1] = a[j];
      }

      a[j + 1] = v;
    }

    return a;
  }

  constructor(world) {
    super();
    this.axisList = void 0;
    this.world = void 0;
    this.axisIndex = void 0;
    this._addBodyHandler = void 0;
    this._removeBodyHandler = void 0;
    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);

      if (idx !== -1) {
        axisList.splice(idx, 1);
      }
    };

    if (world) {
      this.setWorld(world);
    }
  }
  /**
   * Change the world
   */


  setWorld(world) {
    // Clear the old axis array
    this.axisList.length = 0; // Add all bodies from the new world

    for (let i = 0; i < world.bodies.length; i++) {
      this.axisList.push(world.bodies[i]);
    } // Remove old handlers, if any


    world.removeEventListener('addBody', this._addBodyHandler);
    world.removeEventListener('removeBody', this._removeBodyHandler); // Add handlers to update the list of bodies.

    world.addEventListener('addBody', this._addBodyHandler);
    world.addEventListener('removeBody', this._removeBodyHandler);
    this.world = world;
    this.dirty = true;
  }
  /**
   * Collect all collision pairs
   */


  collisionPairs(world, p1, p2) {
    const bodies = this.axisList;
    const N = bodies.length;
    const axisIndex = this.axisIndex;
    let i;
    let j;

    if (this.dirty) {
      this.sortList();
      this.dirty = false;
    } // Look through the list


    for (i = 0; i !== N; i++) {
      const bi = bodies[i];

      for (j = i + 1; j < N; j++) {
        const bj = bodies[j];

        if (!this.needBroadphaseCollision(bi, bj)) {
          continue;
        }

        if (!SAPBroadphase.checkBounds(bi, bj, axisIndex)) {
          break;
        }

        this.intersectionTest(bi, bj, p1, p2);
      }
    }
  }

  sortList() {
    const axisList = this.axisList;
    const axisIndex = this.axisIndex;
    const N = axisList.length; // Update AABBs

    for (let i = 0; i !== N; i++) {
      const bi = axisList[i];

      if (bi.aabbNeedsUpdate) {
        bi.updateAABB();
      }
    } // Sort the list


    if (axisIndex === 0) {
      SAPBroadphase.insertionSortX(axisList);
    } else if (axisIndex === 1) {
      SAPBroadphase.insertionSortY(axisList);
    } else if (axisIndex === 2) {
      SAPBroadphase.insertionSortZ(axisList);
    }
  }
  /**
   * Computes the variance of the body positions and estimates the best axis to use.
   * Will automatically set property `axisIndex`.
   */


  autoDetectAxis() {
    let sumX = 0;
    let sumX2 = 0;
    let sumY = 0;
    let sumY2 = 0;
    let sumZ = 0;
    let sumZ2 = 0;
    const bodies = this.axisList;
    const N = bodies.length;
    const invN = 1 / N;

    for (let i = 0; i !== N; i++) {
      const b = bodies[i];
      const centerX = b.position.x;
      sumX += centerX;
      sumX2 += centerX * centerX;
      const centerY = b.position.y;
      sumY += centerY;
      sumY2 += centerY * centerY;
      const centerZ = b.position.z;
      sumZ += centerZ;
      sumZ2 += centerZ * centerZ;
    }

    const varianceX = sumX2 - sumX * sumX * invN;
    const varianceY = sumY2 - sumY * sumY * invN;
    const varianceZ = sumZ2 - sumZ * sumZ * invN;

    if (varianceX > varianceY) {
      if (varianceX > varianceZ) {
        this.axisIndex = 0;
      } else {
        this.axisIndex = 2;
      }
    } else if (varianceY > varianceZ) {
      this.axisIndex = 1;
    } else {
      this.axisIndex = 2;
    }
  }
  /**
   * Returns all the bodies within an AABB.
   * @param result An array to store resulting bodies in.
   */


  aabbQuery(world, aabb, result = []) {
    if (this.dirty) {
      this.sortList();
      this.dirty = false;
    }

    const axisIndex = this.axisIndex;
    let axis = 'x';

    if (axisIndex === 1) {
      axis = 'y';
    }

    if (axisIndex === 2) {
      axis = 'z';
    }

    const axisList = this.axisList;
    aabb.lowerBound[axis];
    aabb.upperBound[axis];

    for (let i = 0; i < axisList.length; i++) {
      const b = axisList[i];

      if (b.aabbNeedsUpdate) {
        b.updateAABB();
      }

      if (b.aabb.overlaps(aabb)) {
        result.push(b);
      }
    }

    return result;
  }

}

class Utils {
  /**
   * Extend an options object with default values.
   * @param options The options object. May be falsy: in this case, a new object is created and returned.
   * @param defaults An object containing default values.
   * @return The modified options object.
   */
  static defaults(options = {}, defaults) {
    for (let key in defaults) {
      if (!(key in options)) {
        options[key] = defaults[key];
      }
    }

    return options;
  }

}

/**
 * Constraint base class
 */
class Constraint {
  /**
   * Equations to be solved in this constraint.
   */

  /**
   * Body A.
   */

  /**
   * Body B.
   */

  /**
   * Set to false if you don't want the bodies to collide when they are connected.
   */
  constructor(bodyA, bodyB, options = {}) {
    this.equations = void 0;
    this.bodyA = void 0;
    this.bodyB = void 0;
    this.id = void 0;
    this.collideConnected = void 0;
    options = Utils.defaults(options, {
      collideConnected: true,
      wakeUpBodies: true
    });
    this.equations = [];
    this.bodyA = bodyA;
    this.bodyB = bodyB;
    this.id = Constraint.idCounter++;
    this.collideConnected = options.collideConnected;

    if (options.wakeUpBodies) {
      if (bodyA) {
        bodyA.wakeUp();
      }

      if (bodyB) {
        bodyB.wakeUp();
      }
    }
  }
  /**
   * Update all the equations with data.
   */


  update() {
    throw new Error('method update() not implmemented in this Constraint subclass!');
  }
  /**
   * Enables all equations in the constraint.
   */


  enable() {
    const eqs = this.equations;

    for (let i = 0; i < eqs.length; i++) {
      eqs[i].enabled = true;
    }
  }
  /**
   * Disables all equations in the constraint.
   */


  disable() {
    const eqs = this.equations;

    for (let i = 0; i < eqs.length; i++) {
      eqs[i].enabled = false;
    }
  }

}
Constraint.idCounter = 0;

/**
 * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
 */

class JacobianElement {
  /**
   * spatial
   */

  /**
   * rotational
   */
  constructor() {
    this.spatial = void 0;
    this.rotational = void 0;
    this.spatial = new Vec3();
    this.rotational = new Vec3();
  }
  /**
   * Multiply with other JacobianElement
   */


  multiplyElement(element) {
    return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  }
  /**
   * Multiply with two vectors
   */


  multiplyVectors(spatial, rotational) {
    return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  }

}

/**
 * Equation base class.
 *
 * `a`, `b` and `eps` are {@link https://www8.cs.umu.se/kurser/5DV058/VT15/lectures/SPOOKlabnotes.pdf SPOOK} parameters that default to `0.0`. See {@link https://github.com/schteppe/cannon.js/issues/238#issuecomment-147172327 this exchange} for more details on Cannon's physics implementation.
 */
class Equation {
  /**
   * Minimum (read: negative max) force to be applied by the constraint.
   */

  /**
   * Maximum (read: positive max) force to be applied by the constraint.
   */

  /**
   * SPOOK parameter
   */

  /**
   * SPOOK parameter
   */

  /**
   * SPOOK parameter
   */

  /**
   * A number, proportional to the force added to the bodies.
   */
  constructor(bi, bj, minForce = -1e6, maxForce = 1e6) {
    this.id = void 0;
    this.minForce = void 0;
    this.maxForce = void 0;
    this.bi = void 0;
    this.bj = void 0;
    this.si = void 0;
    this.sj = void 0;
    this.a = void 0;
    this.b = void 0;
    this.eps = void 0;
    this.jacobianElementA = void 0;
    this.jacobianElementB = void 0;
    this.enabled = void 0;
    this.multiplier = void 0;
    this.id = Equation.idCounter++;
    this.minForce = minForce;
    this.maxForce = maxForce;
    this.bi = bi;
    this.bj = bj;
    this.a = 0.0; // SPOOK parameter

    this.b = 0.0; // SPOOK parameter

    this.eps = 0.0; // SPOOK parameter

    this.jacobianElementA = new JacobianElement();
    this.jacobianElementB = new JacobianElement();
    this.enabled = true;
    this.multiplier = 0;
    this.setSpookParams(1e7, 4, 1 / 60); // Set typical spook params
  }
  /**
   * Recalculates a, b, and eps.
   *
   * The Equation constructor sets typical SPOOK parameters as such:
   * * `stiffness` = 1e7
   * * `relaxation` = 4
   * * `timeStep`= 1 / 60, _note the hardcoded refresh rate._
   */


  setSpookParams(stiffness, relaxation, timeStep) {
    const d = relaxation;
    const k = stiffness;
    const h = timeStep;
    this.a = 4.0 / (h * (1 + 4 * d));
    this.b = 4.0 * d / (1 + 4 * d);
    this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  }
  /**
   * Computes the right hand side of the SPOOK equation
   */


  computeB(a, b, h) {
    const GW = this.computeGW();
    const Gq = this.computeGq();
    const GiMf = this.computeGiMf();
    return -Gq * a - GW * b - GiMf * h;
  }
  /**
   * Computes G*q, where q are the generalized body coordinates
   */


  computeGq() {
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    const bi = this.bi;
    const bj = this.bj;
    const xi = bi.position;
    const xj = bj.position;
    return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  }
  /**
   * Computes G*W, where W are the body velocities
   */


  computeGW() {
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    const bi = this.bi;
    const bj = this.bj;
    const vi = bi.velocity;
    const vj = bj.velocity;
    const wi = bi.angularVelocity;
    const wj = bj.angularVelocity;
    return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  }
  /**
   * Computes G*Wlambda, where W are the body velocities
   */


  computeGWlambda() {
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    const bi = this.bi;
    const bj = this.bj;
    const vi = bi.vlambda;
    const vj = bj.vlambda;
    const wi = bi.wlambda;
    const wj = bj.wlambda;
    return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  }
  /**
   * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
   */


  computeGiMf() {
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    const bi = this.bi;
    const bj = this.bj;
    const fi = bi.force;
    const ti = bi.torque;
    const fj = bj.force;
    const tj = bj.torque;
    const invMassi = bi.invMassSolve;
    const invMassj = bj.invMassSolve;
    fi.scale(invMassi, iMfi);
    fj.scale(invMassj, iMfj);
    bi.invInertiaWorldSolve.vmult(ti, invIi_vmult_taui);
    bj.invInertiaWorldSolve.vmult(tj, invIj_vmult_tauj);
    return GA.multiplyVectors(iMfi, invIi_vmult_taui) + GB.multiplyVectors(iMfj, invIj_vmult_tauj);
  }
  /**
   * Computes G*inv(M)*G'
   */


  computeGiMGt() {
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    const bi = this.bi;
    const bj = this.bj;
    const invMassi = bi.invMassSolve;
    const invMassj = bj.invMassSolve;
    const invIi = bi.invInertiaWorldSolve;
    const invIj = bj.invInertiaWorldSolve;
    let result = invMassi + invMassj;
    invIi.vmult(GA.rotational, tmp);
    result += tmp.dot(GA.rotational);
    invIj.vmult(GB.rotational, tmp);
    result += tmp.dot(GB.rotational);
    return result;
  }
  /**
   * Add constraint velocity to the bodies.
   */


  addToWlambda(deltalambda) {
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    const bi = this.bi;
    const bj = this.bj;
    const temp = addToWlambda_temp; // Add to linear velocity
    // v_lambda += inv(M) * delta_lamba * G

    bi.vlambda.addScaledVector(bi.invMassSolve * deltalambda, GA.spatial, bi.vlambda);
    bj.vlambda.addScaledVector(bj.invMassSolve * deltalambda, GB.spatial, bj.vlambda); // Add to angular velocity

    bi.invInertiaWorldSolve.vmult(GA.rotational, temp);
    bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda);
    bj.invInertiaWorldSolve.vmult(GB.rotational, temp);
    bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda);
  }
  /**
   * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
   */


  computeC() {
    return this.computeGiMGt() + this.eps;
  }

}
Equation.idCounter = 0;
const iMfi = new Vec3();
const iMfj = new Vec3();
const invIi_vmult_taui = new Vec3();
const invIj_vmult_tauj = new Vec3();
const tmp = new Vec3();
const addToWlambda_temp = new Vec3();

/**
 * Contact/non-penetration constraint equation
 */
class ContactEquation extends Equation {
  /**
   * "bounciness": u1 = -e*u0
   */

  /**
   * World-oriented vector that goes from the center of bi to the contact point.
   */

  /**
   * World-oriented vector that starts in body j position and goes to the contact point.
   */

  /**
   * Contact normal, pointing out of body i.
   */
  constructor(bodyA, bodyB, maxForce = 1e6) {
    super(bodyA, bodyB, 0, maxForce);
    this.restitution = void 0;
    this.ri = void 0;
    this.rj = void 0;
    this.ni = void 0;
    this.restitution = 0.0;
    this.ri = new Vec3();
    this.rj = new Vec3();
    this.ni = new Vec3();
  }

  computeB(h) {
    const a = this.a;
    const b = this.b;
    const bi = this.bi;
    const bj = this.bj;
    const ri = this.ri;
    const rj = this.rj;
    const rixn = ContactEquation_computeB_temp1;
    const rjxn = ContactEquation_computeB_temp2;
    const vi = bi.velocity;
    const wi = bi.angularVelocity;
    bi.force;
    bi.torque;
    const vj = bj.velocity;
    const wj = bj.angularVelocity;
    bj.force;
    bj.torque;
    const penetrationVec = ContactEquation_computeB_temp3;
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    const n = this.ni; // Caluclate cross products

    ri.cross(n, rixn);
    rj.cross(n, rjxn); // g = xj+rj -(xi+ri)
    // G = [ -ni  -rixn  ni  rjxn ]

    n.negate(GA.spatial);
    rixn.negate(GA.rotational);
    GB.spatial.copy(n);
    GB.rotational.copy(rjxn); // Calculate the penetration vector

    penetrationVec.copy(bj.position);
    penetrationVec.vadd(rj, penetrationVec);
    penetrationVec.vsub(bi.position, penetrationVec);
    penetrationVec.vsub(ri, penetrationVec);
    const g = n.dot(penetrationVec); // Compute iteration

    const ePlusOne = this.restitution + 1;
    const GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
    const GiMf = this.computeGiMf();
    const B = -g * a - GW * b - h * GiMf;
    return B;
  }
  /**
   * Get the current relative velocity in the contact point.
   */


  getImpactVelocityAlongNormal() {
    const vi = ContactEquation_getImpactVelocityAlongNormal_vi;
    const vj = ContactEquation_getImpactVelocityAlongNormal_vj;
    const xi = ContactEquation_getImpactVelocityAlongNormal_xi;
    const xj = ContactEquation_getImpactVelocityAlongNormal_xj;
    const relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
    this.bi.position.vadd(this.ri, xi);
    this.bj.position.vadd(this.rj, xj);
    this.bi.getVelocityAtWorldPoint(xi, vi);
    this.bj.getVelocityAtWorldPoint(xj, vj);
    vi.vsub(vj, relVel);
    return this.ni.dot(relVel);
  }

}
const ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors

const ContactEquation_computeB_temp2 = new Vec3();
const ContactEquation_computeB_temp3 = new Vec3();
const ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
const ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
const ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
const ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
const ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();

/**
 * Connects two bodies at given offset points.
 * @example
 *     const bodyA = new Body({ mass: 1 })
 *     const bodyB = new Body({ mass: 1 })
 *     bodyA.position.set(-1, 0, 0)
 *     bodyB.position.set(1, 0, 0)
 *     bodyA.addShape(shapeA)
 *     bodyB.addShape(shapeB)
 *     world.addBody(bodyA)
 *     world.addBody(bodyB)
 *     const localPivotA = new Vec3(1, 0, 0)
 *     const localPivotB = new Vec3(-1, 0, 0)
 *     const constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB)
 *     world.addConstraint(constraint)
 */
class PointToPointConstraint extends Constraint {
  /**
   * Pivot, defined locally in bodyA.
   */

  /**
   * Pivot, defined locally in bodyB.
   */

  /**
   * @param pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
   * @param bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.
   * @param pivotB The point relative to the center of mass of bodyB which bodyB is constrained to.
   * @param maxForce The maximum force that should be applied to constrain the bodies.
   */
  constructor(bodyA, pivotA = new Vec3(), bodyB, pivotB = new Vec3(), maxForce = 1e6) {
    super(bodyA, bodyB);
    this.pivotA = void 0;
    this.pivotB = void 0;
    this.equationX = void 0;
    this.equationY = void 0;
    this.equationZ = void 0;
    this.pivotA = pivotA.clone();
    this.pivotB = pivotB.clone();
    const x = this.equationX = new ContactEquation(bodyA, bodyB);
    const y = this.equationY = new ContactEquation(bodyA, bodyB);
    const z = this.equationZ = new ContactEquation(bodyA, bodyB); // Equations to be fed to the solver

    this.equations.push(x, y, z); // Make the equations bidirectional

    x.minForce = y.minForce = z.minForce = -maxForce;
    x.maxForce = y.maxForce = z.maxForce = maxForce;
    x.ni.set(1, 0, 0);
    y.ni.set(0, 1, 0);
    z.ni.set(0, 0, 1);
  }

  update() {
    const bodyA = this.bodyA;
    const bodyB = this.bodyB;
    const x = this.equationX;
    const y = this.equationY;
    const z = this.equationZ; // Rotate the pivots to world space

    bodyA.quaternion.vmult(this.pivotA, x.ri);
    bodyB.quaternion.vmult(this.pivotB, x.rj);
    y.ri.copy(x.ri);
    y.rj.copy(x.rj);
    z.ri.copy(x.ri);
    z.rj.copy(x.rj);
  }

}

/**
 * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
 */
class ConeEquation extends Equation {
  /**
   * Local axis in A
   */

  /**
   * Local axis in B
   */

  /**
   * The "cone angle" to keep
   */
  constructor(bodyA, bodyB, options = {}) {
    const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
    super(bodyA, bodyB, -maxForce, maxForce);
    this.axisA = void 0;
    this.axisB = void 0;
    this.angle = void 0;
    this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
    this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
    this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
  }

  computeB(h) {
    const a = this.a;
    const b = this.b;
    const ni = this.axisA;
    const nj = this.axisB;
    const nixnj = tmpVec1$2;
    const njxni = tmpVec2$2;
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB; // Caluclate cross products

    ni.cross(nj, nixnj);
    nj.cross(ni, njxni); // The angle between two vector is:
    // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
    // g = a * b
    // gdot = (b x a) * wi + (a x b) * wj
    // G = [0 bxa 0 axb]
    // W = [vi wi vj wj]

    GA.rotational.copy(njxni);
    GB.rotational.copy(nixnj);
    const g = Math.cos(this.angle) - ni.dot(nj);
    const GW = this.computeGW();
    const GiMf = this.computeGiMf();
    const B = -g * a - GW * b - h * GiMf;
    return B;
  }

}
const tmpVec1$2 = new Vec3();
const tmpVec2$2 = new Vec3();

/**
 * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
 */
class RotationalEquation extends Equation {
  /**
   * World oriented rotational axis.
   */

  /**
   * World oriented rotational axis.
   */

  /**
   * maxAngle
   */
  constructor(bodyA, bodyB, options = {}) {
    const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
    super(bodyA, bodyB, -maxForce, maxForce);
    this.axisA = void 0;
    this.axisB = void 0;
    this.maxAngle = void 0;
    this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
    this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
    this.maxAngle = Math.PI / 2;
  }

  computeB(h) {
    const a = this.a;
    const b = this.b;
    const ni = this.axisA;
    const nj = this.axisB;
    const nixnj = tmpVec1$1;
    const njxni = tmpVec2$1;
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB; // Caluclate cross products

    ni.cross(nj, nixnj);
    nj.cross(ni, njxni); // g = ni * nj
    // gdot = (nj x ni) * wi + (ni x nj) * wj
    // G = [0 njxni 0 nixnj]
    // W = [vi wi vj wj]

    GA.rotational.copy(njxni);
    GB.rotational.copy(nixnj);
    const g = Math.cos(this.maxAngle) - ni.dot(nj);
    const GW = this.computeGW();
    const GiMf = this.computeGiMf();
    const B = -g * a - GW * b - h * GiMf;
    return B;
  }

}
const tmpVec1$1 = new Vec3();
const tmpVec2$1 = new Vec3();

/**
 * A Cone Twist constraint, useful for ragdolls.
 */
class ConeTwistConstraint extends PointToPointConstraint {
  /**
   * The axis direction for the constraint of the body A.
   */

  /**
   * The axis direction for the constraint of the body B.
   */

  /**
   * The aperture angle of the cone.
   */

  /**
   * The twist angle of the joint.
   */
  constructor(bodyA, bodyB, options = {}) {
    const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between

    const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
    const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
    super(bodyA, pivotA, bodyB, pivotB, maxForce);
    this.axisA = void 0;
    this.axisB = void 0;
    this.angle = void 0;
    this.twistAngle = void 0;
    this.coneEquation = void 0;
    this.twistEquation = void 0;
    this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
    this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
    this.collideConnected = !!options.collideConnected;
    this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
    const c = this.coneEquation = new ConeEquation(bodyA, bodyB, options);
    const t = this.twistEquation = new RotationalEquation(bodyA, bodyB, options);
    this.twistAngle = typeof options.twistAngle !== 'undefined' ? options.twistAngle : 0; // Make the cone equation push the bodies toward the cone axis, not outward

    c.maxForce = 0;
    c.minForce = -maxForce; // Make the twist equation add torque toward the initial position

    t.maxForce = 0;
    t.minForce = -maxForce;
    this.equations.push(c, t);
  }

  update() {
    const bodyA = this.bodyA;
    const bodyB = this.bodyB;
    const cone = this.coneEquation;
    const twist = this.twistEquation;
    super.update(); // Update the axes to the cone constraint

    bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
    bodyB.vectorToWorldFrame(this.axisB, cone.axisB); // Update the world axes in the twist constraint

    this.axisA.tangents(twist.axisA, twist.axisA);
    bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
    this.axisB.tangents(twist.axisB, twist.axisB);
    bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
    cone.angle = this.angle;
    twist.maxAngle = this.twistAngle;
  }

}

/**
 * Constrains two bodies to be at a constant distance from each others center of mass.
 */
class DistanceConstraint extends Constraint {
  /**
   * The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
   */

  /**
   * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB.
   * @param maxForce The maximum force that should be applied to constrain the bodies.
   */
  constructor(bodyA, bodyB, distance, maxForce = 1e6) {
    super(bodyA, bodyB);
    this.distance = void 0;
    this.distanceEquation = void 0;

    if (typeof distance === 'undefined') {
      distance = bodyA.position.distanceTo(bodyB.position);
    }

    this.distance = distance;
    const eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
    this.equations.push(eq); // Make it bidirectional

    eq.minForce = -maxForce;
    eq.maxForce = maxForce;
  }
  /**
   * update
   */


  update() {
    const bodyA = this.bodyA;
    const bodyB = this.bodyB;
    const eq = this.distanceEquation;
    const halfDist = this.distance * 0.5;
    const normal = eq.ni;
    bodyB.position.vsub(bodyA.position, normal);
    normal.normalize();
    normal.scale(halfDist, eq.ri);
    normal.scale(-halfDist, eq.rj);
  }

}

/**
 * Lock constraint. Will remove all degrees of freedom between the bodies.
 */
class LockConstraint extends PointToPointConstraint {
  constructor(bodyA, bodyB, options = {}) {
    const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between

    const pivotA = new Vec3();
    const pivotB = new Vec3();
    const halfWay = new Vec3();
    bodyA.position.vadd(bodyB.position, halfWay);
    halfWay.scale(0.5, halfWay);
    bodyB.pointToLocalFrame(halfWay, pivotB);
    bodyA.pointToLocalFrame(halfWay, pivotA); // The point-to-point constraint will keep a point shared between the bodies

    super(bodyA, pivotA, bodyB, pivotB, maxForce); // Store initial rotation of the bodies as unit vectors in the local body spaces

    this.xA = void 0;
    this.xB = void 0;
    this.yA = void 0;
    this.yB = void 0;
    this.zA = void 0;
    this.zB = void 0;
    this.rotationalEquation1 = void 0;
    this.rotationalEquation2 = void 0;
    this.rotationalEquation3 = void 0;
    this.motorEquation = void 0;
    this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X);
    this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X);
    this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y);
    this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y);
    this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z);
    this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z); // ...and the following rotational equations will keep all rotational DOF's in place

    const r1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
    const r2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
    const r3 = this.rotationalEquation3 = new RotationalEquation(bodyA, bodyB, options);
    this.equations.push(r1, r2, r3);
  }
  /**
   * update
   */


  update() {
    const bodyA = this.bodyA;
    const bodyB = this.bodyB;
    this.motorEquation;
    const r1 = this.rotationalEquation1;
    const r2 = this.rotationalEquation2;
    const r3 = this.rotationalEquation3;
    super.update(); // These vector pairs must be orthogonal

    bodyA.vectorToWorldFrame(this.xA, r1.axisA);
    bodyB.vectorToWorldFrame(this.yB, r1.axisB);
    bodyA.vectorToWorldFrame(this.yA, r2.axisA);
    bodyB.vectorToWorldFrame(this.zB, r2.axisB);
    bodyA.vectorToWorldFrame(this.zA, r3.axisA);
    bodyB.vectorToWorldFrame(this.xB, r3.axisB);
  }

}

/**
 * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
 */
class RotationalMotorEquation extends Equation {
  /**
   * World oriented rotational axis.
   */

  /**
   * World oriented rotational axis.
   */

  /**
   * Motor velocity.
   */
  constructor(bodyA, bodyB, maxForce = 1e6) {
    super(bodyA, bodyB, -maxForce, maxForce);
    this.axisA = void 0;
    this.axisB = void 0;
    this.targetVelocity = void 0;
    this.axisA = new Vec3();
    this.axisB = new Vec3();
    this.targetVelocity = 0;
  }

  computeB(h) {
    this.a;
    const b = this.b;
    this.bi;
    this.bj;
    const axisA = this.axisA;
    const axisB = this.axisB;
    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB; // g = 0
    // gdot = axisA * wi - axisB * wj
    // gdot = G * W = G * [vi wi vj wj]
    // =>
    // G = [0 axisA 0 -axisB]

    GA.rotational.copy(axisA);
    axisB.negate(GB.rotational);
    const GW = this.computeGW() - this.targetVelocity;
    const GiMf = this.computeGiMf();
    const B = -GW * b - h * GiMf;
    return B;
  }

}

/**
 * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
 */
class HingeConstraint extends PointToPointConstraint {
  /**
   * Rotation axis, defined locally in bodyA.
   */

  /**
   * Rotation axis, defined locally in bodyB.
   */
  constructor(bodyA, bodyB, options = {}) {
    const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
    const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
    const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
    super(bodyA, pivotA, bodyB, pivotB, maxForce);
    this.axisA = void 0;
    this.axisB = void 0;
    this.rotationalEquation1 = void 0;
    this.rotationalEquation2 = void 0;
    this.motorEquation = void 0;
    const axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
    axisA.normalize();
    const axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1, 0, 0);
    axisB.normalize();
    this.collideConnected = !!options.collideConnected;
    const rotational1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
    const rotational2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
    const motor = this.motorEquation = new RotationalMotorEquation(bodyA, bodyB, maxForce);
    motor.enabled = false; // Not enabled by default
    // Equations to be fed to the solver

    this.equations.push(rotational1, rotational2, motor);
  }
  /**
   * enableMotor
   */


  enableMotor() {
    this.motorEquation.enabled = true;
  }
  /**
   * disableMotor
   */


  disableMotor() {
    this.motorEquation.enabled = false;
  }
  /**
   * setMotorSpeed
   */


  setMotorSpeed(speed) {
    this.motorEquation.targetVelocity = speed;
  }
  /**
   * setMotorMaxForce
   */


  setMotorMaxForce(maxForce) {
    this.motorEquation.maxForce = maxForce;
    this.motorEquation.minForce = -maxForce;
  }
  /**
   * update
   */


  update() {
    const bodyA = this.bodyA;
    const bodyB = this.bodyB;
    const motor = this.motorEquation;
    const r1 = this.rotationalEquation1;
    const r2 = this.rotationalEquation2;
    const worldAxisA = HingeConstraint_update_tmpVec1;
    const worldAxisB = HingeConstraint_update_tmpVec2;
    const axisA = this.axisA;
    const axisB = this.axisB;
    super.update(); // Get world axes

    bodyA.quaternion.vmult(axisA, worldAxisA);
    bodyB.quaternion.vmult(axisB, worldAxisB);
    worldAxisA.tangents(r1.axisA, r2.axisA);
    r1.axisB.copy(worldAxisB);
    r2.axisB.copy(worldAxisB);

    if (this.motorEquation.enabled) {
      bodyA.quaternion.vmult(this.axisA, motor.axisA);
      bodyB.quaternion.vmult(this.axisB, motor.axisB);
    }
  }

}
const HingeConstraint_update_tmpVec1 = new Vec3();
const HingeConstraint_update_tmpVec2 = new Vec3();

/**
 * Constrains the slipping in a contact along a tangent
 */
class FrictionEquation extends Equation {
  // Tangent

  /**
   * @param slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
   */
  constructor(bodyA, bodyB, slipForce) {
    super(bodyA, bodyB, -slipForce, slipForce);
    this.ri = void 0;
    this.rj = void 0;
    this.t = void 0;
    this.ri = new Vec3();
    this.rj = new Vec3();
    this.t = new Vec3();
  }

  computeB(h) {
    this.a;
    const b = this.b;
    this.bi;
    this.bj;
    const ri = this.ri;
    const rj = this.rj;
    const rixt = FrictionEquation_computeB_temp1;
    const rjxt = FrictionEquation_computeB_temp2;
    const t = this.t; // Caluclate cross products

    ri.cross(t, rixt);
    rj.cross(t, rjxt); // G = [-t -rixt t rjxt]
    // And remember, this is a pure velocity constraint, g is always zero!

    const GA = this.jacobianElementA;
    const GB = this.jacobianElementB;
    t.negate(GA.spatial);
    rixt.negate(GA.rotational);
    GB.spatial.copy(t);
    GB.rotational.copy(rjxt);
    const GW = this.computeGW();
    const GiMf = this.computeGiMf();
    const B = -GW * b - h * GiMf;
    return B;
  }

}
const FrictionEquation_computeB_temp1 = new Vec3();
const FrictionEquation_computeB_temp2 = new Vec3();

/**
 * Defines what happens when two materials meet.
 * @todo Refactor materials to materialA and materialB
 */
class ContactMaterial {
  /**
   * Identifier of this material.
   */

  /**
   * Participating materials.
   */

  /**
   * Friction coefficient.
   * @default 0.3
   */

  /**
   * Restitution coefficient.
   * @default 0.3
   */

  /**
   * Stiffness of the produced contact equations.
   * @default 1e7
   */

  /**
   * Relaxation time of the produced contact equations.
   * @default 3
   */

  /**
   * Stiffness of the produced friction equations.
   * @default 1e7
   */

  /**
   * Relaxation time of the produced friction equations
   * @default 3
   */
  constructor(m1, m2, options) {
    this.id = void 0;
    this.materials = void 0;
    this.friction = void 0;
    this.restitution = void 0;
    this.contactEquationStiffness = void 0;
    this.contactEquationRelaxation = void 0;
    this.frictionEquationStiffness = void 0;
    this.frictionEquationRelaxation = void 0;
    options = Utils.defaults(options, {
      friction: 0.3,
      restitution: 0.3,
      contactEquationStiffness: 1e7,
      contactEquationRelaxation: 3,
      frictionEquationStiffness: 1e7,
      frictionEquationRelaxation: 3
    });
    this.id = ContactMaterial.idCounter++;
    this.materials = [m1, m2];
    this.friction = options.friction;
    this.restitution = options.restitution;
    this.contactEquationStiffness = options.contactEquationStiffness;
    this.contactEquationRelaxation = options.contactEquationRelaxation;
    this.frictionEquationStiffness = options.frictionEquationStiffness;
    this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  }

}
ContactMaterial.idCounter = 0;

/**
 * Defines a physics material.
 */
class Material {
  /**
   * Material name.
   * If options is a string, name will be set to that string.
   * @todo Deprecate this
   */

  /** Material id. */

  /**
   * Friction for this material.
   * If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.
   */

  /**
   * Restitution for this material.
   * If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.
   */
  constructor(options = {}) {
    this.name = void 0;
    this.id = void 0;
    this.friction = void 0;
    this.restitution = void 0;
    let name = ''; // Backwards compatibility fix

    if (typeof options === 'string') {
      //console.warn(`Passing a string to MaterialOptions is deprecated, and has no effect`)
      name = options;
      options = {};
    }

    this.name = name;
    this.id = Material.idCounter++;
    this.friction = typeof options.friction !== 'undefined' ? options.friction : -1;
    this.restitution = typeof options.restitution !== 'undefined' ? options.restitution : -1;
  }

}
Material.idCounter = 0;

/**
 * A spring, connecting two bodies.
 * @example
 *     const spring = new Spring(boxBody, sphereBody, {
 *       restLength: 0,
 *       stiffness: 50,
 *       damping: 1,
 *     })
 *
 *     // Compute the force after each step
 *     world.addEventListener('postStep', (event) => {
 *       spring.applyForce()
 *     })
 */
class Spring {
  /**
   * Rest length of the spring. A number > 0.
   * @default 1
   */

  /**
   * Stiffness of the spring. A number >= 0.
   * @default 100
   */

  /**
   * Damping of the spring. A number >= 0.
   * @default 1
   */

  /**
   * First connected body.
   */

  /**
   * Second connected body.
   */

  /**
   * Anchor for bodyA in local bodyA coordinates.
   * Where to hook the spring to body A, in local body coordinates.
   * @default new Vec3()
   */

  /**
   * Anchor for bodyB in local bodyB coordinates.
   * Where to hook the spring to body B, in local body coordinates.
   * @default new Vec3()
   */
  constructor(bodyA, bodyB, options = {}) {
    this.restLength = void 0;
    this.stiffness = void 0;
    this.damping = void 0;
    this.bodyA = void 0;
    this.bodyB = void 0;
    this.localAnchorA = void 0;
    this.localAnchorB = void 0;
    this.restLength = typeof options.restLength === 'number' ? options.restLength : 1;
    this.stiffness = options.stiffness || 100;
    this.damping = options.damping || 1;
    this.bodyA = bodyA;
    this.bodyB = bodyB;
    this.localAnchorA = new Vec3();
    this.localAnchorB = new Vec3();

    if (options.localAnchorA) {
      this.localAnchorA.copy(options.localAnchorA);
    }

    if (options.localAnchorB) {
      this.localAnchorB.copy(options.localAnchorB);
    }

    if (options.worldAnchorA) {
      this.setWorldAnchorA(options.worldAnchorA);
    }

    if (options.worldAnchorB) {
      this.setWorldAnchorB(options.worldAnchorB);
    }
  }
  /**
   * Set the anchor point on body A, using world coordinates.
   */


  setWorldAnchorA(worldAnchorA) {
    this.bodyA.pointToLocalFrame(worldAnchorA, this.localAnchorA);
  }
  /**
   * Set the anchor point on body B, using world coordinates.
   */


  setWorldAnchorB(worldAnchorB) {
    this.bodyB.pointToLocalFrame(worldAnchorB, this.localAnchorB);
  }
  /**
   * Get the anchor point on body A, in world coordinates.
   * @param result The vector to store the result in.
   */


  getWorldAnchorA(result) {
    this.bodyA.pointToWorldFrame(this.localAnchorA, result);
  }
  /**
   * Get the anchor point on body B, in world coordinates.
   * @param result The vector to store the result in.
   */


  getWorldAnchorB(result) {
    this.bodyB.pointToWorldFrame(this.localAnchorB, result);
  }
  /**
   * Apply the spring force to the connected bodies.
   */


  applyForce() {
    const k = this.stiffness;
    const d = this.damping;
    const l = this.restLength;
    const bodyA = this.bodyA;
    const bodyB = this.bodyB;
    const r = applyForce_r;
    const r_unit = applyForce_r_unit;
    const u = applyForce_u;
    const f = applyForce_f;
    const tmp = applyForce_tmp;
    const worldAnchorA = applyForce_worldAnchorA;
    const worldAnchorB = applyForce_worldAnchorB;
    const ri = applyForce_ri;
    const rj = applyForce_rj;
    const ri_x_f = applyForce_ri_x_f;
    const rj_x_f = applyForce_rj_x_f; // Get world anchors

    this.getWorldAnchorA(worldAnchorA);
    this.getWorldAnchorB(worldAnchorB); // Get offset points

    worldAnchorA.vsub(bodyA.position, ri);
    worldAnchorB.vsub(bodyB.position, rj); // Compute distance vector between world anchor points

    worldAnchorB.vsub(worldAnchorA, r);
    const rlen = r.length();
    r_unit.copy(r);
    r_unit.normalize(); // Compute relative velocity of the anchor points, u

    bodyB.velocity.vsub(bodyA.velocity, u); // Add rotational velocity

    bodyB.angularVelocity.cross(rj, tmp);
    u.vadd(tmp, u);
    bodyA.angularVelocity.cross(ri, tmp);
    u.vsub(tmp, u); // F = - k * ( x - L ) - D * ( u )

    r_unit.scale(-k * (rlen - l) - d * u.dot(r_unit), f); // Add forces to bodies

    bodyA.force.vsub(f, bodyA.force);
    bodyB.force.vadd(f, bodyB.force); // Angular force

    ri.cross(f, ri_x_f);
    rj.cross(f, rj_x_f);
    bodyA.torque.vsub(ri_x_f, bodyA.torque);
    bodyB.torque.vadd(rj_x_f, bodyB.torque);
  }

}
const applyForce_r = new Vec3();
const applyForce_r_unit = new Vec3();
const applyForce_u = new Vec3();
const applyForce_f = new Vec3();
const applyForce_worldAnchorA = new Vec3();
const applyForce_worldAnchorB = new Vec3();
const applyForce_ri = new Vec3();
const applyForce_rj = new Vec3();
const applyForce_ri_x_f = new Vec3();
const applyForce_rj_x_f = new Vec3();
const applyForce_tmp = new Vec3();

/**
 * WheelInfo
 */
class WheelInfo {
  /**
   * Max travel distance of the suspension, in meters.
   * @default 1
   */

  /**
   * Speed to apply to the wheel rotation when the wheel is sliding.
   * @default -0.1
   */

  /**
   * If the customSlidingRotationalSpeed should be used.
   * @default false
   */

  /**
   * sliding
   */

  /**
   * Connection point, defined locally in the chassis body frame.
   */

  /**
   * chassisConnectionPointWorld
   */

  /**
   * directionLocal
   */

  /**
   * directionWorld
   */

  /**
   * axleLocal
   */

  /**
   * axleWorld
   */

  /**
   * suspensionRestLength
   * @default 1
   */

  /**
   * suspensionMaxLength
   * @default 2
   */

  /**
   * radius
   * @default 1
   */

  /**
   * suspensionStiffness
   * @default 100
   */

  /**
   * dampingCompression
   * @default 10
   */

  /**
   * dampingRelaxation
   * @default 10
   */

  /**
   * frictionSlip
   * @default 10.5
   */

  /** forwardAcceleration */

  /** sideAcceleration */

  /**
   * steering
   * @default 0
   */

  /**
   * Rotation value, in radians.
   * @default 0
   */

  /**
   * deltaRotation
   * @default 0
   */

  /**
   * rollInfluence
   * @default 0.01
   */

  /**
   * maxSuspensionForce
   */

  /**
   * engineForce
   */

  /**
   * brake
   */

  /**
   * isFrontWheel
   * @default true
   */

  /**
   * clippedInvContactDotSuspension
   * @default 1
   */

  /**
   * suspensionRelativeVelocity
   * @default 0
   */

  /**
   * suspensionForce
   * @default 0
   */

  /**
   * slipInfo
   */

  /**
   * skidInfo
   * @default 0
   */

  /**
   * suspensionLength
   * @default 0
   */

  /**
   * sideImpulse
   */

  /**
   * forwardImpulse
   */

  /**
   * The result from raycasting.
   */

  /**
   * Wheel world transform.
   */

  /**
   * isInContact
   */
  constructor(options = {}) {
    this.maxSuspensionTravel = void 0;
    this.customSlidingRotationalSpeed = void 0;
    this.useCustomSlidingRotationalSpeed = void 0;
    this.sliding = void 0;
    this.chassisConnectionPointLocal = void 0;
    this.chassisConnectionPointWorld = void 0;
    this.directionLocal = void 0;
    this.directionWorld = void 0;
    this.axleLocal = void 0;
    this.axleWorld = void 0;
    this.suspensionRestLength = void 0;
    this.suspensionMaxLength = void 0;
    this.radius = void 0;
    this.suspensionStiffness = void 0;
    this.dampingCompression = void 0;
    this.dampingRelaxation = void 0;
    this.frictionSlip = void 0;
    this.forwardAcceleration = void 0;
    this.sideAcceleration = void 0;
    this.steering = void 0;
    this.rotation = void 0;
    this.deltaRotation = void 0;
    this.rollInfluence = void 0;
    this.maxSuspensionForce = void 0;
    this.engineForce = void 0;
    this.brake = void 0;
    this.isFrontWheel = void 0;
    this.clippedInvContactDotSuspension = void 0;
    this.suspensionRelativeVelocity = void 0;
    this.suspensionForce = void 0;
    this.slipInfo = void 0;
    this.skidInfo = void 0;
    this.suspensionLength = void 0;
    this.sideImpulse = void 0;
    this.forwardImpulse = void 0;
    this.raycastResult = void 0;
    this.worldTransform = void 0;
    this.isInContact = void 0;
    options = Utils.defaults(options, {
      chassisConnectionPointLocal: new Vec3(),
      chassisConnectionPointWorld: new Vec3(),
      directionLocal: new Vec3(),
      directionWorld: new Vec3(),
      axleLocal: new Vec3(),
      axleWorld: new Vec3(),
      suspensionRestLength: 1,
      suspensionMaxLength: 2,
      radius: 1,
      suspensionStiffness: 100,
      dampingCompression: 10,
      dampingRelaxation: 10,
      frictionSlip: 10.5,
      forwardAcceleration: 1,
      sideAcceleration: 1,
      steering: 0,
      rotation: 0,
      deltaRotation: 0,
      rollInfluence: 0.01,
      maxSuspensionForce: Number.MAX_VALUE,
      isFrontWheel: true,
      clippedInvContactDotSuspension: 1,
      suspensionRelativeVelocity: 0,
      suspensionForce: 0,
      slipInfo: 0,
      skidInfo: 0,
      suspensionLength: 0,
      maxSuspensionTravel: 1,
      useCustomSlidingRotationalSpeed: false,
      customSlidingRotationalSpeed: -0.1
    });
    this.maxSuspensionTravel = options.maxSuspensionTravel;
    this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
    this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
    this.sliding = false;
    this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
    this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
    this.directionLocal = options.directionLocal.clone();
    this.directionWorld = options.directionWorld.clone();
    this.axleLocal = options.axleLocal.clone();
    this.axleWorld = options.axleWorld.clone();
    this.suspensionRestLength = options.suspensionRestLength;
    this.suspensionMaxLength = options.suspensionMaxLength;
    this.radius = options.radius;
    this.suspensionStiffness = options.suspensionStiffness;
    this.dampingCompression = options.dampingCompression;
    this.dampingRelaxation = options.dampingRelaxation;
    this.frictionSlip = options.frictionSlip;
    this.forwardAcceleration = options.forwardAcceleration;
    this.sideAcceleration = options.sideAcceleration;
    this.steering = 0;
    this.rotation = 0;
    this.deltaRotation = 0;
    this.rollInfluence = options.rollInfluence;
    this.maxSuspensionForce = options.maxSuspensionForce;
    this.engineForce = 0;
    this.brake = 0;
    this.isFrontWheel = options.isFrontWheel;
    this.clippedInvContactDotSuspension = 1;
    this.suspensionRelativeVelocity = 0;
    this.suspensionForce = 0;
    this.slipInfo = 0;
    this.skidInfo = 0;
    this.suspensionLength = 0;
    this.sideImpulse = 0;
    this.forwardImpulse = 0;
    this.raycastResult = new RaycastResult();
    this.worldTransform = new Transform();
    this.isInContact = false;
  }

  updateWheel(chassis) {
    const raycastResult = this.raycastResult;

    if (this.isInContact) {
      const project = raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
      raycastResult.hitPointWorld.vsub(chassis.position, relpos);
      chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
      const projVel = raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);

      if (project >= -0.1) {
        this.suspensionRelativeVelocity = 0.0;
        this.clippedInvContactDotSuspension = 1.0 / 0.1;
      } else {
        const inv = -1 / project;
        this.suspensionRelativeVelocity = projVel * inv;
        this.clippedInvContactDotSuspension = inv;
      }
    } else {
      // Not in contact : position wheel in a nice (rest length) position
      raycastResult.suspensionLength = this.suspensionRestLength;
      this.suspensionRelativeVelocity = 0.0;
      raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
      this.clippedInvContactDotSuspension = 1.0;
    }
  }

}
const chassis_velocity_at_contactPoint = new Vec3();
const relpos = new Vec3();

/**
 * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
 */
class RaycastVehicle {
  /** The car chassis body. */

  /** The wheels. */

  /** Will be set to true if the car is sliding. */

  /** Index of the right axis. x=0, y=1, z=2 */

  /** Index of the forward axis. x=0, y=1, z=2 */

  /** Index of the up axis. x=0, y=1, z=2 */

  /** The constraints. */

  /** Optional pre-step callback. */

  /** Number of wheels on the ground. */
  constructor(options) {
    this.chassisBody = void 0;
    this.wheelInfos = void 0;
    this.sliding = void 0;
    this.world = void 0;
    this.indexRightAxis = void 0;
    this.indexForwardAxis = void 0;
    this.indexUpAxis = void 0;
    this.constraints = void 0;
    this.preStepCallback = void 0;
    this.currentVehicleSpeedKmHour = void 0;
    this.numWheelsOnGround = void 0;
    this.chassisBody = options.chassisBody;
    this.wheelInfos = [];
    this.sliding = false;
    this.world = null;
    this.indexRightAxis = typeof options.indexRightAxis !== 'undefined' ? options.indexRightAxis : 2;
    this.indexForwardAxis = typeof options.indexForwardAxis !== 'undefined' ? options.indexForwardAxis : 0;
    this.indexUpAxis = typeof options.indexUpAxis !== 'undefined' ? options.indexUpAxis : 1;
    this.constraints = [];

    this.preStepCallback = () => {};

    this.currentVehicleSpeedKmHour = 0;
    this.numWheelsOnGround = 0;
  }
  /**
   * Add a wheel. For information about the options, see `WheelInfo`.
   */


  addWheel(options = {}) {
    const info = new WheelInfo(options);
    const index = this.wheelInfos.length;
    this.wheelInfos.push(info);
    return index;
  }
  /**
   * Set the steering value of a wheel.
   */


  setSteeringValue(value, wheelIndex) {
    const wheel = this.wheelInfos[wheelIndex];
    wheel.steering = value;
  }
  /**
   * Set the wheel force to apply on one of the wheels each time step
   */


  applyEngineForce(value, wheelIndex) {
    this.wheelInfos[wheelIndex].engineForce = value;
  }
  /**
   * Set the braking force of a wheel
   */


  setBrake(brake, wheelIndex) {
    this.wheelInfos[wheelIndex].brake = brake;
  }
  /**
   * Add the vehicle including its constraints to the world.
   */


  addToWorld(world) {
    world.addBody(this.chassisBody);
    const that = this;

    this.preStepCallback = () => {
      that.updateVehicle(world.dt);
    };

    world.addEventListener('preStep', this.preStepCallback);
    this.world = world;
  }
  /**
   * Get one of the wheel axles, world-oriented.
   */


  getVehicleAxisWorld(axisIndex, result) {
    result.set(axisIndex === 0 ? 1 : 0, axisIndex === 1 ? 1 : 0, axisIndex === 2 ? 1 : 0);
    this.chassisBody.vectorToWorldFrame(result, result);
  }

  updateVehicle(timeStep) {
    const wheelInfos = this.wheelInfos;
    const numWheels = wheelInfos.length;
    const chassisBody = this.chassisBody;

    for (let i = 0; i < numWheels; i++) {
      this.updateWheelTransform(i);
    }

    this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length();
    const forwardWorld = new Vec3();
    this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);

    if (forwardWorld.dot(chassisBody.velocity) < 0) {
      this.currentVehicleSpeedKmHour *= -1;
    } // simulate suspension


    for (let i = 0; i < numWheels; i++) {
      this.castRay(wheelInfos[i]);
    }

    this.updateSuspension(timeStep);
    const impulse = new Vec3();
    const relpos = new Vec3();

    for (let i = 0; i < numWheels; i++) {
      //apply suspension force
      const wheel = wheelInfos[i];
      let suspensionForce = wheel.suspensionForce;

      if (suspensionForce > wheel.maxSuspensionForce) {
        suspensionForce = wheel.maxSuspensionForce;
      }

      wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
      wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
      chassisBody.applyImpulse(impulse, relpos);
    }

    this.updateFriction(timeStep);
    const hitNormalWorldScaledWithProj = new Vec3();
    const fwd = new Vec3();
    const vel = new Vec3();

    for (let i = 0; i < numWheels; i++) {
      const wheel = wheelInfos[i]; //const relpos = new Vec3();
      //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);

      chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel); // Hack to get the rotation in the correct direction

      let m = 1;

      switch (this.indexUpAxis) {
        case 1:
          m = -1;
          break;
      }

      if (wheel.isInContact) {
        this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
        const proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
        wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
        fwd.vsub(hitNormalWorldScaledWithProj, fwd);
        const proj2 = fwd.dot(vel);
        wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
      }

      if ((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed) {
        // Apply custom rotation when accelerating and sliding
        wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
      } // Lock wheels


      if (Math.abs(wheel.brake) > Math.abs(wheel.engineForce)) {
        wheel.deltaRotation = 0;
      }

      wheel.rotation += wheel.deltaRotation; // Use the old value

      wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
    }
  }

  updateSuspension(deltaTime) {
    const chassisBody = this.chassisBody;
    const chassisMass = chassisBody.mass;
    const wheelInfos = this.wheelInfos;
    const numWheels = wheelInfos.length;

    for (let w_it = 0; w_it < numWheels; w_it++) {
      const wheel = wheelInfos[w_it];

      if (wheel.isInContact) {
        let force; // Spring

        const susp_length = wheel.suspensionRestLength;
        const current_length = wheel.suspensionLength;
        const length_diff = susp_length - current_length;
        force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension; // Damper

        const projected_rel_vel = wheel.suspensionRelativeVelocity;
        let susp_damping;

        if (projected_rel_vel < 0) {
          susp_damping = wheel.dampingCompression;
        } else {
          susp_damping = wheel.dampingRelaxation;
        }

        force -= susp_damping * projected_rel_vel;
        wheel.suspensionForce = force * chassisMass;

        if (wheel.suspensionForce < 0) {
          wheel.suspensionForce = 0;
        }
      } else {
        wheel.suspensionForce = 0;
      }
    }
  }
  /**
   * Remove the vehicle including its constraints from the world.
   */


  removeFromWorld(world) {
    this.constraints;
    world.removeBody(this.chassisBody);
    world.removeEventListener('preStep', this.preStepCallback);
    this.world = null;
  }

  castRay(wheel) {
    const rayvector = castRay_rayvector;
    const target = castRay_target;
    this.updateWheelTransformWorld(wheel);
    const chassisBody = this.chassisBody;
    let depth = -1;
    const raylen = wheel.suspensionRestLength + wheel.radius;
    wheel.directionWorld.scale(raylen, rayvector);
    const source = wheel.chassisConnectionPointWorld;
    source.vadd(rayvector, target);
    const raycastResult = wheel.raycastResult;
    raycastResult.reset(); // Turn off ray collision with the chassis temporarily

    const oldState = chassisBody.collisionResponse;
    chassisBody.collisionResponse = false; // Cast ray against world

    this.world.rayTest(source, target, raycastResult);
    chassisBody.collisionResponse = oldState;
    const object = raycastResult.body;
    wheel.raycastResult.groundObject = 0;

    if (object) {
      depth = raycastResult.distance;
      wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
      wheel.isInContact = true;
      const hitDistance = raycastResult.distance;
      wheel.suspensionLength = hitDistance - wheel.radius; // clamp on max suspension travel

      const minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
      const maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;

      if (wheel.suspensionLength < minSuspensionLength) {
        wheel.suspensionLength = minSuspensionLength;
      }

      if (wheel.suspensionLength > maxSuspensionLength) {
        wheel.suspensionLength = maxSuspensionLength;
        wheel.raycastResult.reset();
      }

      const denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
      const 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 >= -0.1) {
        wheel.suspensionRelativeVelocity = 0;
        wheel.clippedInvContactDotSuspension = 1 / 0.1;
      } else {
        const inv = -1 / denominator;
        wheel.suspensionRelativeVelocity = projVel * inv;
        wheel.clippedInvContactDotSuspension = inv;
      }
    } else {
      //put wheel info as in rest position
      wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
      wheel.suspensionRelativeVelocity = 0.0;
      wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
      wheel.clippedInvContactDotSuspension = 1.0;
    }

    return depth;
  }

  updateWheelTransformWorld(wheel) {
    wheel.isInContact = false;
    const chassisBody = this.chassisBody;
    chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
    chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
    chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  }
  /**
   * Update one of the wheel transform.
   * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.
   * @param wheelIndex The wheel index to update.
   */


  updateWheelTransform(wheelIndex) {
    const up = tmpVec4;
    const right = tmpVec5;
    const fwd = tmpVec6;
    const wheel = this.wheelInfos[wheelIndex];
    this.updateWheelTransformWorld(wheel);
    wheel.directionLocal.scale(-1, up);
    right.copy(wheel.axleLocal);
    up.cross(right, fwd);
    fwd.normalize();
    right.normalize(); // Rotate around steering over the wheelAxle

    const steering = wheel.steering;
    const steeringOrn = new Quaternion();
    steeringOrn.setFromAxisAngle(up, steering);
    const rotatingOrn = new Quaternion();
    rotatingOrn.setFromAxisAngle(right, wheel.rotation); // World rotation of the wheel

    const q = wheel.worldTransform.quaternion;
    this.chassisBody.quaternion.mult(steeringOrn, q);
    q.mult(rotatingOrn, q);
    q.normalize(); // world position of the wheel

    const p = wheel.worldTransform.position;
    p.copy(wheel.directionWorld);
    p.scale(wheel.suspensionLength, p);
    p.vadd(wheel.chassisConnectionPointWorld, p);
  }
  /**
   * Get the world transform of one of the wheels
   */


  getWheelTransformWorld(wheelIndex) {
    return this.wheelInfos[wheelIndex].worldTransform;
  }

  updateFriction(timeStep) {
    const surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; //calculate the impulse, so that the wheels don't move sidewards

    const wheelInfos = this.wheelInfos;
    const numWheels = wheelInfos.length;
    const chassisBody = this.chassisBody;
    const forwardWS = updateFriction_forwardWS;
    const axle = updateFriction_axle;
    this.numWheelsOnGround = 0;

    for (let i = 0; i < numWheels; i++) {
      const wheel = wheelInfos[i];
      const groundObject = wheel.raycastResult.body;

      if (groundObject) {
        this.numWheelsOnGround++;
      }

      wheel.sideImpulse = 0;
      wheel.forwardImpulse = 0;

      if (!forwardWS[i]) {
        forwardWS[i] = new Vec3();
      }

      if (!axle[i]) {
        axle[i] = new Vec3();
      }
    }

    for (let i = 0; i < numWheels; i++) {
      const wheel = wheelInfos[i];
      const groundObject = wheel.raycastResult.body;

      if (groundObject) {
        const axlei = axle[i];
        const wheelTrans = this.getWheelTransformWorld(i); // Get world axle

        wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
        const surfNormalWS = wheel.raycastResult.hitNormalWorld;
        const proj = axlei.dot(surfNormalWS);
        surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
        axlei.vsub(surfNormalWS_scaled_proj, axlei);
        axlei.normalize();
        surfNormalWS.cross(axlei, forwardWS[i]);
        forwardWS[i].normalize();
        wheel.sideImpulse = resolveSingleBilateral(chassisBody, wheel.raycastResult.hitPointWorld, groundObject, wheel.raycastResult.hitPointWorld, axlei);
        wheel.sideImpulse *= sideFrictionStiffness2;
      }
    }

    const sideFactor = 1;
    const fwdFactor = 0.5;
    this.sliding = false;

    for (let i = 0; i < numWheels; i++) {
      const wheel = wheelInfos[i];
      const groundObject = wheel.raycastResult.body;
      let rollingFriction = 0;
      wheel.slipInfo = 1;

      if (groundObject) {
        const defaultRollingFrictionImpulse = 0;
        const maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse; // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
        // rollingFriction = calcRollingFriction(contactPt);

        rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
        rollingFriction += wheel.engineForce * timeStep; // rollingFriction = 0;

        const factor = maxImpulse / rollingFriction;
        wheel.slipInfo *= factor;
      } //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)


      wheel.forwardImpulse = 0;
      wheel.skidInfo = 1;

      if (groundObject) {
        wheel.skidInfo = 1;
        const maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
        const maximpSide = maximp;
        const maximpSquared = maximp * maximpSide;
        wheel.forwardImpulse = rollingFriction; //wheelInfo.engineForce* timeStep;

        const x = wheel.forwardImpulse * fwdFactor / wheel.forwardAcceleration;
        const y = wheel.sideImpulse * sideFactor / wheel.sideAcceleration;
        const impulseSquared = x * x + y * y;
        wheel.sliding = false;

        if (impulseSquared > maximpSquared) {
          this.sliding = true;
          wheel.sliding = true;
          const factor = maximp / Math.sqrt(impulseSquared);
          wheel.skidInfo *= factor;
        }
      }
    }

    if (this.sliding) {
      for (let i = 0; i < numWheels; i++) {
        const wheel = wheelInfos[i];

        if (wheel.sideImpulse !== 0) {
          if (wheel.skidInfo < 1) {
            wheel.forwardImpulse *= wheel.skidInfo;
            wheel.sideImpulse *= wheel.skidInfo;
          }
        }
      }
    } // apply the impulses


    for (let i = 0; i < numWheels; i++) {
      const wheel = wheelInfos[i];
      const rel_pos = new Vec3();
      wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); // cannons applyimpulse is using world coord for the position
      //rel_pos.copy(wheel.raycastResult.hitPointWorld);

      if (wheel.forwardImpulse !== 0) {
        const impulse = new Vec3();
        forwardWS[i].scale(wheel.forwardImpulse, impulse);
        chassisBody.applyImpulse(impulse, rel_pos);
      }

      if (wheel.sideImpulse !== 0) {
        const groundObject = wheel.raycastResult.body;
        const rel_pos2 = new Vec3();
        wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); //rel_pos2.copy(wheel.raycastResult.hitPointWorld);

        const sideImp = new Vec3();
        axle[i].scale(wheel.sideImpulse, sideImp); // Scale the relative position in the up direction with rollInfluence.
        // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).

        chassisBody.vectorToLocalFrame(rel_pos, rel_pos);
        rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
        chassisBody.vectorToWorldFrame(rel_pos, rel_pos);
        chassisBody.applyImpulse(sideImp, rel_pos); //apply friction impulse on the ground

        sideImp.scale(-1, sideImp);
        groundObject.applyImpulse(sideImp, rel_pos2);
      }
    }
  }

}
const tmpVec4 = new Vec3();
const tmpVec5 = new Vec3();
const tmpVec6 = new Vec3();
new Ray();
const castRay_rayvector = new Vec3();
const castRay_target = new Vec3();
const directions = [new Vec3(1, 0, 0), new Vec3(0, 1, 0), new Vec3(0, 0, 1)];
const updateFriction_surfNormalWS_scaled_proj = new Vec3();
const updateFriction_axle = [];
const updateFriction_forwardWS = [];
const sideFrictionStiffness2 = 1;
const calcRollingFriction_vel1 = new Vec3();
const calcRollingFriction_vel2 = new Vec3();
const calcRollingFriction_vel = new Vec3();

function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  let j1 = 0;
  const contactPosWorld = frictionPosWorld; // const rel_pos1 = new Vec3();
  // const rel_pos2 = new Vec3();

  const vel1 = calcRollingFriction_vel1;
  const vel2 = calcRollingFriction_vel2;
  const vel = calcRollingFriction_vel; // contactPosWorld.vsub(body0.position, rel_pos1);
  // contactPosWorld.vsub(body1.position, rel_pos2);

  body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  vel1.vsub(vel2, vel);
  const vrel = frictionDirectionWorld.dot(vel);
  const denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  const denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  const relaxation = 1;
  const jacDiagABInv = relaxation / (denom0 + denom1); // calculate j that moves us to zero relative velocity

  j1 = -vrel * jacDiagABInv;

  if (maxImpulse < j1) {
    j1 = maxImpulse;
  }

  if (j1 < -maxImpulse) {
    j1 = -maxImpulse;
  }

  return j1;
}

const computeImpulseDenominator_r0 = new Vec3();
const computeImpulseDenominator_c0 = new Vec3();
const computeImpulseDenominator_vec = new Vec3();
const computeImpulseDenominator_m = new Vec3();

function computeImpulseDenominator(body, pos, normal) {
  const r0 = computeImpulseDenominator_r0;
  const c0 = computeImpulseDenominator_c0;
  const vec = computeImpulseDenominator_vec;
  const m = computeImpulseDenominator_m;
  pos.vsub(body.position, r0);
  r0.cross(normal, c0);
  body.invInertiaWorld.vmult(c0, m);
  m.cross(r0, vec);
  return body.invMass + normal.dot(vec);
}

const resolveSingleBilateral_vel1 = new Vec3();
const resolveSingleBilateral_vel2 = new Vec3();
const resolveSingleBilateral_vel = new Vec3(); // bilateral constraint between two dynamic objects

function resolveSingleBilateral(body1, pos1, body2, pos2, normal) {
  const normalLenSqr = normal.lengthSquared();

  if (normalLenSqr > 1.1) {
    return 0; // no impulse
  } // const rel_pos1 = new Vec3();
  // const rel_pos2 = new Vec3();
  // pos1.vsub(body1.position, rel_pos1);
  // pos2.vsub(body2.position, rel_pos2);


  const vel1 = resolveSingleBilateral_vel1;
  const vel2 = resolveSingleBilateral_vel2;
  const vel = resolveSingleBilateral_vel;
  body1.getVelocityAtWorldPoint(pos1, vel1);
  body2.getVelocityAtWorldPoint(pos2, vel2);
  vel1.vsub(vel2, vel);
  const rel_vel = normal.dot(vel);
  const contactDamping = 0.2;
  const massTerm = 1 / (body1.invMass + body2.invMass);
  const impulse = -contactDamping * rel_vel * massTerm;
  return impulse;
}

/**
 * Spherical shape
 * @example
 *     const radius = 1
 *     const sphereShape = new CANNON.Sphere(radius)
 *     const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape })
 *     world.addBody(sphereBody)
 */
class Sphere extends Shape {
  /**
   * The radius of the sphere.
   */

  /**
   *
   * @param radius The radius of the sphere, a non-negative number.
   */
  constructor(radius) {
    super({
      type: Shape.types.SPHERE
    });
    this.radius = void 0;
    this.radius = radius !== undefined ? radius : 1.0;

    if (this.radius < 0) {
      throw new Error('The sphere radius cannot be negative.');
    }

    this.updateBoundingSphereRadius();
  }
  /** calculateLocalInertia */


  calculateLocalInertia(mass, target = new Vec3()) {
    const I = 2.0 * mass * this.radius * this.radius / 5.0;
    target.x = I;
    target.y = I;
    target.z = I;
    return target;
  }
  /** volume */


  volume() {
    return 4.0 * Math.PI * Math.pow(this.radius, 3) / 3.0;
  }

  updateBoundingSphereRadius() {
    this.boundingSphereRadius = this.radius;
  }

  calculateWorldAABB(pos, quat, min, max) {
    const r = this.radius;
    const axes = ['x', 'y', 'z'];

    for (let i = 0; i < axes.length; i++) {
      const ax = axes[i];
      min[ax] = pos[ax] - r;
      max[ax] = pos[ax] + r;
    }
  }

}

/**
 * Simple vehicle helper class with spherical rigid body wheels.
 */
class RigidVehicle {
  /**
   * The bodies of the wheels.
   */

  /**
   * The chassis body.
   */

  /**
   * The constraints.
   */

  /**
   * The wheel axes.
   */

  /**
   * The wheel forces.
   */
  constructor(options = {}) {
    this.wheelBodies = void 0;
    this.coordinateSystem = void 0;
    this.chassisBody = void 0;
    this.constraints = void 0;
    this.wheelAxes = void 0;
    this.wheelForces = void 0;
    this.wheelBodies = [];
    this.coordinateSystem = typeof options.coordinateSystem !== 'undefined' ? options.coordinateSystem.clone() : new Vec3(1, 2, 3);

    if (options.chassisBody) {
      this.chassisBody = options.chassisBody;
    } else {
      // No chassis body given. Create it!
      this.chassisBody = new Body({
        mass: 1,
        shape: new Box(new Vec3(5, 0.5, 2))
      });
    }

    this.constraints = [];
    this.wheelAxes = [];
    this.wheelForces = [];
  }
  /**
   * Add a wheel
   */


  addWheel(options = {}) {
    let wheelBody;

    if (options.body) {
      wheelBody = options.body;
    } else {
      // No wheel body given. Create it!
      wheelBody = new Body({
        mass: 1,
        shape: new Sphere(1.2)
      });
    }

    this.wheelBodies.push(wheelBody);
    this.wheelForces.push(0); // Position constrain wheels

    const position = typeof options.position !== 'undefined' ? options.position.clone() : new Vec3(); // Set position locally to the chassis

    const worldPosition = new Vec3();
    this.chassisBody.pointToWorldFrame(position, worldPosition);
    wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); // Constrain wheel

    const axis = typeof options.axis !== 'undefined' ? options.axis.clone() : new Vec3(0, 0, 1);
    this.wheelAxes.push(axis);
    const hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
      pivotA: position,
      axisA: axis,
      pivotB: Vec3.ZERO,
      axisB: axis,
      collideConnected: false
    });
    this.constraints.push(hingeConstraint);
    return this.wheelBodies.length - 1;
  }
  /**
   * Set the steering value of a wheel.
   * @todo check coordinateSystem
   */


  setSteeringValue(value, wheelIndex) {
    // Set angle of the hinge axis
    const axis = this.wheelAxes[wheelIndex];
    const c = Math.cos(value);
    const s = Math.sin(value);
    const x = axis.x;
    const z = axis.z;
    this.constraints[wheelIndex].axisA.set(-c * x + s * z, 0, s * x + c * z);
  }
  /**
   * Set the target rotational speed of the hinge constraint.
   */


  setMotorSpeed(value, wheelIndex) {
    const hingeConstraint = this.constraints[wheelIndex];
    hingeConstraint.enableMotor();
    hingeConstraint.motorTargetVelocity = value;
  }
  /**
   * Set the target rotational speed of the hinge constraint.
   */


  disableMotor(wheelIndex) {
    const hingeConstraint = this.constraints[wheelIndex];
    hingeConstraint.disableMotor();
  }
  /**
   * Set the wheel force to apply on one of the wheels each time step
   */


  setWheelForce(value, wheelIndex) {
    this.wheelForces[wheelIndex] = value;
  }
  /**
   * Apply a torque on one of the wheels.
   */


  applyWheelForce(value, wheelIndex) {
    const axis = this.wheelAxes[wheelIndex];
    const wheelBody = this.wheelBodies[wheelIndex];
    const bodyTorque = wheelBody.torque;
    axis.scale(value, torque);
    wheelBody.vectorToWorldFrame(torque, torque);
    bodyTorque.vadd(torque, bodyTorque);
  }
  /**
   * Add the vehicle including its constraints to the world.
   */


  addToWorld(world) {
    const constraints = this.constraints;
    const bodies = this.wheelBodies.concat([this.chassisBody]);

    for (let i = 0; i < bodies.length; i++) {
      world.addBody(bodies[i]);
    }

    for (let i = 0; i < constraints.length; i++) {
      world.addConstraint(constraints[i]);
    }

    world.addEventListener('preStep', this._update.bind(this));
  }

  _update() {
    const wheelForces = this.wheelForces;

    for (let i = 0; i < wheelForces.length; i++) {
      this.applyWheelForce(wheelForces[i], i);
    }
  }
  /**
   * Remove the vehicle including its constraints from the world.
   */


  removeFromWorld(world) {
    const constraints = this.constraints;
    const bodies = this.wheelBodies.concat([this.chassisBody]);

    for (let i = 0; i < bodies.length; i++) {
      world.removeBody(bodies[i]);
    }

    for (let i = 0; i < constraints.length; i++) {
      world.removeConstraint(constraints[i]);
    }
  }
  /**
   * Get current rotational velocity of a wheel
   */


  getWheelSpeed(wheelIndex) {
    const axis = this.wheelAxes[wheelIndex];
    const wheelBody = this.wheelBodies[wheelIndex];
    const w = wheelBody.angularVelocity;
    this.chassisBody.vectorToWorldFrame(axis, worldAxis);
    return w.dot(worldAxis);
  }

}
const torque = new Vec3();
const worldAxis = new Vec3();

/**
 * Smoothed-particle hydrodynamics system
 * @todo Make parameters customizable in the constructor
 */
class SPHSystem {
  /**
   * The particles array.
   */

  /**
   * Density of the system (kg/m3).
   * @default 1
   */

  /**
   * Distance below which two particles are considered to be neighbors.
   * It should be adjusted so there are about 15-20 neighbor particles within this radius.
   * @default 1
   */

  /**
   * @default 1
   */

  /**
   * Viscosity of the system.
   * @default 0.01
   */

  /**
   * @default 0.000001
   */
  constructor() {
    this.particles = void 0;
    this.density = void 0;
    this.smoothingRadius = void 0;
    this.speedOfSound = void 0;
    this.viscosity = void 0;
    this.eps = void 0;
    this.pressures = void 0;
    this.densities = void 0;
    this.neighbors = void 0;
    this.particles = [];
    this.density = 1;
    this.smoothingRadius = 1;
    this.speedOfSound = 1;
    this.viscosity = 0.01;
    this.eps = 0.000001; // Stuff Computed per particle

    this.pressures = [];
    this.densities = [];
    this.neighbors = [];
  }
  /**
   * Add a particle to the system.
   */


  add(particle) {
    this.particles.push(particle);

    if (this.neighbors.length < this.particles.length) {
      this.neighbors.push([]);
    }
  }
  /**
   * Remove a particle from the system.
   */


  remove(particle) {
    const idx = this.particles.indexOf(particle);

    if (idx !== -1) {
      this.particles.splice(idx, 1);

      if (this.neighbors.length > this.particles.length) {
        this.neighbors.pop();
      }
    }
  }
  /**
   * Get neighbors within smoothing volume, save in the array neighbors
   */


  getNeighbors(particle, neighbors) {
    const N = this.particles.length;
    const id = particle.id;
    const R2 = this.smoothingRadius * this.smoothingRadius;
    const dist = SPHSystem_getNeighbors_dist;

    for (let i = 0; i !== N; i++) {
      const p = this.particles[i];
      p.position.vsub(particle.position, dist);

      if (id !== p.id && dist.lengthSquared() < R2) {
        neighbors.push(p);
      }
    }
  }

  update() {
    const N = this.particles.length;
    const dist = SPHSystem_update_dist;
    const cs = this.speedOfSound;
    const eps = this.eps;

    for (let i = 0; i !== N; i++) {
      const p = this.particles[i]; // Current particle

      const neighbors = this.neighbors[i]; // Get neighbors

      neighbors.length = 0;
      this.getNeighbors(p, neighbors);
      neighbors.push(this.particles[i]); // Add current too

      const numNeighbors = neighbors.length; // Accumulate density for the particle

      let sum = 0.0;

      for (let j = 0; j !== numNeighbors; j++) {
        //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
        p.position.vsub(neighbors[j].position, dist);
        const len = dist.length();
        const weight = this.w(len);
        sum += neighbors[j].mass * weight;
      } // Save


      this.densities[i] = sum;
      this.pressures[i] = cs * cs * (this.densities[i] - this.density);
    } // Add forces
    // Sum to these accelerations


    const a_pressure = SPHSystem_update_a_pressure;
    const a_visc = SPHSystem_update_a_visc;
    const gradW = SPHSystem_update_gradW;
    const r_vec = SPHSystem_update_r_vec;
    const u = SPHSystem_update_u;

    for (let i = 0; i !== N; i++) {
      const particle = this.particles[i];
      a_pressure.set(0, 0, 0);
      a_visc.set(0, 0, 0); // Init vars

      let Pij;
      let nabla;

      const neighbors = this.neighbors[i];
      const numNeighbors = neighbors.length; //printf("Neighbors: ");

      for (let j = 0; j !== numNeighbors; j++) {
        const neighbor = neighbors[j]; //printf("%d ",nj);
        // Get r once for all..

        particle.position.vsub(neighbor.position, r_vec);
        const r = r_vec.length(); // Pressure contribution

        Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i] * this.densities[i] + eps) + this.pressures[j] / (this.densities[j] * this.densities[j] + eps));
        this.gradw(r_vec, gradW); // Add to pressure acceleration

        gradW.scale(Pij, gradW);
        a_pressure.vadd(gradW, a_pressure); // Viscosity contribution

        neighbor.velocity.vsub(particle.velocity, u);
        u.scale(1.0 / (0.0001 + this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass, u);
        nabla = this.nablaw(r);
        u.scale(nabla, u); // Add to viscosity acceleration

        a_visc.vadd(u, a_visc);
      } // Calculate force


      a_visc.scale(particle.mass, a_visc);
      a_pressure.scale(particle.mass, a_pressure); // Add force to particles

      particle.force.vadd(a_visc, particle.force);
      particle.force.vadd(a_pressure, particle.force);
    }
  } // Calculate the weight using the W(r) weightfunction


  w(r) {
    // 315
    const h = this.smoothingRadius;
    return 315.0 / (64.0 * Math.PI * h ** 9) * (h * h - r * r) ** 3;
  } // calculate gradient of the weight function


  gradw(rVec, resultVec) {
    const r = rVec.length();
    const h = this.smoothingRadius;
    rVec.scale(945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) ** 2, resultVec);
  } // Calculate nabla(W)


  nablaw(r) {
    const h = this.smoothingRadius;
    const nabla = 945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) * (7 * r * r - 3 * h * h);
    return nabla;
  }

}
const SPHSystem_getNeighbors_dist = new Vec3(); // Temp vectors for calculation

const SPHSystem_update_dist = new Vec3(); // Relative velocity

const SPHSystem_update_a_pressure = new Vec3();
const SPHSystem_update_a_visc = new Vec3();
const SPHSystem_update_gradW = new Vec3();
const SPHSystem_update_r_vec = new Vec3();
const SPHSystem_update_u = new Vec3();

/**
 * Cylinder class.
 * @example
 *     const radiusTop = 0.5
 *     const radiusBottom = 0.5
 *     const height = 2
 *     const numSegments = 12
 *     const cylinderShape = new CANNON.Cylinder(radiusTop, radiusBottom, height, numSegments)
 *     const cylinderBody = new CANNON.Body({ mass: 1, shape: cylinderShape })
 *     world.addBody(cylinderBody)
 */

class Cylinder extends ConvexPolyhedron {
  /** The radius of the top of the Cylinder. */

  /** The radius of the bottom of the Cylinder. */

  /** The height of the Cylinder. */

  /** The number of segments to build the cylinder out of. */

  /**
   * @param radiusTop The radius of the top of the Cylinder.
   * @param radiusBottom The radius of the bottom of the Cylinder.
   * @param height The height of the Cylinder.
   * @param numSegments The number of segments to build the cylinder out of.
   */
  constructor(radiusTop = 1, radiusBottom = 1, height = 1, numSegments = 8) {
    if (radiusTop < 0) {
      throw new Error('The cylinder radiusTop cannot be negative.');
    }

    if (radiusBottom < 0) {
      throw new Error('The cylinder radiusBottom cannot be negative.');
    }

    const N = numSegments;
    const vertices = [];
    const axes = [];
    const faces = [];
    const bottomface = [];
    const topface = [];
    const cos = Math.cos;
    const sin = Math.sin; // First bottom point

    vertices.push(new Vec3(-radiusBottom * sin(0), -height * 0.5, radiusBottom * cos(0)));
    bottomface.push(0); // First top point

    vertices.push(new Vec3(-radiusTop * sin(0), height * 0.5, radiusTop * cos(0)));
    topface.push(1);

    for (let i = 0; i < N; i++) {
      const theta = 2 * Math.PI / N * (i + 1);
      const thetaN = 2 * Math.PI / N * (i + 0.5);

      if (i < N - 1) {
        // Bottom
        vertices.push(new Vec3(-radiusBottom * sin(theta), -height * 0.5, radiusBottom * cos(theta)));
        bottomface.push(2 * i + 2); // Top

        vertices.push(new Vec3(-radiusTop * sin(theta), height * 0.5, radiusTop * cos(theta)));
        topface.push(2 * i + 3); // Face

        faces.push([2 * i, 2 * i + 1, 2 * i + 3, 2 * i + 2]);
      } else {
        faces.push([2 * i, 2 * i + 1, 1, 0]); // Connect
      } // Axis: we can cut off half of them if we have even number of segments


      if (N % 2 === 1 || i < N / 2) {
        axes.push(new Vec3(-sin(thetaN), 0, cos(thetaN)));
      }
    }

    faces.push(bottomface);
    axes.push(new Vec3(0, 1, 0)); // Reorder top face

    const temp = [];

    for (let i = 0; i < topface.length; i++) {
      temp.push(topface[topface.length - i - 1]);
    }

    faces.push(temp);
    super({
      vertices,
      faces,
      axes
    });
    this.radiusTop = void 0;
    this.radiusBottom = void 0;
    this.height = void 0;
    this.numSegments = void 0;
    this.type = Shape.types.CYLINDER;
    this.radiusTop = radiusTop;
    this.radiusBottom = radiusBottom;
    this.height = height;
    this.numSegments = numSegments;
  }

}

/**
 * Particle shape.
 * @example
 *     const particleShape = new CANNON.Particle()
 *     const particleBody = new CANNON.Body({ mass: 1, shape: particleShape })
 *     world.addBody(particleBody)
 */
class Particle extends Shape {
  constructor() {
    super({
      type: Shape.types.PARTICLE
    });
  }
  /**
   * calculateLocalInertia
   */


  calculateLocalInertia(mass, target = new Vec3()) {
    target.set(0, 0, 0);
    return target;
  }

  volume() {
    return 0;
  }

  updateBoundingSphereRadius() {
    this.boundingSphereRadius = 0;
  }

  calculateWorldAABB(pos, quat, min, max) {
    // Get each axis max
    min.copy(pos);
    max.copy(pos);
  }

}

/**
 * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a Body and rotate that body. See the demos.
 * @example
 *     const planeShape = new CANNON.Plane()
 *     const planeBody = new CANNON.Body({ mass: 0, shape:  planeShape })
 *     planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up
 *     world.addBody(planeBody)
 */
class Plane extends Shape {
  /** worldNormal */

  /** worldNormalNeedsUpdate */
  constructor() {
    super({
      type: Shape.types.PLANE
    }); // World oriented normal

    this.worldNormal = void 0;
    this.worldNormalNeedsUpdate = void 0;
    this.boundingSphereRadius = void 0;
    this.worldNormal = new Vec3();
    this.worldNormalNeedsUpdate = true;
    this.boundingSphereRadius = Number.MAX_VALUE;
  }
  /** computeWorldNormal */


  computeWorldNormal(quat) {
    const n = this.worldNormal;
    n.set(0, 0, 1);
    quat.vmult(n, n);
    this.worldNormalNeedsUpdate = false;
  }

  calculateLocalInertia(mass, target = new Vec3()) {
    return target;
  }

  volume() {
    return (// The plane is infinite...
      Number.MAX_VALUE
    );
  }

  calculateWorldAABB(pos, quat, min, max) {
    // The plane AABB is infinite, except if the normal is pointing along any axis
    tempNormal.set(0, 0, 1); // Default plane normal is z

    quat.vmult(tempNormal, tempNormal);
    const maxVal = Number.MAX_VALUE;
    min.set(-maxVal, -maxVal, -maxVal);
    max.set(maxVal, maxVal, maxVal);

    if (tempNormal.x === 1) {
      max.x = pos.x;
    } else if (tempNormal.x === -1) {
      min.x = pos.x;
    }

    if (tempNormal.y === 1) {
      max.y = pos.y;
    } else if (tempNormal.y === -1) {
      min.y = pos.y;
    }

    if (tempNormal.z === 1) {
      max.z = pos.z;
    } else if (tempNormal.z === -1) {
      min.z = pos.z;
    }
  }

  updateBoundingSphereRadius() {
    this.boundingSphereRadius = Number.MAX_VALUE;
  }

}
const tempNormal = new Vec3();

/**
 * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
 * @todo Should be possible to use along all axes, not just y
 * @todo should be possible to scale along all axes
 * @todo Refactor elementSize to elementSizeX and elementSizeY
 *
 * @example
 *     // Generate some height data (y-values).
 *     const data = []
 *     for (let i = 0; i < 1000; i++) {
 *         const y = 0.5 * Math.cos(0.2 * i)
 *         data.push(y)
 *     }
 *
 *     // Create the heightfield shape
 *     const heightfieldShape = new CANNON.Heightfield(data, {
 *         elementSize: 1 // Distance between the data points in X and Y directions
 *     })
 *     const heightfieldBody = new CANNON.Body({ shape: heightfieldShape })
 *     world.addBody(heightfieldBody)
 */
class Heightfield extends Shape {
  /**
   * An array of numbers, or height values, that are spread out along the x axis.
   */

  /**
   * Max value of the data points in the data array.
   */

  /**
   * Minimum value of the data points in the data array.
   */

  /**
   * World spacing between the data points in X and Y direction.
   * @todo elementSizeX and Y
   * @default 1
   */

  /**
   * @default true
   */

  /**
   * @param data An array of numbers, or height values, that are spread out along the x axis.
   */
  constructor(data, options = {}) {
    options = Utils.defaults(options, {
      maxValue: null,
      minValue: null,
      elementSize: 1
    });
    super({
      type: Shape.types.HEIGHTFIELD
    });
    this.data = void 0;
    this.maxValue = void 0;
    this.minValue = void 0;
    this.elementSize = void 0;
    this.cacheEnabled = void 0;
    this.pillarConvex = void 0;
    this.pillarOffset = void 0;
    this._cachedPillars = void 0;
    this.data = data;
    this.maxValue = options.maxValue;
    this.minValue = options.minValue;
    this.elementSize = options.elementSize;

    if (options.minValue === null) {
      this.updateMinValue();
    }

    if (options.maxValue === null) {
      this.updateMaxValue();
    }

    this.cacheEnabled = true;
    this.pillarConvex = new ConvexPolyhedron();
    this.pillarOffset = new Vec3();
    this.updateBoundingSphereRadius(); // "i_j_isUpper" => { convex: ..., offset: ... }
    // for example:
    // _cachedPillars["0_2_1"]

    this._cachedPillars = {};
  }
  /**
   * Call whenever you change the data array.
   */


  update() {
    this._cachedPillars = {};
  }
  /**
   * Update the `minValue` property
   */


  updateMinValue() {
    const data = this.data;
    let minValue = data[0][0];

    for (let i = 0; i !== data.length; i++) {
      for (let j = 0; j !== data[i].length; j++) {
        const v = data[i][j];

        if (v < minValue) {
          minValue = v;
        }
      }
    }

    this.minValue = minValue;
  }
  /**
   * Update the `maxValue` property
   */


  updateMaxValue() {
    const data = this.data;
    let maxValue = data[0][0];

    for (let i = 0; i !== data.length; i++) {
      for (let j = 0; j !== data[i].length; j++) {
        const v = data[i][j];

        if (v > maxValue) {
          maxValue = v;
        }
      }
    }

    this.maxValue = maxValue;
  }
  /**
   * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
   */


  setHeightValueAtIndex(xi, yi, value) {
    const data = this.data;
    data[xi][yi] = value; // Invalidate cache

    this.clearCachedConvexTrianglePillar(xi, yi, false);

    if (xi > 0) {
      this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
      this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
    }

    if (yi > 0) {
      this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
      this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
    }

    if (yi > 0 && xi > 0) {
      this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
    }
  }
  /**
   * Get max/min in a rectangle in the matrix data
   * @param result An array to store the results in.
   * @return The result array, if it was passed in. Minimum will be at position 0 and max at 1.
   */


  getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, result = []) {
    // Get max and min of the data
    const data = this.data; // Set first value

    let max = this.minValue;

    for (let i = iMinX; i <= iMaxX; i++) {
      for (let j = iMinY; j <= iMaxY; j++) {
        const height = data[i][j];

        if (height > max) {
          max = height;
        }
      }
    }

    result[0] = this.minValue;
    result[1] = max;
  }
  /**
   * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.
   * @param result Two-element array
   * @param clamp If the position should be clamped to the heightfield edge.
   */


  getIndexOfPosition(x, y, result, clamp) {
    // Get the index of the data points to test against
    const w = this.elementSize;
    const data = this.data;
    let xi = Math.floor(x / w);
    let yi = Math.floor(y / w);
    result[0] = xi;
    result[1] = yi;

    if (clamp) {
      // Clamp index to edges
      if (xi < 0) {
        xi = 0;
      }

      if (yi < 0) {
        yi = 0;
      }

      if (xi >= data.length - 1) {
        xi = data.length - 1;
      }

      if (yi >= data[0].length - 1) {
        yi = data[0].length - 1;
      }
    } // Bail out if we are out of the terrain


    if (xi < 0 || yi < 0 || xi >= data.length - 1 || yi >= data[0].length - 1) {
      return false;
    }

    return true;
  }

  getTriangleAt(x, y, edgeClamp, a, b, c) {
    const idx = getHeightAt_idx;
    this.getIndexOfPosition(x, y, idx, edgeClamp);
    let xi = idx[0];
    let yi = idx[1];
    const data = this.data;

    if (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;
    const lowerDist2 = (x / elementSize - xi) ** 2 + (y / elementSize - yi) ** 2;
    const upperDist2 = (x / elementSize - (xi + 1)) ** 2 + (y / elementSize - (yi + 1)) ** 2;
    const upper = lowerDist2 > upperDist2;
    this.getTriangle(xi, yi, upper, a, b, c);
    return upper;
  }

  getNormalAt(x, y, edgeClamp, result) {
    const a = getNormalAt_a;
    const b = getNormalAt_b;
    const c = getNormalAt_c;
    const e0 = getNormalAt_e0;
    const 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();
  }
  /**
   * Get an AABB of a square in the heightfield
   * @param xi
   * @param yi
   * @param result
   */


  getAabbAtIndex(xi, yi, {
    lowerBound,
    upperBound
  }) {
    const data = this.data;
    const 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]);
  }
  /**
   * Get the height in the heightfield at a given position
   */


  getHeightAt(x, y, edgeClamp) {
    const data = this.data;
    const a = getHeightAt_a;
    const b = getHeightAt_b;
    const c = getHeightAt_c;
    const idx = getHeightAt_idx;
    this.getIndexOfPosition(x, y, idx, edgeClamp);
    let xi = idx[0];
    let yi = idx[1];

    if (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);
    barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);
    const w = getHeightAt_weights;

    if (upper) {
      // Top triangle verts
      return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;
    } else {
      // Top triangle verts
      return 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,
      offset
    };
  }

  clearCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {
    delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  }
  /**
   * Get a triangle from the heightfield
   */


  getTriangle(xi, yi, upper, a, b, c) {
    const data = this.data;
    const elementSize = this.elementSize;

    if (upper) {
      // Top triangle verts
      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]);
    } else {
      // Top triangle verts
      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]);
    }
  }
  /**
   * Get a triangle in the terrain in the form of a triangular convex shape.
   */


  getConvexTrianglePillar(xi, yi, getUpperTriangle) {
    let result = this.pillarConvex;
    let offsetResult = this.pillarOffset;

    if (this.cacheEnabled) {
      const data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);

      if (data) {
        this.pillarConvex = data.convex;
        this.pillarOffset = data.offset;
        return;
      }

      result = new ConvexPolyhedron();
      offsetResult = new Vec3();
      this.pillarConvex = result;
      this.pillarOffset = offsetResult;
    }

    const data = this.data;
    const elementSize = this.elementSize;
    const faces = result.faces; // Reuse verts if possible

    result.vertices.length = 6;

    for (let i = 0; i < 6; i++) {
      if (!result.vertices[i]) {
        result.vertices[i] = new Vec3();
      }
    } // Reuse faces if possible


    faces.length = 5;

    for (let i = 0; i < 5; i++) {
      if (!faces[i]) {
        faces[i] = [];
      }
    }

    const verts = result.vertices;
    const h = (Math.min(data[xi][yi], data[xi + 1][yi], data[xi][yi + 1], data[xi + 1][yi + 1]) - this.minValue) / 2 + this.minValue;

    if (!getUpperTriangle) {
      // Center of the triangle pillar - all polygons are given relative to this one
      offsetResult.set((xi + 0.25) * elementSize, // sort of center of a triangle
      (yi + 0.25) * elementSize, h // vertical center
      ); // Top triangle verts

      verts[0].set(-0.25 * elementSize, -0.25 * elementSize, data[xi][yi] - h);
      verts[1].set(0.75 * elementSize, -0.25 * elementSize, data[xi + 1][yi] - h);
      verts[2].set(-0.25 * elementSize, 0.75 * elementSize, data[xi][yi + 1] - h); // bottom triangle verts

      verts[3].set(-0.25 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
      verts[4].set(0.75 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
      verts[5].set(-0.25 * elementSize, 0.75 * elementSize, -Math.abs(h) - 1); // top triangle

      faces[0][0] = 0;
      faces[0][1] = 1;
      faces[0][2] = 2; // bottom triangle

      faces[1][0] = 5;
      faces[1][1] = 4;
      faces[1][2] = 3; // -x facing quad

      faces[2][0] = 0;
      faces[2][1] = 2;
      faces[2][2] = 5;
      faces[2][3] = 3; // -y facing quad

      faces[3][0] = 1;
      faces[3][1] = 0;
      faces[3][2] = 3;
      faces[3][3] = 4; // +xy facing quad

      faces[4][0] = 4;
      faces[4][1] = 5;
      faces[4][2] = 2;
      faces[4][3] = 1;
    } else {
      // Center of the triangle pillar - all polygons are given relative to this one
      offsetResult.set((xi + 0.75) * elementSize, // sort of center of a triangle
      (yi + 0.75) * elementSize, h // vertical center
      ); // Top triangle verts

      verts[0].set(0.25 * elementSize, 0.25 * elementSize, data[xi + 1][yi + 1] - h);
      verts[1].set(-0.75 * elementSize, 0.25 * elementSize, data[xi][yi + 1] - h);
      verts[2].set(0.25 * elementSize, -0.75 * elementSize, data[xi + 1][yi] - h); // bottom triangle verts

      verts[3].set(0.25 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
      verts[4].set(-0.75 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
      verts[5].set(0.25 * elementSize, -0.75 * elementSize, -Math.abs(h) - 1); // Top triangle

      faces[0][0] = 0;
      faces[0][1] = 1;
      faces[0][2] = 2; // bottom triangle

      faces[1][0] = 5;
      faces[1][1] = 4;
      faces[1][2] = 3; // +x facing quad

      faces[2][0] = 2;
      faces[2][1] = 5;
      faces[2][2] = 3;
      faces[2][3] = 0; // +y facing quad

      faces[3][0] = 3;
      faces[3][1] = 4;
      faces[3][2] = 1;
      faces[3][3] = 0; // -xy facing quad

      faces[4][0] = 1;
      faces[4][1] = 4;
      faces[4][2] = 5;
      faces[4][3] = 2;
    }

    result.computeNormals();
    result.computeEdges();
    result.updateBoundingSphereRadius();
    this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  }

  calculateLocalInertia(mass, target = new Vec3()) {
    target.set(0, 0, 0);
    return target;
  }

  volume() {
    return (// The terrain is infinite
      Number.MAX_VALUE
    );
  }

  calculateWorldAABB(pos, quat, min, max) {
    /** @TODO do it properly */
    min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  }

  updateBoundingSphereRadius() {
    // Use the bounding box of the min/max values
    const data = this.data;
    const 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();
  }
  /**
   * Sets the height values from an image. Currently only supported in browser.
   */


  setHeightsFromImage(image, scale) {
    const {
      x,
      z,
      y
    } = scale;
    const 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);
    const matrix = this.data;
    matrix.length = 0;
    this.elementSize = Math.abs(x) / imageData.width;

    for (let i = 0; i < imageData.height; i++) {
      const row = [];

      for (let j = 0; j < imageData.width; j++) {
        const a = imageData.data[(i * imageData.height + j) * 4];
        const b = imageData.data[(i * imageData.height + j) * 4 + 1];
        const c = imageData.data[(i * imageData.height + j) * 4 + 2];
        const height = (a + b + c) / 4 / 255 * z;

        if (x < 0) {
          row.push(height);
        } else {
          row.unshift(height);
        }
      }

      if (y < 0) {
        matrix.unshift(row);
      } else {
        matrix.push(row);
      }
    }

    this.updateMaxValue();
    this.updateMinValue();
    this.update();
  }

}
const getHeightAt_idx = [];
const getHeightAt_weights = new Vec3();
const getHeightAt_a = new Vec3();
const getHeightAt_b = new Vec3();
const getHeightAt_c = new Vec3();
const getNormalAt_a = new Vec3();
const getNormalAt_b = new Vec3();
const getNormalAt_c = new Vec3();
const getNormalAt_e0 = new Vec3();
const getNormalAt_e1 = new Vec3(); // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system

function barycentricWeights(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;
}

/**
 * OctreeNode
 */
class OctreeNode {
  /** The root node */

  /** Boundary of this node */

  /** Contained data at the current node level */

  /** Children to this node */
  constructor(options = {}) {
    this.root = void 0;
    this.aabb = void 0;
    this.data = void 0;
    this.children = void 0;
    this.root = options.root || null;
    this.aabb = options.aabb ? options.aabb.clone() : new AABB();
    this.data = [];
    this.children = [];
  }
  /**
   * reset
   */


  reset() {
    this.children.length = this.data.length = 0;
  }
  /**
   * Insert data into this node
   * @return True if successful, otherwise false
   */


  insert(aabb, elementData, level = 0) {
    const nodeData = this.data; // Ignore objects that do not belong in this node

    if (!this.aabb.contains(aabb)) {
      return false; // object cannot be added
    }

    const children = this.children;
    const maxDepth = this.maxDepth || this.root.maxDepth;

    if (level < maxDepth) {
      // Subdivide if there are no children yet
      let subdivided = false;

      if (!children.length) {
        this.subdivide();
        subdivided = true;
      } // add to whichever node will accept it


      for (let i = 0; i !== 8; i++) {
        if (children[i].insert(aabb, elementData, level + 1)) {
          return true;
        }
      }

      if (subdivided) {
        // No children accepted! Might as well just remove em since they contain none
        children.length = 0;
      }
    } // Too deep, or children didnt want it. add it in current node


    nodeData.push(elementData);
    return true;
  }
  /**
   * Create 8 equally sized children nodes and put them in the `children` array.
   */


  subdivide() {
    const aabb = this.aabb;
    const l = aabb.lowerBound;
    const u = aabb.upperBound;
    const children = this.children;
    children.push(new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(0, 0, 0)
      })
    }), new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(1, 0, 0)
      })
    }), new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(1, 1, 0)
      })
    }), new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(1, 1, 1)
      })
    }), new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(0, 1, 1)
      })
    }), new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(0, 0, 1)
      })
    }), new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(1, 0, 1)
      })
    }), new OctreeNode({
      aabb: new AABB({
        lowerBound: new Vec3(0, 1, 0)
      })
    }));
    u.vsub(l, halfDiagonal);
    halfDiagonal.scale(0.5, halfDiagonal);
    const root = this.root || this;

    for (let i = 0; i !== 8; i++) {
      const child = children[i]; // Set current node as root

      child.root = root; // Compute bounds

      const lowerBound = child.aabb.lowerBound;
      lowerBound.x *= halfDiagonal.x;
      lowerBound.y *= halfDiagonal.y;
      lowerBound.z *= halfDiagonal.z;
      lowerBound.vadd(l, lowerBound); // Upper bound is always lower bound + halfDiagonal

      lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
    }
  }
  /**
   * Get all data, potentially within an AABB
   * @return The "result" object
   */


  aabbQuery(aabb, result) {
    this.data; // abort if the range does not intersect this node
    // if (!this.aabb.overlaps(aabb)){
    //     return result;
    // }
    // Add objects at this level
    // Array.prototype.push.apply(result, nodeData);
    // Add child data
    // @todo unwrap recursion into a queue / loop, that's faster in JS

    this.children; // for (let i = 0, N = this.children.length; i !== N; i++) {
    //     children[i].aabbQuery(aabb, result);
    // }

    const queue = [this];

    while (queue.length) {
      const node = queue.pop();

      if (node.aabb.overlaps(aabb)) {
        Array.prototype.push.apply(result, node.data);
      }

      Array.prototype.push.apply(queue, node.children);
    }

    return result;
  }
  /**
   * Get all data, potentially intersected by a ray.
   * @return The "result" object
   */


  rayQuery(ray, treeTransform, result) {
    // Use aabb query for now.

    /** @todo implement real ray query which needs less lookups */
    ray.getAABB(tmpAABB);
    tmpAABB.toLocalFrame(treeTransform, tmpAABB);
    this.aabbQuery(tmpAABB, result);
    return result;
  }
  /**
   * removeEmptyNodes
   */


  removeEmptyNodes() {
    for (let i = this.children.length - 1; i >= 0; i--) {
      this.children[i].removeEmptyNodes();

      if (!this.children[i].children.length && !this.children[i].data.length) {
        this.children.splice(i, 1);
      }
    }
  }

}
/**
 * Octree
 */


class Octree extends OctreeNode {
  /**
   * Maximum subdivision depth
   * @default 8
   */

  /**
   * @param aabb The total AABB of the tree
   */
  constructor(aabb, options = {}) {
    super({
      root: null,
      aabb
    });
    this.maxDepth = void 0;
    this.maxDepth = typeof options.maxDepth !== 'undefined' ? options.maxDepth : 8;
  }

}
const halfDiagonal = new Vec3();
const tmpAABB = new AABB();

/**
 * Trimesh.
 * @example
 *     // How to make a mesh with a single triangle
 *     const vertices = [
 *         0, 0, 0, // vertex 0
 *         1, 0, 0, // vertex 1
 *         0, 1, 0  // vertex 2
 *     ]
 *     const indices = [
 *         0, 1, 2  // triangle 0
 *     ]
 *     const trimeshShape = new CANNON.Trimesh(vertices, indices)
 */
class Trimesh extends Shape {
  /**
   * vertices
   */

  /**
   * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
   */

  /**
   * The normals data.
   */

  /**
   * The local AABB of the mesh.
   */

  /**
   * References to vertex pairs, making up all unique edges in the trimesh.
   */

  /**
   * Local scaling of the mesh. Use .setScale() to set it.
   */

  /**
   * The indexed triangles. Use .updateTree() to update it.
   */
  constructor(vertices, indices) {
    super({
      type: Shape.types.TRIMESH
    });
    this.vertices = void 0;
    this.indices = void 0;
    this.normals = void 0;
    this.aabb = void 0;
    this.edges = void 0;
    this.scale = void 0;
    this.tree = void 0;
    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
   */


  updateTree() {
    const tree = this.tree;
    tree.reset();
    tree.aabb.copy(this.aabb);
    const scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled

    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; // Insert all triangles

    const triangleAABB = new AABB();
    const a = new Vec3();
    const b = new Vec3();
    const c = new Vec3();
    const points = [a, b, c];

    for (let i = 0; i < this.indices.length / 3; i++) {
      //this.getTriangleVertices(i, a, b, c);
      // Get unscaled triangle verts
      const i3 = i * 3;

      this._getUnscaledVertex(this.indices[i3], a);

      this._getUnscaledVertex(this.indices[i3 + 1], b);

      this._getUnscaledVertex(this.indices[i3 + 2], c);

      triangleAABB.setFromPoints(points);
      tree.insert(triangleAABB, i);
    }

    tree.removeEmptyNodes();
  }
  /**
   * Get triangles in a local AABB from the trimesh.
   * @param result An array of integers, referencing the queried triangles.
   */


  getTrianglesInAABB(aabb, result) {
    unscaledAABB.copy(aabb); // Scale it to local

    const scale = this.scale;
    const isx = scale.x;
    const isy = scale.y;
    const isz = scale.z;
    const l = unscaledAABB.lowerBound;
    const u = unscaledAABB.upperBound;
    l.x /= isx;
    l.y /= isy;
    l.z /= isz;
    u.x /= isx;
    u.y /= isy;
    u.z /= isz;
    return this.tree.aabbQuery(unscaledAABB, result);
  }
  /**
   * setScale
   */


  setScale(scale) {
    const wasUniform = this.scale.x === this.scale.y && this.scale.y === this.scale.z;
    const isUniform = scale.x === scale.y && scale.y === scale.z;

    if (!(wasUniform && isUniform)) {
      // Non-uniform scaling. Need to update normals.
      this.updateNormals();
    }

    this.scale.copy(scale);
    this.updateAABB();
    this.updateBoundingSphereRadius();
  }
  /**
   * Compute the normals of the faces. Will save in the `.normals` array.
   */


  updateNormals() {
    const n = computeNormals_n; // Generate normals

    const normals = this.normals;

    for (let i = 0; i < this.indices.length / 3; i++) {
      const i3 = i * 3;
      const a = this.indices[i3];
      const b = this.indices[i3 + 1];
      const c = this.indices[i3 + 2];
      this.getVertex(a, va);
      this.getVertex(b, vb);
      this.getVertex(c, vc);
      Trimesh.computeNormal(vb, va, vc, n);
      normals[i3] = n.x;
      normals[i3 + 1] = n.y;
      normals[i3 + 2] = n.z;
    }
  }
  /**
   * Update the `.edges` property
   */


  updateEdges() {
    const edges = {};

    const add = (a, b) => {
      const key = a < b ? a + "_" + b : b + "_" + a;
      edges[key] = true;
    };

    for (let i = 0; i < this.indices.length / 3; i++) {
      const i3 = i * 3;
      const a = this.indices[i3];
      const b = this.indices[i3 + 1];
      const c = this.indices[i3 + 2];
      add(a, b);
      add(b, c);
      add(c, a);
    }

    const keys = Object.keys(edges);
    this.edges = new Int16Array(keys.length * 2);

    for (let i = 0; i < keys.length; i++) {
      const indices = keys[i].split('_');
      this.edges[2 * i] = parseInt(indices[0], 10);
      this.edges[2 * i + 1] = parseInt(indices[1], 10);
    }
  }
  /**
   * Get an edge vertex
   * @param firstOrSecond 0 or 1, depending on which one of the vertices you need.
   * @param vertexStore Where to store the result
   */


  getEdgeVertex(edgeIndex, firstOrSecond, vertexStore) {
    const vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
    this.getVertex(vertexIndex, vertexStore);
  }
  /**
   * Get a vector along an edge.
   */


  getEdgeVector(edgeIndex, vectorStore) {
    const va = getEdgeVector_va;
    const vb = getEdgeVector_vb;
    this.getEdgeVertex(edgeIndex, 0, va);
    this.getEdgeVertex(edgeIndex, 1, vb);
    vb.vsub(va, vectorStore);
  }
  /**
   * Get face normal given 3 vertices
   */


  static computeNormal(va, vb, vc, target) {
    vb.vsub(va, ab);
    vc.vsub(vb, cb);
    cb.cross(ab, target);

    if (!target.isZero()) {
      target.normalize();
    }
  }
  /**
   * Get vertex i.
   * @return The "out" vector object
   */


  getVertex(i, out) {
    const scale = this.scale;

    this._getUnscaledVertex(i, out);

    out.x *= scale.x;
    out.y *= scale.y;
    out.z *= scale.z;
    return out;
  }
  /**
   * Get raw vertex i
   * @return The "out" vector object
   */


  _getUnscaledVertex(i, out) {
    const i3 = i * 3;
    const vertices = this.vertices;
    return out.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]);
  }
  /**
   * Get a vertex from the trimesh,transformed by the given position and quaternion.
   * @return The "out" vector object
   */


  getWorldVertex(i, pos, quat, out) {
    this.getVertex(i, out);
    Transform.pointToWorldFrame(pos, quat, out, out);
    return out;
  }
  /**
   * Get the three vertices for triangle i.
   */


  getTriangleVertices(i, a, b, c) {
    const i3 = i * 3;
    this.getVertex(this.indices[i3], a);
    this.getVertex(this.indices[i3 + 1], b);
    this.getVertex(this.indices[i3 + 2], c);
  }
  /**
   * Compute the normal of triangle i.
   * @return The "target" vector object
   */


  getNormal(i, target) {
    const i3 = i * 3;
    return target.set(this.normals[i3], this.normals[i3 + 1], this.normals[i3 + 2]);
  }
  /**
   * @return The "target" vector object
   */


  calculateLocalInertia(mass, target) {
    // Approximate with box inertia
    // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
    this.computeLocalAABB(cli_aabb);
    const x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x;
    const y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y;
    const z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
    return target.set(1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x));
  }
  /**
   * Compute the local AABB for the trimesh
   */


  computeLocalAABB(aabb) {
    const l = aabb.lowerBound;
    const u = aabb.upperBound;
    const n = this.vertices.length;
    this.vertices;
    const v = computeLocalAABB_worldVert;
    this.getVertex(0, v);
    l.copy(v);
    u.copy(v);

    for (let i = 0; i !== n; i++) {
      this.getVertex(i, v);

      if (v.x < l.x) {
        l.x = v.x;
      } else if (v.x > u.x) {
        u.x = v.x;
      }

      if (v.y < l.y) {
        l.y = v.y;
      } else if (v.y > u.y) {
        u.y = v.y;
      }

      if (v.z < l.z) {
        l.z = v.z;
      } else if (v.z > u.z) {
        u.z = v.z;
      }
    }
  }
  /**
   * Update the `.aabb` property
   */


  updateAABB() {
    this.computeLocalAABB(this.aabb);
  }
  /**
   * Will update the `.boundingSphereRadius` property
   */


  updateBoundingSphereRadius() {
    // Assume points are distributed with local (0,0,0) as center
    let max2 = 0;
    const vertices = this.vertices;
    const v = new Vec3();

    for (let i = 0, N = vertices.length / 3; i !== N; i++) {
      this.getVertex(i, v);
      const norm2 = v.lengthSquared();

      if (norm2 > max2) {
        max2 = norm2;
      }
    }

    this.boundingSphereRadius = Math.sqrt(max2);
  }
  /**
   * calculateWorldAABB
   */


  calculateWorldAABB(pos, quat, min, max) {
    /*
        const n = this.vertices.length / 3,
            verts = this.vertices;
        const minx,miny,minz,maxx,maxy,maxz;
         const v = tempWorldVertex;
        for(let i=0; i<n; i++){
            this.getVertex(i, v);
            quat.vmult(v, v);
            pos.vadd(v, v);
            if (v.x < minx || minx===undefined){
                minx = v.x;
            } else if(v.x > maxx || maxx===undefined){
                maxx = v.x;
            }
             if (v.y < miny || miny===undefined){
                miny = v.y;
            } else if(v.y > maxy || maxy===undefined){
                maxy = v.y;
            }
             if (v.z < minz || minz===undefined){
                minz = v.z;
            } else if(v.z > maxz || maxz===undefined){
                maxz = v.z;
            }
        }
        min.set(minx,miny,minz);
        max.set(maxx,maxy,maxz);
        */
    // Faster approximation using local AABB
    const frame = calculateWorldAABB_frame;
    const result = calculateWorldAABB_aabb;
    frame.position = pos;
    frame.quaternion = quat;
    this.aabb.toWorldFrame(frame, result);
    min.copy(result.lowerBound);
    max.copy(result.upperBound);
  }
  /**
   * Get approximate volume
   */


  volume() {
    return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  }
  /**
   * Create a Trimesh instance, shaped as a torus.
   */


  static createTorus(radius = 1, tube = 0.5, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
    const vertices = [];
    const indices = [];

    for (let j = 0; j <= radialSegments; j++) {
      for (let i = 0; i <= tubularSegments; i++) {
        const u = i / tubularSegments * arc;
        const v = j / radialSegments * Math.PI * 2;
        const x = (radius + tube * Math.cos(v)) * Math.cos(u);
        const y = (radius + tube * Math.cos(v)) * Math.sin(u);
        const 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;
        const b = (tubularSegments + 1) * (j - 1) + i - 1;
        const c = (tubularSegments + 1) * (j - 1) + i;
        const d = (tubularSegments + 1) * j + i;
        indices.push(a, b, d);
        indices.push(b, c, d);
      }
    }

    return new Trimesh(vertices, indices);
  }

}
const computeNormals_n = new Vec3();
const unscaledAABB = new AABB();
const getEdgeVector_va = new Vec3();
const getEdgeVector_vb = new Vec3();
const cb = new Vec3();
const ab = new Vec3();
const va = new Vec3();
const vb = new Vec3();
const vc = new Vec3();
const cli_aabb = new AABB();
const computeLocalAABB_worldVert = new Vec3();
const calculateWorldAABB_frame = new Transform();
const calculateWorldAABB_aabb = new AABB();

/**
 * Constraint equation solver base class.
 */
class Solver {
  /**
   * All equations to be solved
   */

  /**
   * @todo remove useless constructor
   */
  constructor() {
    this.equations = void 0;
    this.equations = [];
  }
  /**
   * Should be implemented in subclasses!
   * @todo use abstract
   * @return number of iterations performed
   */


  solve(dt, world) {
    return (// Should return the number of iterations done!
      0
    );
  }
  /**
   * Add an equation
   */


  addEquation(eq) {
    if (eq.enabled && !eq.bi.isTrigger && !eq.bj.isTrigger) {
      this.equations.push(eq);
    }
  }
  /**
   * Remove an equation
   */


  removeEquation(eq) {
    const eqs = this.equations;
    const i = eqs.indexOf(eq);

    if (i !== -1) {
      eqs.splice(i, 1);
    }
  }
  /**
   * Add all equations
   */


  removeAllEquations() {
    this.equations.length = 0;
  }

}

/**
 * Constraint equation Gauss-Seidel solver.
 * @todo The spook parameters should be specified for each constraint, not globally.
 * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
 */
class GSSolver extends Solver {
  /**
   * The number of solver iterations determines quality of the constraints in the world.
   * The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
   */

  /**
   * When tolerance is reached, the system is assumed to be converged.
   */

  /**
   * @todo remove useless constructor
   */
  constructor() {
    super();
    this.iterations = void 0;
    this.tolerance = void 0;
    this.iterations = 10;
    this.tolerance = 1e-7;
  }
  /**
   * Solve
   * @return number of iterations performed
   */


  solve(dt, world) {
    let iter = 0;
    const maxIter = this.iterations;
    const tolSquared = this.tolerance * this.tolerance;
    const equations = this.equations;
    const Neq = equations.length;
    const bodies = world.bodies;
    const Nbodies = bodies.length;
    const h = dt;
    let B;
    let invC;
    let deltalambda;
    let deltalambdaTot;
    let GWlambda;
    let lambdaj; // Update solve mass

    if (Neq !== 0) {
      for (let i = 0; i !== Nbodies; i++) {
        bodies[i].updateSolveMassProperties();
      }
    } // Things that do not change during iteration can be computed once


    const invCs = GSSolver_solve_invCs;
    const Bs = GSSolver_solve_Bs;
    const 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.0;
      Bs[i] = c.computeB(h);
      invCs[i] = 1.0 / c.computeC();
    }

    if (Neq !== 0) {
      // Reset vlambda
      for (let i = 0; i !== Nbodies; i++) {
        const b = bodies[i];
        const vlambda = b.vlambda;
        const wlambda = b.wlambda;
        vlambda.set(0, 0, 0);
        wlambda.set(0, 0, 0);
      } // Iterate over equations


      for (iter = 0; iter !== maxIter; iter++) {
        // Accumulate the total error for each iteration.
        deltalambdaTot = 0.0;

        for (let j = 0; j !== Neq; j++) {
          const c = equations[j]; // Compute iteration

          B = Bs[j];
          invC = invCs[j];
          lambdaj = lambda[j];
          GWlambda = c.computeGWlambda();
          deltalambda = invC * (B - GWlambda - c.eps * lambdaj); // Clamp if we are not within the min/max interval

          if (lambdaj + deltalambda < c.minForce) {
            deltalambda = c.minForce - lambdaj;
          } else if (lambdaj + deltalambda > c.maxForce) {
            deltalambda = c.maxForce - lambdaj;
          }

          lambda[j] += deltalambda;
          deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)

          c.addToWlambda(deltalambda);
        } // If the total error is small enough - stop iterate


        if (deltalambdaTot * deltalambdaTot < tolSquared) {
          break;
        }
      } // Add result to velocity


      for (let i = 0; i !== Nbodies; i++) {
        const b = bodies[i];
        const v = b.velocity;
        const w = b.angularVelocity;
        b.vlambda.vmul(b.linearFactor, b.vlambda);
        v.vadd(b.vlambda, v);
        b.wlambda.vmul(b.angularFactor, b.wlambda);
        w.vadd(b.wlambda, w);
      } // Set the `.multiplier` property of each equation


      let l = equations.length;
      const invDt = 1 / h;

      while (l--) {
        equations[l].multiplier = lambda[l] * invDt;
      }
    }

    return iter;
  }

} // Just temporary number holders that we want to reuse each iteration.

const GSSolver_solve_lambda = [];
const GSSolver_solve_invCs = [];
const GSSolver_solve_Bs = [];

/**
 * Splits the equations into islands and solves them independently. Can improve performance.
 */
class SplitSolver extends Solver {
  /**
   * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
   */

  /**
   * When tolerance is reached, the system is assumed to be converged.
   */

  /** subsolver */
  constructor(subsolver) {
    super();
    this.iterations = void 0;
    this.tolerance = void 0;
    this.subsolver = void 0;
    this.nodes = void 0;
    this.nodePool = void 0;
    this.iterations = 10;
    this.tolerance = 1e-7;
    this.subsolver = subsolver;
    this.nodes = [];
    this.nodePool = []; // Create needed nodes, reuse if possible

    while (this.nodePool.length < 128) {
      this.nodePool.push(this.createNode());
    }
  }
  /**
   * createNode
   */


  createNode() {
    return {
      body: null,
      children: [],
      eqs: [],
      visited: false
    };
  }
  /**
   * Solve the subsystems
   * @return number of iterations performed
   */


  solve(dt, world) {
    const nodes = SplitSolver_solve_nodes;
    const nodePool = this.nodePool;
    const bodies = world.bodies;
    const equations = this.equations;
    const Neq = equations.length;
    const Nbodies = bodies.length;
    const subsolver = this.subsolver; // Create needed nodes, reuse if possible

    while (nodePool.length < Nbodies) {
      nodePool.push(this.createNode());
    }

    nodes.length = Nbodies;

    for (let i = 0; i < Nbodies; i++) {
      nodes[i] = nodePool[i];
    } // Reset node values


    for (let i = 0; i !== Nbodies; i++) {
      const node = nodes[i];
      node.body = bodies[i];
      node.children.length = 0;
      node.eqs.length = 0;
      node.visited = false;
    }

    for (let k = 0; k !== Neq; k++) {
      const eq = equations[k];
      const i = bodies.indexOf(eq.bi);
      const j = bodies.indexOf(eq.bj);
      const ni = nodes[i];
      const nj = nodes[j];
      ni.children.push(nj);
      ni.eqs.push(eq);
      nj.children.push(ni);
      nj.eqs.push(eq);
    }

    let child;
    let n = 0;
    let eqs = SplitSolver_solve_eqs;
    subsolver.tolerance = this.tolerance;
    subsolver.iterations = this.iterations;
    const dummyWorld = SplitSolver_solve_dummyWorld;

    while (child = getUnvisitedNode(nodes)) {
      eqs.length = 0;
      dummyWorld.bodies.length = 0;
      bfs(child, visitFunc, dummyWorld.bodies, eqs);
      const Neqs = eqs.length;
      eqs = eqs.sort(sortById);

      for (let i = 0; i !== Neqs; i++) {
        subsolver.addEquation(eqs[i]);
      }

      subsolver.solve(dt, dummyWorld);
      subsolver.removeAllEquations();
      n++;
    }

    return n;
  }

} // Returns the number of subsystems

const SplitSolver_solve_nodes = []; // All allocated node objects

const SplitSolver_solve_eqs = []; // Temp array

const SplitSolver_solve_dummyWorld = {
  bodies: []
}; // Temp object

const STATIC = Body.STATIC;

function getUnvisitedNode(nodes) {
  const Nnodes = nodes.length;

  for (let i = 0; i !== Nnodes; i++) {
    const node = nodes[i];

    if (!node.visited && !(node.body.type & STATIC)) {
      return node;
    }
  }

  return false;
}

const queue = [];

function bfs(root, visitFunc, bds, eqs) {
  queue.push(root);
  root.visited = true;
  visitFunc(root, bds, eqs);

  while (queue.length) {
    const node = queue.pop(); // Loop over unvisited child nodes

    let child;

    while (child = getUnvisitedNode(node.children)) {
      child.visited = true;
      visitFunc(child, bds, eqs);
      queue.push(child);
    }
  }
}

function visitFunc(node, bds, eqs) {
  bds.push(node.body);
  const Neqs = node.eqs.length;

  for (let i = 0; i !== Neqs; i++) {
    const eq = node.eqs[i];

    if (!eqs.includes(eq)) {
      eqs.push(eq);
    }
  }
}

function sortById(a, b) {
  return b.id - a.id;
}

/**
 * For pooling objects that can be reused.
 */
class Pool {
  constructor() {
    this.objects = [];
    this.type = Object;
  }

  /**
   * Release an object after use
   */
  release(...args) {
    const Nargs = args.length;

    for (let i = 0; i !== Nargs; i++) {
      this.objects.push(args[i]);
    }

    return this;
  }
  /**
   * Get an object
   */


  get() {
    if (this.objects.length === 0) {
      return this.constructObject();
    } else {
      return this.objects.pop();
    }
  }
  /**
   * Construct an object. Should be implemented in each subclass.
   */


  constructObject() {
    throw new Error('constructObject() not implemented in this Pool subclass yet!');
  }
  /**
   * @return Self, for chaining
   */


  resize(size) {
    const objects = this.objects;

    while (objects.length > size) {
      objects.pop();
    }

    while (objects.length < size) {
      objects.push(this.constructObject());
    }

    return this;
  }

}

/**
 * Vec3Pool
 */

class Vec3Pool extends Pool {
  constructor(...args) {
    super(...args);
    this.type = Vec3;
  }

  /**
   * Construct a vector
   */
  constructObject() {
    return new Vec3();
  }

}

let _COLLISION_TYPES$sphe, _COLLISION_TYPES$sphe2, _COLLISION_TYPES$boxB, _COLLISION_TYPES$sphe3, _COLLISION_TYPES$plan, _COLLISION_TYPES$conv, _COLLISION_TYPES$sphe4, _COLLISION_TYPES$plan2, _COLLISION_TYPES$boxC, _COLLISION_TYPES$sphe5, _COLLISION_TYPES$boxH, _COLLISION_TYPES$conv2, _COLLISION_TYPES$sphe6, _COLLISION_TYPES$plan3, _COLLISION_TYPES$boxP, _COLLISION_TYPES$conv3, _COLLISION_TYPES$cyli, _COLLISION_TYPES$sphe7, _COLLISION_TYPES$plan4, _COLLISION_TYPES$boxC2, _COLLISION_TYPES$conv4, _COLLISION_TYPES$heig, _COLLISION_TYPES$part, _COLLISION_TYPES$sphe8, _COLLISION_TYPES$plan5;
// Naming rule: based of the order in SHAPE_TYPES,
// the first part of the method is formed by the
// shape type that comes before, in the second part
// there is the shape type that comes after in the SHAPE_TYPES list
const COLLISION_TYPES = {
  sphereSphere: Shape.types.SPHERE,
  spherePlane: Shape.types.SPHERE | Shape.types.PLANE,
  boxBox: Shape.types.BOX | Shape.types.BOX,
  sphereBox: Shape.types.SPHERE | Shape.types.BOX,
  planeBox: Shape.types.PLANE | Shape.types.BOX,
  convexConvex: Shape.types.CONVEXPOLYHEDRON,
  sphereConvex: Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON,
  planeConvex: Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON,
  boxConvex: Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON,
  sphereHeightfield: Shape.types.SPHERE | Shape.types.HEIGHTFIELD,
  boxHeightfield: Shape.types.BOX | Shape.types.HEIGHTFIELD,
  convexHeightfield: Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD,
  sphereParticle: Shape.types.PARTICLE | Shape.types.SPHERE,
  planeParticle: Shape.types.PLANE | Shape.types.PARTICLE,
  boxParticle: Shape.types.BOX | Shape.types.PARTICLE,
  convexParticle: Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON,
  cylinderCylinder: Shape.types.CYLINDER,
  sphereCylinder: Shape.types.SPHERE | Shape.types.CYLINDER,
  planeCylinder: Shape.types.PLANE | Shape.types.CYLINDER,
  boxCylinder: Shape.types.BOX | Shape.types.CYLINDER,
  convexCylinder: Shape.types.CONVEXPOLYHEDRON | Shape.types.CYLINDER,
  heightfieldCylinder: Shape.types.HEIGHTFIELD | Shape.types.CYLINDER,
  particleCylinder: Shape.types.PARTICLE | Shape.types.CYLINDER,
  sphereTrimesh: Shape.types.SPHERE | Shape.types.TRIMESH,
  planeTrimesh: Shape.types.PLANE | Shape.types.TRIMESH
};
_COLLISION_TYPES$sphe = COLLISION_TYPES.sphereSphere;
_COLLISION_TYPES$sphe2 = COLLISION_TYPES.spherePlane;
_COLLISION_TYPES$boxB = COLLISION_TYPES.boxBox;
_COLLISION_TYPES$sphe3 = COLLISION_TYPES.sphereBox;
_COLLISION_TYPES$plan = COLLISION_TYPES.planeBox;
_COLLISION_TYPES$conv = COLLISION_TYPES.convexConvex;
_COLLISION_TYPES$sphe4 = COLLISION_TYPES.sphereConvex;
_COLLISION_TYPES$plan2 = COLLISION_TYPES.planeConvex;
_COLLISION_TYPES$boxC = COLLISION_TYPES.boxConvex;
_COLLISION_TYPES$sphe5 = COLLISION_TYPES.sphereHeightfield;
_COLLISION_TYPES$boxH = COLLISION_TYPES.boxHeightfield;
_COLLISION_TYPES$conv2 = COLLISION_TYPES.convexHeightfield;
_COLLISION_TYPES$sphe6 = COLLISION_TYPES.sphereParticle;
_COLLISION_TYPES$plan3 = COLLISION_TYPES.planeParticle;
_COLLISION_TYPES$boxP = COLLISION_TYPES.boxParticle;
_COLLISION_TYPES$conv3 = COLLISION_TYPES.convexParticle;
_COLLISION_TYPES$cyli = COLLISION_TYPES.cylinderCylinder;
_COLLISION_TYPES$sphe7 = COLLISION_TYPES.sphereCylinder;
_COLLISION_TYPES$plan4 = COLLISION_TYPES.planeCylinder;
_COLLISION_TYPES$boxC2 = COLLISION_TYPES.boxCylinder;
_COLLISION_TYPES$conv4 = COLLISION_TYPES.convexCylinder;
_COLLISION_TYPES$heig = COLLISION_TYPES.heightfieldCylinder;
_COLLISION_TYPES$part = COLLISION_TYPES.particleCylinder;
_COLLISION_TYPES$sphe8 = COLLISION_TYPES.sphereTrimesh;
_COLLISION_TYPES$plan5 = COLLISION_TYPES.planeTrimesh;

/**
 * Helper class for the World. Generates ContactEquations.
 * @todo Sphere-ConvexPolyhedron contacts
 * @todo Contact reduction
 * @todo should move methods to prototype
 */
class Narrowphase {
  /**
   * Internal storage of pooled contact points.
   */

  /**
   * Pooled vectors.
   */
  get [_COLLISION_TYPES$sphe]() {
    return this.sphereSphere;
  }

  get [_COLLISION_TYPES$sphe2]() {
    return this.spherePlane;
  }

  get [_COLLISION_TYPES$boxB]() {
    return this.boxBox;
  }

  get [_COLLISION_TYPES$sphe3]() {
    return this.sphereBox;
  }

  get [_COLLISION_TYPES$plan]() {
    return this.planeBox;
  }

  get [_COLLISION_TYPES$conv]() {
    return this.convexConvex;
  }

  get [_COLLISION_TYPES$sphe4]() {
    return this.sphereConvex;
  }

  get [_COLLISION_TYPES$plan2]() {
    return this.planeConvex;
  }

  get [_COLLISION_TYPES$boxC]() {
    return this.boxConvex;
  }

  get [_COLLISION_TYPES$sphe5]() {
    return this.sphereHeightfield;
  }

  get [_COLLISION_TYPES$boxH]() {
    return this.boxHeightfield;
  }

  get [_COLLISION_TYPES$conv2]() {
    return this.convexHeightfield;
  }

  get [_COLLISION_TYPES$sphe6]() {
    return this.sphereParticle;
  }

  get [_COLLISION_TYPES$plan3]() {
    return this.planeParticle;
  }

  get [_COLLISION_TYPES$boxP]() {
    return this.boxParticle;
  }

  get [_COLLISION_TYPES$conv3]() {
    return this.convexParticle;
  }

  get [_COLLISION_TYPES$cyli]() {
    return this.convexConvex;
  }

  get [_COLLISION_TYPES$sphe7]() {
    return this.sphereConvex;
  }

  get [_COLLISION_TYPES$plan4]() {
    return this.planeConvex;
  }

  get [_COLLISION_TYPES$boxC2]() {
    return this.boxConvex;
  }

  get [_COLLISION_TYPES$conv4]() {
    return this.convexConvex;
  }

  get [_COLLISION_TYPES$heig]() {
    return this.heightfieldCylinder;
  }

  get [_COLLISION_TYPES$part]() {
    return this.particleCylinder;
  }

  get [_COLLISION_TYPES$sphe8]() {
    return this.sphereTrimesh;
  }

  get [_COLLISION_TYPES$plan5]() {
    return this.planeTrimesh;
  } // get [COLLISION_TYPES.convexTrimesh]() {
  //   return this.convexTrimesh
  // }


  constructor(world) {
    this.contactPointPool = void 0;
    this.frictionEquationPool = void 0;
    this.result = void 0;
    this.frictionResult = void 0;
    this.v3pool = void 0;
    this.world = void 0;
    this.currentContactMaterial = void 0;
    this.enableFrictionReduction = void 0;
    this.contactPointPool = [];
    this.frictionEquationPool = [];
    this.result = [];
    this.frictionResult = [];
    this.v3pool = new Vec3Pool();
    this.world = world;
    this.currentContactMaterial = world.defaultContactMaterial;
    this.enableFrictionReduction = false;
  }
  /**
   * Make a contact object, by using the internal pool or creating a new one.
   */


  createContactEquation(bi, bj, si, sj, overrideShapeA, overrideShapeB) {
    let c;

    if (this.contactPointPool.length) {
      c = this.contactPointPool.pop();
      c.bi = bi;
      c.bj = bj;
    } else {
      c = new ContactEquation(bi, bj);
    }

    c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
    const cm = this.currentContactMaterial;
    c.restitution = cm.restitution;
    c.setSpookParams(cm.contactEquationStiffness, cm.contactEquationRelaxation, this.world.dt);
    const matA = si.material || bi.material;
    const matB = sj.material || bj.material;

    if (matA && matB && matA.restitution >= 0 && matB.restitution >= 0) {
      c.restitution = matA.restitution * matB.restitution;
    }

    c.si = overrideShapeA || si;
    c.sj = overrideShapeB || sj;
    return c;
  }

  createFrictionEquationsFromContact(contactEquation, outArray) {
    const bodyA = contactEquation.bi;
    const bodyB = contactEquation.bj;
    const shapeA = contactEquation.si;
    const shapeB = contactEquation.sj;
    const world = this.world;
    const cm = this.currentContactMaterial; // If friction or restitution were specified in the material, use them

    let friction = cm.friction;
    const matA = shapeA.material || bodyA.material;
    const matB = shapeB.material || bodyB.material;

    if (matA && matB && matA.friction >= 0 && matB.friction >= 0) {
      friction = matA.friction * matB.friction;
    }

    if (friction > 0) {
      // Create 2 tangent equations
      const mug = friction * world.gravity.length();
      let reducedMass = bodyA.invMass + bodyB.invMass;

      if (reducedMass > 0) {
        reducedMass = 1 / reducedMass;
      }

      const pool = this.frictionEquationPool;
      const c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
      const c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
      c1.bi = c2.bi = bodyA;
      c1.bj = c2.bj = bodyB;
      c1.minForce = c2.minForce = -mug * reducedMass;
      c1.maxForce = c2.maxForce = mug * reducedMass; // Copy over the relative vectors

      c1.ri.copy(contactEquation.ri);
      c1.rj.copy(contactEquation.rj);
      c2.ri.copy(contactEquation.ri);
      c2.rj.copy(contactEquation.rj); // Construct tangents

      contactEquation.ni.tangents(c1.t, c2.t); // Set spook params

      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);
      return true;
    }

    return false;
  }
  /**
   * Take the average N latest contact point on the plane.
   */


  createFrictionFromAverage(numContacts) {
    // The last contactEquation
    let c = this.result[this.result.length - 1]; // Create the result: two "average" friction equations

    if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
      return;
    }

    const f1 = this.frictionResult[this.frictionResult.length - 2];
    const 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];

      if (c.bi !== bodyA) {
        averageNormal.vadd(c.ni, averageNormal);
        averageContactPointA.vadd(c.ri, averageContactPointA);
        averageContactPointB.vadd(c.rj, averageContactPointB);
      } else {
        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); // Should be the same

    f2.rj.copy(f1.rj);
    averageNormal.normalize();
    averageNormal.tangents(f1.t, f2.t); // return eq;
  }
  /**
   * Generate all contacts between a list of body pairs
   * @param p1 Array of body indices
   * @param p2 Array of body indices
   * @param result Array to store generated contacts
   * @param oldcontacts Optional. Array of reusable contact objects
   */


  getContacts(p1, p2, world, result, oldcontacts, frictionResult, frictionPool) {
    // Save old contact objects
    this.contactPointPool = oldcontacts;
    this.frictionEquationPool = frictionPool;
    this.result = result;
    this.frictionResult = frictionResult;
    const qi = tmpQuat1;
    const qj = tmpQuat2;
    const xi = tmpVec1;
    const xj = tmpVec2;

    for (let k = 0, N = p1.length; k !== N; k++) {
      // Get current collision bodies
      const bi = p1[k];
      const bj = p2[k]; // Get contact material

      let bodyContactMaterial = null;

      if (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; i < bi.shapes.length; i++) {
        bi.quaternion.mult(bi.shapeOrientations[i], qi);
        bi.quaternion.vmult(bi.shapeOffsets[i], xi);
        xi.vadd(bi.position, xi);
        const si = bi.shapes[i];

        for (let j = 0; j < bj.shapes.length; j++) {
          // Compute world transform of shapes
          bj.quaternion.mult(bj.shapeOrientations[j], qj);
          bj.quaternion.vmult(bj.shapeOffsets[j], xj);
          xj.vadd(bj.position, xj);
          const sj = bj.shapes[j];

          if (!(si.collisionFilterMask & sj.collisionFilterGroup && sj.collisionFilterMask & si.collisionFilterGroup)) {
            continue;
          }

          if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
            continue;
          } // Get collision material


          let shapeContactMaterial = null;

          if (si.material && sj.material) {
            shapeContactMaterial = world.getContactMaterial(si.material, sj.material) || null;
          }

          this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial; // Get contacts

          const resolverIndex = si.type | sj.type;
          const resolver = this[resolverIndex];

          if (resolver) {
            let retval = false; // TO DO: investigate why sphereParticle and convexParticle
            // resolvers expect si and sj shapes to be in reverse order
            // (i.e. larger integer value type first instead of smaller first)

            if (si.type < sj.type) {
              retval = resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
            } else {
              retval = resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj, justTest);
            }

            if (retval && justTest) {
              // Register overlap
              world.shapeOverlapKeeper.set(si.id, sj.id);
              world.bodyOverlapKeeper.set(bi.id, bj.id);
            }
          }
        }
      }
    }
  }

  sphereSphere(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    if (justTest) {
      return xi.distanceSquared(xj) < (si.radius + sj.radius) ** 2;
    } // We will have only one contact in this case


    const contactEq = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal

    xj.vsub(xi, contactEq.ni);
    contactEq.ni.normalize(); // Contact point locations

    contactEq.ri.copy(contactEq.ni);
    contactEq.rj.copy(contactEq.ni);
    contactEq.ri.scale(si.radius, contactEq.ri);
    contactEq.rj.scale(-sj.radius, contactEq.rj);
    contactEq.ri.vadd(xi, contactEq.ri);
    contactEq.ri.vsub(bi.position, contactEq.ri);
    contactEq.rj.vadd(xj, contactEq.rj);
    contactEq.rj.vsub(bj.position, contactEq.rj);
    this.result.push(contactEq);
    this.createFrictionEquationsFromContact(contactEq, this.frictionResult);
  }

  spherePlane(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    // We will have one contact in this case
    const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal

    r.ni.set(0, 0, 1);
    qj.vmult(r.ni, r.ni);
    r.ni.negate(r.ni); // body i is the sphere, flip normal

    r.ni.normalize(); // Needed?
    // Vector from sphere center to contact point

    r.ni.scale(si.radius, r.ri); // Project down sphere on plane

    xi.vsub(xj, point_on_plane_to_sphere);
    r.ni.scale(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
    point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, r.rj); // The sphere position projected to plane

    if (-point_on_plane_to_sphere.dot(r.ni) <= si.radius) {
      if (justTest) {
        return true;
      } // Make it relative to the body


      const ri = r.ri;
      const rj = r.rj;
      ri.vadd(xi, ri);
      ri.vsub(bi.position, ri);
      rj.vadd(xj, rj);
      rj.vsub(bj.position, rj);
      this.result.push(r);
      this.createFrictionEquationsFromContact(r, this.frictionResult);
    }
  }

  boxBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    si.convexPolyhedronRepresentation.material = si.material;
    sj.convexPolyhedronRepresentation.material = sj.material;
    si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
    sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
    return this.convexConvex(si.convexPolyhedronRepresentation, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  }

  sphereBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    const v3pool = this.v3pool; // we refer to the box as body j

    const sides = sphereBox_sides;
    xi.vsub(xj, box_to_sphere);
    sj.getSideNormals(sides, qj);
    const R = si.radius;

    let found = false; // Store the resulting side penetration info

    const side_ns = sphereBox_side_ns;
    const side_ns1 = sphereBox_side_ns1;
    const side_ns2 = sphereBox_side_ns2;
    let side_h = null;
    let side_penetrations = 0;
    let side_dot1 = 0;
    let side_dot2 = 0;
    let side_distance = null;

    for (let idx = 0, nsides = sides.length; idx !== nsides && found === false; idx++) {
      // Get the plane side normal (ns)
      const ns = sphereBox_ns;
      ns.copy(sides[idx]);
      const h = ns.length();
      ns.normalize(); // The normal/distance dot product tells which side of the plane we are

      const dot = box_to_sphere.dot(ns);

      if (dot < h + R && dot > 0) {
        // Intersects plane. Now check the other two dimensions
        const ns1 = sphereBox_ns1;
        const ns2 = sphereBox_ns2;
        ns1.copy(sides[(idx + 1) % 3]);
        ns2.copy(sides[(idx + 2) % 3]);
        const h1 = ns1.length();
        const h2 = ns2.length();
        ns1.normalize();
        ns2.normalize();
        const dot1 = box_to_sphere.dot(ns1);
        const dot2 = box_to_sphere.dot(ns2);

        if (dot1 < h1 && dot1 > -h1 && dot2 < h2 && dot2 > -h2) {
          const dist = Math.abs(dot - h - R);

          if (side_distance === null || dist < side_distance) {
            side_distance = dist;
            side_dot1 = dot1;
            side_dot2 = dot2;
            side_h = h;
            side_ns.copy(ns);
            side_ns1.copy(ns1);
            side_ns2.copy(ns2);
            side_penetrations++;

            if (justTest) {
              return true;
            }
          }
        }
      }
    }

    if (side_penetrations) {
      found = true;
      const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
      side_ns.scale(-R, r.ri); // Sphere r

      r.ni.copy(side_ns);
      r.ni.negate(r.ni); // Normal should be out of sphere

      side_ns.scale(side_h, side_ns);
      side_ns1.scale(side_dot1, side_ns1);
      side_ns.vadd(side_ns1, side_ns);
      side_ns2.scale(side_dot2, side_ns2);
      side_ns.vadd(side_ns2, r.rj); // Make relative to bodies

      r.ri.vadd(xi, r.ri);
      r.ri.vsub(bi.position, r.ri);
      r.rj.vadd(xj, r.rj);
      r.rj.vsub(bj.position, r.rj);
      this.result.push(r);
      this.createFrictionEquationsFromContact(r, this.frictionResult);
    } // Check corners


    let rj = v3pool.get();
    const sphere_to_corner = sphereBox_sphere_to_corner;

    for (let j = 0; j !== 2 && !found; j++) {
      for (let k = 0; k !== 2 && !found; k++) {
        for (let l = 0; l !== 2 && !found; l++) {
          rj.set(0, 0, 0);

          if (j) {
            rj.vadd(sides[0], rj);
          } else {
            rj.vsub(sides[0], rj);
          }

          if (k) {
            rj.vadd(sides[1], rj);
          } else {
            rj.vsub(sides[1], rj);
          }

          if (l) {
            rj.vadd(sides[2], rj);
          } else {
            rj.vsub(sides[2], rj);
          } // World position of corner


          xj.vadd(rj, sphere_to_corner);
          sphere_to_corner.vsub(xi, sphere_to_corner);

          if (sphere_to_corner.lengthSquared() < R * R) {
            if (justTest) {
              return true;
            }

            found = true;
            const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
            r.ri.copy(sphere_to_corner);
            r.ri.normalize();
            r.ni.copy(r.ri);
            r.ri.scale(R, r.ri);
            r.rj.copy(rj); // Make relative to bodies

            r.ri.vadd(xi, r.ri);
            r.ri.vsub(bi.position, r.ri);
            r.rj.vadd(xj, r.rj);
            r.rj.vsub(bj.position, r.rj);
            this.result.push(r);
            this.createFrictionEquationsFromContact(r, this.frictionResult);
          }
        }
      }
    }

    v3pool.release(rj);
    rj = null; // Check edges

    const edgeTangent = v3pool.get();
    const edgeCenter = v3pool.get();
    const r = v3pool.get(); // r = edge center to sphere center

    const orthogonal = v3pool.get();
    const dist = v3pool.get();
    const Nsides = sides.length;

    for (let j = 0; j !== Nsides && !found; j++) {
      for (let k = 0; k !== Nsides && !found; k++) {
        if (j % 3 !== k % 3) {
          // Get edge tangent
          sides[k].cross(sides[j], edgeTangent);
          edgeTangent.normalize();
          sides[j].vadd(sides[k], edgeCenter);
          r.copy(xi);
          r.vsub(edgeCenter, r);
          r.vsub(xj, r);
          const orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction

          edgeTangent.scale(orthonorm, orthogonal); // Vector from edge center to sphere center in the tangent direction
          // Find the third side orthogonal to this one

          let l = 0;

          while (l === j % 3 || l === k % 3) {
            l++;
          } // vec from edge center to sphere projected to the plane orthogonal to the edge tangent


          dist.copy(xi);
          dist.vsub(orthogonal, dist);
          dist.vsub(edgeCenter, dist);
          dist.vsub(xj, dist); // Distances in tangent direction and distance in the plane orthogonal to it

          const tdist = Math.abs(orthonorm);
          const ndist = dist.length();

          if (tdist < sides[l].length() && ndist < R) {
            if (justTest) {
              return true;
            }

            found = true;
            const res = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
            edgeCenter.vadd(orthogonal, res.rj); // box rj

            res.rj.copy(res.rj);
            dist.negate(res.ni);
            res.ni.normalize();
            res.ri.copy(res.rj);
            res.ri.vadd(xj, res.ri);
            res.ri.vsub(xi, res.ri);
            res.ri.normalize();
            res.ri.scale(R, res.ri); // Make relative to bodies

            res.ri.vadd(xi, res.ri);
            res.ri.vsub(bi.position, res.ri);
            res.rj.vadd(xj, res.rj);
            res.rj.vsub(bj.position, res.rj);
            this.result.push(res);
            this.createFrictionEquationsFromContact(res, this.frictionResult);
          }
        }
      }
    }

    v3pool.release(edgeTangent, edgeCenter, r, orthogonal, dist);
  }

  planeBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    sj.convexPolyhedronRepresentation.material = sj.material;
    sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
    sj.convexPolyhedronRepresentation.id = sj.id;
    return this.planeConvex(si, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  }

  convexConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest, faceListA, faceListB) {
    const sepAxis = convexConvex_sepAxis;

    if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
      return;
    }

    if (si.findSeparatingAxis(sj, xi, qi, xj, qj, sepAxis, faceListA, faceListB)) {
      const res = [];
      const 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 true;
        }

        const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
        const ri = r.ri;
        const 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); // Contact points are in world coordinates. Transform back to relative

        ri.vsub(xi, ri);
        rj.vsub(xj, rj); // Make relative to bodies

        ri.vadd(xi, ri);
        ri.vsub(bi.position, ri);
        rj.vadd(xj, rj);
        rj.vsub(bj.position, rj);
        this.result.push(r);
        numContacts++;

        if (!this.enableFrictionReduction) {
          this.createFrictionEquationsFromContact(r, this.frictionResult);
        }
      }

      if (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;
    const faces = sj.faces;
    const verts = sj.vertices;
    const R = si.radius;
    //     return;
    // }

    let found = false; // Check corners

    for (let i = 0; i !== verts.length; i++) {
      const v = verts[i]; // World position of corner

      const worldCorner = sphereConvex_worldCorner;
      qj.vmult(v, worldCorner);
      xj.vadd(worldCorner, worldCorner);
      const sphere_to_corner = sphereConvex_sphereToCorner;
      worldCorner.vsub(xi, sphere_to_corner);

      if (sphere_to_corner.lengthSquared() < R * R) {
        if (justTest) {
          return true;
        }

        found = true;
        const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
        r.ri.copy(sphere_to_corner);
        r.ri.normalize();
        r.ni.copy(r.ri);
        r.ri.scale(R, r.ri);
        worldCorner.vsub(xj, r.rj); // Should be relative to the body.

        r.ri.vadd(xi, r.ri);
        r.ri.vsub(bi.position, r.ri); // Should be relative to the body.

        r.rj.vadd(xj, r.rj);
        r.rj.vsub(bj.position, r.rj);
        this.result.push(r);
        this.createFrictionEquationsFromContact(r, this.frictionResult);
        return;
      }
    } // Check side (plane) intersections


    for (let i = 0, nfaces = faces.length; i !== nfaces && found === false; i++) {
      const normal = normals[i];
      const face = faces[i]; // Get world-transformed normal of the face

      const worldNormal = sphereConvex_worldNormal;
      qj.vmult(normal, worldNormal); // Get a world vertex from the face

      const worldPoint = sphereConvex_worldPoint;
      qj.vmult(verts[face[0]], worldPoint);
      worldPoint.vadd(xj, worldPoint); // Get a point on the sphere, closest to the face normal

      const worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
      worldNormal.scale(-R, worldSpherePointClosestToPlane);
      xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); // Vector from a face point to the closest point on the sphere

      const penetrationVec = sphereConvex_penetrationVec;
      worldSpherePointClosestToPlane.vsub(worldPoint, penetrationVec); // The penetration. Negative value means overlap.

      const penetration = penetrationVec.dot(worldNormal);
      const worldPointToSphere = sphereConvex_sphereToWorldPoint;
      xi.vsub(worldPoint, worldPointToSphere);

      if (penetration < 0 && worldPointToSphere.dot(worldNormal) > 0) {
        // Intersects plane. Now check if the sphere is inside the face polygon
        const faceVerts = []; // Face vertices, in world coords

        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)) {
          // Is the sphere center in the face polygon?
          if (justTest) {
            return true;
          }

          found = true;
          const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
          worldNormal.scale(-R, r.ri); // Contact offset, from sphere center to contact

          worldNormal.negate(r.ni); // Normal pointing out of sphere

          const penetrationVec2 = v3pool.get();
          worldNormal.scale(-penetration, penetrationVec2);
          const penetrationSpherePoint = v3pool.get();
          worldNormal.scale(-R, penetrationSpherePoint); //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);

          xi.vsub(xj, r.rj);
          r.rj.vadd(penetrationSpherePoint, r.rj);
          r.rj.vadd(penetrationVec2, r.rj); // Should be relative to the body.

          r.rj.vadd(xj, r.rj);
          r.rj.vsub(bj.position, r.rj); // Should be relative to the body.

          r.ri.vadd(xi, r.ri);
          r.ri.vsub(bi.position, r.ri);
          v3pool.release(penetrationVec2);
          v3pool.release(penetrationSpherePoint);
          this.result.push(r);
          this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices

          for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
            v3pool.release(faceVerts[j]);
          }

          return; // We only expect *one* face contact
        } else {
          // Edge?
          for (let j = 0; j !== face.length; j++) {
            // Get two world transformed vertices
            const v1 = v3pool.get();
            const v2 = v3pool.get();
            qj.vmult(verts[face[(j + 1) % face.length]], v1);
            qj.vmult(verts[face[(j + 2) % face.length]], v2);
            xj.vadd(v1, v1);
            xj.vadd(v2, v2); // Construct edge vector

            const edge = sphereConvex_edge;
            v2.vsub(v1, edge); // Construct the same vector, but normalized

            const edgeUnit = sphereConvex_edgeUnit;
            edge.unit(edgeUnit); // p is xi projected onto the edge

            const p = v3pool.get();
            const 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); // Compute a vector from p to the center of the sphere

            const xi_to_p = v3pool.get();
            p.vsub(xi, xi_to_p); // Collision if the edge-sphere distance is less than the radius
            // AND if p is in between v1 and v2

            if (dot > 0 && dot * dot < edge.lengthSquared() && xi_to_p.lengthSquared() < R * R) {
              // Collision if the edge-sphere distance is less than the radius
              // Edge contact!
              if (justTest) {
                return true;
              }

              const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
              p.vsub(xj, r.rj);
              p.vsub(xi, r.ni);
              r.ni.normalize();
              r.ni.scale(R, r.ri); // Should be relative to the body.

              r.rj.vadd(xj, r.rj);
              r.rj.vsub(bj.position, r.rj); // Should be relative to the body.

              r.ri.vadd(xi, r.ri);
              r.ri.vsub(bi.position, r.ri);
              this.result.push(r);
              this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices

              for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
                v3pool.release(faceVerts[j]);
              }

              v3pool.release(v1);
              v3pool.release(v2);
              v3pool.release(p);
              v3pool.release(xi_to_p);
              v3pool.release(v1_to_xi);
              return;
            }

            v3pool.release(v1);
            v3pool.release(v2);
            v3pool.release(p);
            v3pool.release(xi_to_p);
            v3pool.release(v1_to_xi);
          }
        } // Release world vertices


        for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
          v3pool.release(faceVerts[j]);
        }
      }
    }
  }

  planeConvex(planeShape, convexShape, planePosition, convexPosition, planeQuat, convexQuat, planeBody, convexBody, si, sj, justTest) {
    // Simply return the points behind the plane.
    const worldVertex = planeConvex_v;
    const worldNormal = planeConvex_normal;
    worldNormal.set(0, 0, 1);
    planeQuat.vmult(worldNormal, worldNormal); // Turn normal according to plane orientation

    let numContacts = 0;
    const relpos = planeConvex_relpos;

    for (let i = 0; i !== convexShape.vertices.length; i++) {
      // Get world convex vertex
      worldVertex.copy(convexShape.vertices[i]);
      convexQuat.vmult(worldVertex, worldVertex);
      convexPosition.vadd(worldVertex, worldVertex);
      worldVertex.vsub(planePosition, relpos);
      const dot = worldNormal.dot(relpos);

      if (dot <= 0.0) {
        if (justTest) {
          return true;
        }

        const r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj); // Get vertex position projected on plane

        const projected = planeConvex_projected;
        worldNormal.scale(worldNormal.dot(relpos), projected);
        worldVertex.vsub(projected, projected);
        projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane

        r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
        // rj is now just the vector from the convex center to the vertex

        worldVertex.vsub(convexPosition, r.rj); // Make it relative to the body

        r.ri.vadd(planePosition, r.ri);
        r.ri.vsub(planeBody.position, r.ri);
        r.rj.vadd(convexPosition, r.rj);
        r.rj.vsub(convexBody.position, r.rj);
        this.result.push(r);
        numContacts++;

        if (!this.enableFrictionReduction) {
          this.createFrictionEquationsFromContact(r, this.frictionResult);
        }
      }
    }

    if (this.enableFrictionReduction && numContacts) {
      this.createFrictionFromAverage(numContacts);
    }
  }

  boxConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    si.convexPolyhedronRepresentation.material = si.material;
    si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
    return this.convexConvex(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  }

  sphereHeightfield(sphereShape, hfShape, spherePos, hfPos, sphereQuat, hfQuat, sphereBody, hfBody, rsi, rsj, justTest) {
    const data = hfShape.data;
    const radius = sphereShape.radius;
    const w = hfShape.elementSize;
    const worldPillarOffset = sphereHeightfield_tmp2; // Get sphere position to heightfield local!

    const localSpherePos = sphereHeightfield_tmp1;
    Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); // Get the index of the data points to test against

    let iMinX = Math.floor((localSpherePos.x - radius) / w) - 1;
    let iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1;
    let iMinY = Math.floor((localSpherePos.y - radius) / w) - 1;
    let iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; // Bail out if we are out of the terrain

    if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
      return;
    } // Clamp index to edges


    if (iMinX < 0) {
      iMinX = 0;
    }

    if (iMaxX < 0) {
      iMaxX = 0;
    }

    if (iMinY < 0) {
      iMinY = 0;
    }

    if (iMaxY < 0) {
      iMaxY = 0;
    }

    if (iMinX >= data.length) {
      iMinX = data.length - 1;
    }

    if (iMaxX >= data.length) {
      iMaxX = data.length - 1;
    }

    if (iMaxY >= data[0].length) {
      iMaxY = data[0].length - 1;
    }

    if (iMinY >= data[0].length) {
      iMinY = data[0].length - 1;
    }

    const minMax = [];
    hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
    const min = minMax[0];
    const max = minMax[1]; // Bail out if we can't touch the bounding height box

    if (localSpherePos.z - radius > max || localSpherePos.z + radius < min) {
      return;
    }

    const result = this.result;

    for (let i = iMinX; i < iMaxX; i++) {
      for (let j = iMinY; j < iMaxY; j++) {
        const numContactsBefore = result.length;
        let intersecting = false; // Lower triangle

        hfShape.getConvexTrianglePillar(i, j, false);
        Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);

        if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
          intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
        }

        if (justTest && intersecting) {
          return true;
        } // Upper triangle


        hfShape.getConvexTrianglePillar(i, j, true);
        Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);

        if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
          intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
        }

        if (justTest && intersecting) {
          return true;
        }

        const numContacts = result.length - numContactsBefore;

        if (numContacts > 2) {
          return;
        }
        /*
          // Skip all but 1
          for (let k = 0; k < numContacts - 1; k++) {
              result.pop();
          }
        */

      }
    }
  }

  boxHeightfield(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    si.convexPolyhedronRepresentation.material = si.material;
    si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
    return 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;
    const w = hfShape.elementSize;
    const radius = convexShape.boundingSphereRadius;
    const worldPillarOffset = convexHeightfield_tmp2;
    const faceList = convexHeightfield_faceList; // Get sphere position to heightfield local!

    const localConvexPos = convexHeightfield_tmp1;
    Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos); // Get the index of the data points to test against

    let iMinX = Math.floor((localConvexPos.x - radius) / w) - 1;
    let iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1;
    let iMinY = Math.floor((localConvexPos.y - radius) / w) - 1;
    let iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1; // Bail out if we are out of the terrain

    if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
      return;
    } // Clamp index to edges


    if (iMinX < 0) {
      iMinX = 0;
    }

    if (iMaxX < 0) {
      iMaxX = 0;
    }

    if (iMinY < 0) {
      iMinY = 0;
    }

    if (iMaxY < 0) {
      iMaxY = 0;
    }

    if (iMinX >= data.length) {
      iMinX = data.length - 1;
    }

    if (iMaxX >= data.length) {
      iMaxX = data.length - 1;
    }

    if (iMaxY >= data[0].length) {
      iMaxY = data[0].length - 1;
    }

    if (iMinY >= data[0].length) {
      iMinY = data[0].length - 1;
    }

    const minMax = [];
    hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
    const min = minMax[0];
    const max = minMax[1]; // Bail out if we're cant touch the bounding height box

    if (localConvexPos.z - radius > max || localConvexPos.z + radius < min) {
      return;
    }

    for (let i = iMinX; i < iMaxX; i++) {
      for (let j = iMinY; j < iMaxY; j++) {
        let intersecting = false; // Lower triangle

        hfShape.getConvexTrianglePillar(i, j, false);
        Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);

        if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
          intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
        }

        if (justTest && intersecting) {
          return true;
        } // Upper triangle


        hfShape.getConvexTrianglePillar(i, j, true);
        Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);

        if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
          intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
        }

        if (justTest && intersecting) {
          return true;
        }
      }
    }
  }

  sphereParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
    // The normal is the unit vector from sphere center to particle center
    const normal = particleSphere_normal;
    normal.set(0, 0, 1);
    xi.vsub(xj, normal);
    const lengthSquared = normal.lengthSquared();

    if (lengthSquared <= sj.radius * sj.radius) {
      if (justTest) {
        return true;
      }

      const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
      normal.normalize();
      r.rj.copy(normal);
      r.rj.scale(sj.radius, r.rj);
      r.ni.copy(normal); // Contact normal

      r.ni.negate(r.ni);
      r.ri.set(0, 0, 0); // Center of particle

      this.result.push(r);
      this.createFrictionEquationsFromContact(r, this.frictionResult);
    }
  }

  planeParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
    const normal = particlePlane_normal;
    normal.set(0, 0, 1);
    bj.quaternion.vmult(normal, normal); // Turn normal according to plane orientation

    const relpos = particlePlane_relpos;
    xi.vsub(bj.position, relpos);
    const dot = normal.dot(relpos);

    if (dot <= 0.0) {
      if (justTest) {
        return true;
      }

      const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
      r.ni.copy(normal); // Contact normal is the plane normal

      r.ni.negate(r.ni);
      r.ri.set(0, 0, 0); // Center of particle
      // Get particle position projected on plane

      const projected = particlePlane_projected;
      normal.scale(normal.dot(xi), projected);
      xi.vsub(projected, projected); //projected.vadd(bj.position,projected);
      // rj is now the projected world position minus plane position

      r.rj.copy(projected);
      this.result.push(r);
      this.createFrictionEquationsFromContact(r, this.frictionResult);
    }
  }

  boxParticle(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    si.convexPolyhedronRepresentation.material = si.material;
    si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
    return this.convexParticle(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  }

  convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
    let penetratedFaceIndex = -1;
    const penetratedFaceNormal = convexParticle_penetratedFaceNormal;
    const worldPenetrationVec = convexParticle_worldPenetrationVec;
    let minPenetration = null;

    const local = convexParticle_local;
    local.copy(xi);
    local.vsub(xj, local); // Convert position to relative the convex origin

    qj.conjugate(cqj);
    cqj.vmult(local, local);

    if (sj.pointIsInside(local)) {
      if (sj.worldVerticesNeedsUpdate) {
        sj.computeWorldVertices(xj, qj);
      }

      if (sj.worldFaceNormalsNeedsUpdate) {
        sj.computeWorldFaceNormals(qj);
      } // For each world polygon in the polyhedra


      for (let i = 0, nfaces = sj.faces.length; i !== nfaces; i++) {
        // Construct world face vertices
        const verts = [sj.worldVertices[sj.faces[i][0]]];
        const normal = sj.worldFaceNormals[i]; // Check how much the particle penetrates the polygon plane.

        xi.vsub(verts[0], convexParticle_vertexToParticle);
        const penetration = -normal.dot(convexParticle_vertexToParticle);

        if (minPenetration === null || Math.abs(penetration) < Math.abs(minPenetration)) {
          if (justTest) {
            return true;
          }

          minPenetration = penetration;
          penetratedFaceIndex = i;
          penetratedFaceNormal.copy(normal);
        }
      }

      if (penetratedFaceIndex !== -1) {
        // Setup contact
        const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
        penetratedFaceNormal.scale(minPenetration, worldPenetrationVec); // rj is the particle position projected to the face

        worldPenetrationVec.vadd(xi, worldPenetrationVec);
        worldPenetrationVec.vsub(xj, worldPenetrationVec);
        r.rj.copy(worldPenetrationVec); //const projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
        //projectedToFace.copy(r.rj);
        //qj.vmult(r.rj,r.rj);

        penetratedFaceNormal.negate(r.ni); // Contact normal

        r.ri.set(0, 0, 0); // Center of particle

        const ri = r.ri;
        const rj = r.rj; // Make relative to bodies

        ri.vadd(xi, ri);
        ri.vsub(bi.position, ri);
        rj.vadd(xj, rj);
        rj.vsub(bj.position, rj);
        this.result.push(r);
        this.createFrictionEquationsFromContact(r, this.frictionResult);
      } else {
        console.warn('Point found inside convex, but did not find penetrating face!');
      }
    }
  }

  heightfieldCylinder(hfShape, convexShape, hfPos, convexPos, hfQuat, convexQuat, hfBody, convexBody, rsi, rsj, justTest) {
    return this.convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest);
  }

  particleCylinder(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
    return this.convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest);
  }

  sphereTrimesh(sphereShape, trimeshShape, spherePos, trimeshPos, sphereQuat, trimeshQuat, sphereBody, trimeshBody, rsi, rsj, justTest) {
    const edgeVertexA = sphereTrimesh_edgeVertexA;
    const edgeVertexB = sphereTrimesh_edgeVertexB;
    const edgeVector = sphereTrimesh_edgeVector;
    const edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
    const localSpherePos = sphereTrimesh_localSpherePos;
    const tmp = sphereTrimesh_tmp;
    const localSphereAABB = sphereTrimesh_localSphereAABB;
    const v2 = sphereTrimesh_v2;
    const relpos = sphereTrimesh_relpos;
    const triangles = sphereTrimesh_triangles; // Convert sphere position to local in the trimesh

    Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos); // Get the aabb of the sphere locally in the trimesh

    const sphereRadius = sphereShape.radius;
    localSphereAABB.lowerBound.set(localSpherePos.x - sphereRadius, localSpherePos.y - sphereRadius, localSpherePos.z - sphereRadius);
    localSphereAABB.upperBound.set(localSpherePos.x + sphereRadius, localSpherePos.y + sphereRadius, localSpherePos.z + sphereRadius);
    trimeshShape.getTrianglesInAABB(localSphereAABB, triangles); //for (let i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
    // Vertices

    const v = sphereTrimesh_v;
    const radiusSquared = sphereShape.radius * sphereShape.radius;

    for (let i = 0; i < triangles.length; i++) {
      for (let j = 0; j < 3; j++) {
        trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v); // Check vertex overlap in sphere

        v.vsub(localSpherePos, relpos);

        if (relpos.lengthSquared() <= radiusSquared) {
          // Safe up
          v2.copy(v);
          Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
          v.vsub(spherePos, relpos);

          if (justTest) {
            return true;
          }

          let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
          r.ni.copy(relpos);
          r.ni.normalize(); // ri is the vector from sphere center to the sphere surface

          r.ri.copy(r.ni);
          r.ri.scale(sphereShape.radius, r.ri);
          r.ri.vadd(spherePos, r.ri);
          r.ri.vsub(sphereBody.position, r.ri);
          r.rj.copy(v);
          r.rj.vsub(trimeshBody.position, r.rj); // Store result

          this.result.push(r);
          this.createFrictionEquationsFromContact(r, this.frictionResult);
        }
      }
    } // Check all edges


    for (let i = 0; i < triangles.length; i++) {
      for (let j = 0; j < 3; j++) {
        trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
        trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + (j + 1) % 3], edgeVertexB);
        edgeVertexB.vsub(edgeVertexA, edgeVector); // Project sphere position to the edge

        localSpherePos.vsub(edgeVertexB, tmp);
        const positionAlongEdgeB = tmp.dot(edgeVector);
        localSpherePos.vsub(edgeVertexA, tmp);
        let positionAlongEdgeA = tmp.dot(edgeVector);

        if (positionAlongEdgeA > 0 && positionAlongEdgeB < 0) {
          // Now check the orthogonal distance from edge to sphere center
          localSpherePos.vsub(edgeVertexA, tmp);
          edgeVectorUnit.copy(edgeVector);
          edgeVectorUnit.normalize();
          positionAlongEdgeA = tmp.dot(edgeVectorUnit);
          edgeVectorUnit.scale(positionAlongEdgeA, tmp);
          tmp.vadd(edgeVertexA, tmp); // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame

          const dist = tmp.distanceTo(localSpherePos);

          if (dist < sphereShape.radius) {
            if (justTest) {
              return true;
            }

            const r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
            tmp.vsub(localSpherePos, r.ni);
            r.ni.normalize();
            r.ni.scale(sphereShape.radius, r.ri);
            r.ri.vadd(spherePos, r.ri);
            r.ri.vsub(sphereBody.position, r.ri);
            Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
            tmp.vsub(trimeshBody.position, r.rj);
            Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
            Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
            this.result.push(r);
            this.createFrictionEquationsFromContact(r, this.frictionResult);
          }
        }
      }
    } // Triangle faces


    const va = sphereTrimesh_va;
    const vb = sphereTrimesh_vb;
    const vc = sphereTrimesh_vc;
    const normal = sphereTrimesh_normal;

    for (let i = 0, N = triangles.length; i !== N; i++) {
      trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
      trimeshShape.getNormal(triangles[i], normal);
      localSpherePos.vsub(va, tmp);
      let dist = tmp.dot(normal);
      normal.scale(dist, tmp);
      localSpherePos.vsub(tmp, tmp); // tmp is now the sphere position projected to the triangle plane

      dist = tmp.distanceTo(localSpherePos);

      if (Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius) {
        if (justTest) {
          return true;
        }

        let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
        tmp.vsub(localSpherePos, r.ni);
        r.ni.normalize();
        r.ni.scale(sphereShape.radius, r.ri);
        r.ri.vadd(spherePos, r.ri);
        r.ri.vsub(sphereBody.position, r.ri);
        Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
        tmp.vsub(trimeshBody.position, r.rj);
        Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
        Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
        this.result.push(r);
        this.createFrictionEquationsFromContact(r, this.frictionResult);
      }
    }

    triangles.length = 0;
  }

  planeTrimesh(planeShape, trimeshShape, planePos, trimeshPos, planeQuat, trimeshQuat, planeBody, trimeshBody, rsi, rsj, justTest) {
    // Make contacts!
    const v = new Vec3();
    const normal = planeTrimesh_normal;
    normal.set(0, 0, 1);
    planeQuat.vmult(normal, normal); // Turn normal according to plane

    for (let i = 0; i < trimeshShape.vertices.length / 3; i++) {
      // Get world vertex from trimesh
      trimeshShape.getVertex(i, v); // Safe up

      const v2 = new Vec3();
      v2.copy(v);
      Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); // Check plane side

      const relpos = planeTrimesh_relpos;
      v.vsub(planePos, relpos);
      const dot = normal.dot(relpos);

      if (dot <= 0.0) {
        if (justTest) {
          return true;
        }

        const r = this.createContactEquation(planeBody, trimeshBody, planeShape, trimeshShape, rsi, rsj);
        r.ni.copy(normal); // Contact normal is the plane normal
        // Get vertex position projected on plane

        const projected = planeTrimesh_projected;
        normal.scale(relpos.dot(normal), projected);
        v.vsub(projected, projected); // ri is the projected world position minus plane position

        r.ri.copy(projected);
        r.ri.vsub(planeBody.position, r.ri);
        r.rj.copy(v);
        r.rj.vsub(trimeshBody.position, r.rj); // Store result

        this.result.push(r);
        this.createFrictionEquationsFromContact(r, this.frictionResult);
      }
    }
  } // convexTrimesh(
  //   si: ConvexPolyhedron, sj: Trimesh, xi: Vec3, xj: Vec3, qi: Quaternion, qj: Quaternion,
  //   bi: Body, bj: Body, rsi?: Shape | null, rsj?: Shape | null,
  //   faceListA?: number[] | null, faceListB?: number[] | null,
  // ) {
  //   const sepAxis = convexConvex_sepAxis;
  //   if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  //       return;
  //   }
  //   // Construct a temp hull for each triangle
  //   const hullB = new ConvexPolyhedron();
  //   hullB.faces = [[0,1,2]];
  //   const va = new Vec3();
  //   const vb = new Vec3();
  //   const vc = new Vec3();
  //   hullB.vertices = [
  //       va,
  //       vb,
  //       vc
  //   ];
  //   for (let i = 0; i < sj.indices.length / 3; i++) {
  //       const triangleNormal = new Vec3();
  //       sj.getNormal(i, triangleNormal);
  //       hullB.faceNormals = [triangleNormal];
  //       sj.getTriangleVertices(i, va, vb, vc);
  //       let d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  //       if(!d){
  //           triangleNormal.scale(-1, triangleNormal);
  //           d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  //           if(!d){
  //               continue;
  //           }
  //       }
  //       const res: ConvexPolyhedronContactPoint[] = [];
  //       const q = convexConvex_q;
  //       si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  //       for(let j = 0; j !== res.length; j++){
  //           const r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  //               ri = r.ri,
  //               rj = r.rj;
  //           r.ni.copy(triangleNormal);
  //           r.ni.negate(r.ni);
  //           res[j].normal.negate(q);
  //           q.mult(res[j].depth, q);
  //           res[j].point.vadd(q, ri);
  //           rj.copy(res[j].point);
  //           // Contact points are in world coordinates. Transform back to relative
  //           ri.vsub(xi,ri);
  //           rj.vsub(xj,rj);
  //           // Make relative to bodies
  //           ri.vadd(xi, ri);
  //           ri.vsub(bi.position, ri);
  //           rj.vadd(xj, rj);
  //           rj.vsub(bj.position, rj);
  //           result.push(r);
  //       }
  //   }
  // }


}
const averageNormal = new Vec3();
const averageContactPointA = new Vec3();
const averageContactPointB = new Vec3();
const tmpVec1 = new Vec3();
const tmpVec2 = new Vec3();
const tmpQuat1 = new Quaternion();
const tmpQuat2 = new Quaternion();

const planeTrimesh_normal = new Vec3();
const planeTrimesh_relpos = new Vec3();
const planeTrimesh_projected = new Vec3();
const sphereTrimesh_normal = new Vec3();
const sphereTrimesh_relpos = new Vec3();
const sphereTrimesh_v = new Vec3();
const sphereTrimesh_v2 = new Vec3();
const sphereTrimesh_edgeVertexA = new Vec3();
const sphereTrimesh_edgeVertexB = new Vec3();
const sphereTrimesh_edgeVector = new Vec3();
const sphereTrimesh_edgeVectorUnit = new Vec3();
const sphereTrimesh_localSpherePos = new Vec3();
const sphereTrimesh_tmp = new Vec3();
const sphereTrimesh_va = new Vec3();
const sphereTrimesh_vb = new Vec3();
const sphereTrimesh_vc = new Vec3();
const sphereTrimesh_localSphereAABB = new AABB();
const sphereTrimesh_triangles = [];
const point_on_plane_to_sphere = new Vec3();
const plane_to_sphere_ortho = new Vec3(); // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html

const pointInPolygon_edge = new Vec3();
const pointInPolygon_edge_x_normal = new Vec3();
const pointInPolygon_vtp = new Vec3();

function pointInPolygon(verts, normal, p) {
  let positiveResult = null;
  const N = verts.length;

  for (let i = 0; i !== N; i++) {
    const v = verts[i]; // Get edge to the next vertex

    const edge = pointInPolygon_edge;
    verts[(i + 1) % N].vsub(v, edge); // Get cross product between polygon normal and the edge

    const edge_x_normal = pointInPolygon_edge_x_normal; //const edge_x_normal = new Vec3();

    edge.cross(normal, edge_x_normal); // Get vector between point and current vertex

    const vertex_to_p = pointInPolygon_vtp;
    p.vsub(v, vertex_to_p); // This dot product determines which side of the edge the point is

    const r = edge_x_normal.dot(vertex_to_p); // If all such dot products have same sign, we are inside the polygon.

    if (positiveResult === null || r > 0 && positiveResult === true || r <= 0 && positiveResult === false) {
      if (positiveResult === null) {
        positiveResult = r > 0;
      }

      continue;
    } else {
      return false; // Encountered some other sign. Exit.
    }
  } // If we got here, all dot products were of the same sign.


  return true;
}

const box_to_sphere = new Vec3();
const sphereBox_ns = new Vec3();
const sphereBox_ns1 = new Vec3();
const sphereBox_ns2 = new Vec3();
const sphereBox_sides = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
const sphereBox_sphere_to_corner = new Vec3();
const sphereBox_side_ns = new Vec3();
const sphereBox_side_ns1 = new Vec3();
const sphereBox_side_ns2 = new Vec3();
const convex_to_sphere = new Vec3();
const sphereConvex_edge = new Vec3();
const sphereConvex_edgeUnit = new Vec3();
const sphereConvex_sphereToCorner = new Vec3();
const sphereConvex_worldCorner = new Vec3();
const sphereConvex_worldNormal = new Vec3();
const sphereConvex_worldPoint = new Vec3();
const sphereConvex_worldSpherePointClosestToPlane = new Vec3();
const sphereConvex_penetrationVec = new Vec3();
const sphereConvex_sphereToWorldPoint = new Vec3();
const planeConvex_v = new Vec3();
const planeConvex_normal = new Vec3();
const planeConvex_relpos = new Vec3();
const planeConvex_projected = new Vec3();
const convexConvex_sepAxis = new Vec3();
const convexConvex_q = new Vec3();
const particlePlane_normal = new Vec3();
const particlePlane_relpos = new Vec3();
const particlePlane_projected = new Vec3();
const particleSphere_normal = new Vec3(); // WIP

const cqj = new Quaternion();
const convexParticle_local = new Vec3();
const convexParticle_penetratedFaceNormal = new Vec3();
const convexParticle_vertexToParticle = new Vec3();
const convexParticle_worldPenetrationVec = new Vec3();
const convexHeightfield_tmp1 = new Vec3();
const convexHeightfield_tmp2 = new Vec3();
const convexHeightfield_faceList = [0];
const sphereHeightfield_tmp1 = new Vec3();
const sphereHeightfield_tmp2 = new Vec3();

class OverlapKeeper {
  /**
   * @todo Remove useless constructor
   */
  constructor() {
    this.current = void 0;
    this.previous = void 0;
    this.current = [];
    this.previous = [];
  }
  /**
   * getKey
   */


  getKey(i, j) {
    if (j < i) {
      const temp = j;
      j = i;
      i = temp;
    }

    return i << 16 | j;
  }
  /**
   * set
   */


  set(i, j) {
    // Insertion sort. This way the diff will have linear complexity.
    const key = this.getKey(i, j);
    const current = this.current;
    let index = 0;

    while (key > current[index]) {
      index++;
    }

    if (key === current[index]) {
      return; // Pair was already added
    }

    for (let j = current.length - 1; j >= index; j--) {
      current[j + 1] = current[j];
    }

    current[index] = key;
  }
  /**
   * tick
   */


  tick() {
    const tmp = this.current;
    this.current = this.previous;
    this.previous = tmp;
    this.current.length = 0;
  }
  /**
   * getDiff
   */


  getDiff(additions, removals) {
    const a = this.current;
    const b = this.previous;
    const al = a.length;
    const bl = b.length;
    let j = 0;

    for (let i = 0; i < al; i++) {
      let found = false;
      const keyA = a[i];

      while (keyA > b[j]) {
        j++;
      }

      found = keyA === b[j];

      if (!found) {
        unpackAndPush(additions, keyA);
      }
    }

    j = 0;

    for (let i = 0; i < bl; i++) {
      let found = false;
      const keyB = b[i];

      while (keyB > a[j]) {
        j++;
      }

      found = a[j] === keyB;

      if (!found) {
        unpackAndPush(removals, keyB);
      }
    }
  }

}

function unpackAndPush(array, key) {
  array.push((key & 0xffff0000) >> 16, key & 0x0000ffff);
}

/**
 * TupleDictionary
 */
class TupleDictionary {
  constructor() {
    this.data = {
      keys: []
    };
  }

  /** get */
  get(i, j) {
    if (i > j) {
      // swap
      const temp = j;
      j = i;
      i = temp;
    }

    return this.data[i + "-" + j];
  }
  /** set */


  set(i, j, value) {
    if (i > j) {
      const temp = j;
      j = i;
      i = temp;
    }

    const key = i + "-" + j; // Check if key already exists

    if (!this.get(i, j)) {
      this.data.keys.push(key);
    }

    this.data[key] = value;
  }
  /** reset */


  reset() {
    const data = this.data;
    const keys = data.keys;

    while (keys.length > 0) {
      const key = keys.pop();
      delete data[key];
    }
  }

}

/**
 * The physics world
 */
class World extends EventTarget {
  /**
   * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks.
   */

  /**
   * Makes bodies go to sleep when they've been inactive.
   * @default false
   */

  /**
   * All the current contacts (instances of ContactEquation) in the world.
   */

  /**
   * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).
   * @default 0
   */

  /**
   * Set to true to use fast quaternion normalization. It is often enough accurate to use.
   * If bodies tend to explode, set to false.
   * @default false
   */

  /**
   * The wall-clock time since simulation start.
   */

  /**
   * Number of timesteps taken since start.
   */

  /**
   * Default and last timestep sizes.
   */

  /**
   * The gravity of the world.
   */

  /**
   * The broadphase algorithm to use.
   * @default NaiveBroadphase
   */

  /**
   * All bodies in this world
   */

  /**
   * True if any bodies are not sleeping, false if every body is sleeping.
   */

  /**
   * The solver algorithm to use.
   * @default GSSolver
   */

  /**
   * collisionMatrix
   */

  /**
   * CollisionMatrix from the previous step.
   */

  /**
   * All added materials.
   * @deprecated
   * @todo Remove
   */

  /**
   * All added contactmaterials.
   */

  /**
   * Used to look up a ContactMaterial given two instances of Material.
   */

  /**
   * The default material of the bodies.
   */

  /**
   * This contact material is used if no suitable contactmaterial is found for a contact.
   */

  /**
   * Time accumulator for interpolation.
   * @see https://gafferongames.com/game-physics/fix-your-timestep/
   */

  /**
   * Dispatched after a body has been added to the world.
   */

  /**
   * Dispatched after a body has been removed from the world.
   */
  constructor(options = {}) {
    super();
    this.dt = void 0;
    this.allowSleep = void 0;
    this.contacts = void 0;
    this.frictionEquations = void 0;
    this.quatNormalizeSkip = void 0;
    this.quatNormalizeFast = void 0;
    this.time = void 0;
    this.stepnumber = void 0;
    this.default_dt = void 0;
    this.nextId = void 0;
    this.gravity = void 0;
    this.broadphase = void 0;
    this.bodies = void 0;
    this.hasActiveBodies = void 0;
    this.solver = void 0;
    this.constraints = void 0;
    this.narrowphase = void 0;
    this.collisionMatrix = void 0;
    this.collisionMatrixPrevious = void 0;
    this.bodyOverlapKeeper = void 0;
    this.shapeOverlapKeeper = void 0;
    this.materials = void 0;
    this.contactmaterials = void 0;
    this.contactMaterialTable = void 0;
    this.defaultMaterial = void 0;
    this.defaultContactMaterial = void 0;
    this.doProfiling = void 0;
    this.profile = void 0;
    this.accumulator = void 0;
    this.subsystems = void 0;
    this.addBodyEvent = void 0;
    this.removeBodyEvent = void 0;
    this.idToBodyMap = void 0;
    this.dt = -1;
    this.allowSleep = !!options.allowSleep;
    this.contacts = [];
    this.frictionEquations = [];
    this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;
    this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;
    this.time = 0.0;
    this.stepnumber = 0;
    this.default_dt = 1 / 60;
    this.nextId = 0;
    this.gravity = new Vec3();

    if (options.gravity) {
      this.gravity.copy(options.gravity);
    }

    this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();
    this.bodies = [];
    this.hasActiveBodies = false;
    this.solver = options.solver !== undefined ? options.solver : new GSSolver();
    this.constraints = [];
    this.narrowphase = new Narrowphase(this);
    this.collisionMatrix = new ArrayCollisionMatrix();
    this.collisionMatrixPrevious = new ArrayCollisionMatrix();
    this.bodyOverlapKeeper = new OverlapKeeper();
    this.shapeOverlapKeeper = new OverlapKeeper();
    this.materials = [];
    this.contactmaterials = [];
    this.contactMaterialTable = new TupleDictionary();
    this.defaultMaterial = new Material('default');
    this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, {
      friction: 0.3,
      restitution: 0.0
    });
    this.doProfiling = false;
    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);
  }
  /**
   * Get the contact material between materials m1 and m2
   * @return The contact material if it was found.
   */


  getContactMaterial(m1, m2) {
    return this.contactMaterialTable.get(m1.id, m2.id);
  }
  /**
   * Get number of objects in the world.
   * @deprecated
   */


  numObjects() {
    return this.bodies.length;
  }
  /**
   * Store old collision state info
   */


  collisionMatrixTick() {
    const temp = this.collisionMatrixPrevious;
    this.collisionMatrixPrevious = this.collisionMatrix;
    this.collisionMatrix = temp;
    this.collisionMatrix.reset();
    this.bodyOverlapKeeper.tick();
    this.shapeOverlapKeeper.tick();
  }
  /**
   * Add a constraint to the simulation.
   */


  addConstraint(c) {
    this.constraints.push(c);
  }
  /**
   * Removes a constraint
   */


  removeConstraint(c) {
    const idx = this.constraints.indexOf(c);

    if (idx !== -1) {
      this.constraints.splice(idx, 1);
    }
  }
  /**
   * Raycast test
   * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
   */


  rayTest(from, to, result) {
    if (result instanceof RaycastResult) {
      // Do raycastClosest
      this.raycastClosest(from, to, {
        skipBackfaces: true
      }, result);
    } else {
      // Do raycastAll
      this.raycastAll(from, to, {
        skipBackfaces: true
      }, result);
    }
  }
  /**
   * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
   * @return True if any body was hit.
   */


  raycastAll(from, to, options = {}, callback) {
    options.mode = Ray.ALL;
    options.from = from;
    options.to = to;
    options.callback = callback;
    return tmpRay.intersectWorld(this, options);
  }
  /**
   * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
   * @return True if any body was hit.
   */


  raycastAny(from, to, options = {}, result) {
    options.mode = Ray.ANY;
    options.from = from;
    options.to = to;
    options.result = result;
    return tmpRay.intersectWorld(this, options);
  }
  /**
   * Ray cast, and return information of the closest hit.
   * @return True if any body was hit.
   */


  raycastClosest(from, to, options = {}, result) {
    options.mode = Ray.CLOSEST;
    options.from = from;
    options.to = to;
    options.result = result;
    return tmpRay.intersectWorld(this, options);
  }
  /**
   * Add a rigid body to the simulation.
   * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
   * @todo Adding an array of bodies should be possible. This would save some loops too
   */


  addBody(body) {
    if (this.bodies.includes(body)) {
      return;
    }

    body.index = this.bodies.length;
    this.bodies.push(body);
    body.world = this;
    body.initPosition.copy(body.position);
    body.initVelocity.copy(body.velocity);
    body.timeLastSleepy = this.time;

    if (body instanceof Body) {
      body.initAngularVelocity.copy(body.angularVelocity);
      body.initQuaternion.copy(body.quaternion);
    }

    this.collisionMatrix.setNumObjects(this.bodies.length);
    this.addBodyEvent.body = body;
    this.idToBodyMap[body.id] = body;
    this.dispatchEvent(this.addBodyEvent);
  }
  /**
   * Remove a rigid body from the simulation.
   */


  removeBody(body) {
    body.world = null;
    const n = this.bodies.length - 1;
    const bodies = this.bodies;
    const idx = bodies.indexOf(body);

    if (idx !== -1) {
      bodies.splice(idx, 1); // Todo: should use a garbage free method
      // Recompute index

      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];
  }
  /**
   * @todo Make a faster map
   */


  getShapeById(id) {
    const bodies = this.bodies;

    for (let i = 0; i < bodies.length; i++) {
      const shapes = bodies[i].shapes;

      for (let j = 0; j < shapes.length; j++) {
        const shape = shapes[j];

        if (shape.id === id) {
          return shape;
        }
      }
    }

    return null;
  }
  /**
   * Adds a material to the World.
   * @deprecated
   * @todo Remove
   */


  addMaterial(m) {
    this.materials.push(m);
  }
  /**
   * Adds a contact material to the World
   */


  addContactMaterial(cmat) {
    // Add contact material
    this.contactmaterials.push(cmat); // Add current contact material to the material table

    this.contactMaterialTable.set(cmat.materials[0].id, cmat.materials[1].id, cmat);
  }
  /**
   * Step the physics world forward in time.
   *
   * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
   *
   * @param dt The fixed time step size to use.
   * @param timeSinceLastCalled The time elapsed since the function was last called.
   * @param maxSubSteps Maximum number of fixed steps to take per function call.
   * @see https://web.archive.org/web/20180426154531/http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World#What_do_the_parameters_to_btDynamicsWorld::stepSimulation_mean.3F
   * @example
   *     // fixed timestepping without interpolation
   *     world.step(1 / 60)
   */


  step(dt, timeSinceLastCalled, maxSubSteps = 10) {
    if (timeSinceLastCalled === undefined) {
      // Fixed, simple stepping
      this.internalStep(dt); // Increment time

      this.time += dt;
    } else {
      this.accumulator += timeSinceLastCalled;
      const t0 = performance.now();
      let substeps = 0;

      while (this.accumulator >= dt && substeps < maxSubSteps) {
        // Do fixed steps to catch up
        this.internalStep(dt);
        this.accumulator -= dt;
        substeps++;

        if (performance.now() - t0 > dt * 1000) {
          // The framerate is not interactive anymore.
          // We are below the target framerate.
          // Better bail out.
          break;
        }
      } // Remove the excess accumulator, since we may not
      // have had enough substeps available to catch up


      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;
    const p1 = World_step_p1;
    const p2 = World_step_p2;
    const N = this.numObjects();
    const bodies = this.bodies;
    const solver = this.solver;
    const gravity = this.gravity;
    const doProfiling = this.doProfiling;
    const profile = this.profile;
    const DYNAMIC = Body.DYNAMIC;
    let profilingStart = -Infinity;
    const constraints = this.constraints;
    const frictionEquationPool = World_step_frictionEquationPool;
    gravity.length();
    const gx = gravity.x;
    const gy = gravity.y;
    const gz = gravity.z;
    let i = 0;

    if (doProfiling) {
      profilingStart = performance.now();
    } // Add gravity to all objects


    for (i = 0; i !== N; i++) {
      const bi = bodies[i];

      if (bi.type === DYNAMIC) {
        // Only for dynamic bodies
        const f = bi.force;
        const m = bi.mass;
        f.x += m * gx;
        f.y += m * gy;
        f.z += m * gz;
      }
    } // Update subsystems


    for (let i = 0, Nsubsystems = this.subsystems.length; i !== Nsubsystems; i++) {
      this.subsystems[i].update();
    } // Collision detection


    if (doProfiling) {
      profilingStart = performance.now();
    }

    p1.length = 0; // Clean up pair arrays from last step

    p2.length = 0;
    this.broadphase.collisionPairs(this, p1, p2);

    if (doProfiling) {
      profile.broadphase = performance.now() - profilingStart;
    } // Remove constrained pairs with collideConnected == false


    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) {
          if (c.bodyA === p1[j] && c.bodyB === p2[j] || c.bodyB === p1[j] && c.bodyA === p2[j]) {
            p1.splice(j, 1);
            p2.splice(j, 1);
          }
        }
      }
    }

    this.collisionMatrixTick(); // Generate contacts

    if (doProfiling) {
      profilingStart = performance.now();
    }

    const oldcontacts = World_step_oldContacts;
    const NoldContacts = contacts.length;

    for (i = 0; i !== NoldContacts; i++) {
      oldcontacts.push(contacts[i]);
    }

    contacts.length = 0; // Transfer FrictionEquation from current list to the pool for reuse

    const NoldFrictionEquations = this.frictionEquations.length;

    for (i = 0; i !== NoldFrictionEquations; i++) {
      frictionEquationPool.push(this.frictionEquations[i]);
    }

    this.frictionEquations.length = 0;
    this.narrowphase.getContacts(p1, p2, this, contacts, oldcontacts, // To be reused
    this.frictionEquations, frictionEquationPool);

    if (doProfiling) {
      profile.narrowphase = performance.now() - profilingStart;
    } // Loop over all collisions


    if (doProfiling) {
      profilingStart = performance.now();
    } // Add all friction eqs


    for (i = 0; i < this.frictionEquations.length; i++) {
      solver.addEquation(this.frictionEquations[i]);
    }

    const ncontacts = contacts.length;

    for (let k = 0; k !== ncontacts; k++) {
      // Current contact
      const c = contacts[k]; // Get current collision indeces

      const bi = c.bi;
      const bj = c.bj;
      const si = c.si;
      const sj = c.sj; // Get collision properties

      let cm;

      if (bi.material && bj.material) {
        cm = this.getContactMaterial(bi.material, bj.material) || this.defaultContactMaterial;
      } else {
        cm = this.defaultContactMaterial;
      } // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;


      cm.friction; // c.restitution = cm.restitution;
      // If friction or restitution were specified in the material, use them

      if (bi.material && bj.material) {
        if (bi.material.friction >= 0 && bj.material.friction >= 0) {
          bi.material.friction * bj.material.friction;
        }

        if (bi.material.restitution >= 0 && bj.material.restitution >= 0) {
          c.restitution = bi.material.restitution * bj.material.restitution;
        }
      } // c.setSpookParams(
      //           cm.contactEquationStiffness,
      //           cm.contactEquationRelaxation,
      //           dt
      //       );


      solver.addEquation(c); // // Add friction constraint equation
      // if(mu > 0){
      // 	// Create 2 tangent equations
      // 	const mug = mu * gnorm;
      // 	const reducedMass = (bi.invMass + bj.invMass);
      // 	if(reducedMass > 0){
      // 		reducedMass = 1/reducedMass;
      // 	}
      // 	const pool = frictionEquationPool;
      // 	const c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
      // 	const c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
      // 	this.frictionEquations.push(c1, c2);
      // 	c1.bi = c2.bi = bi;
      // 	c1.bj = c2.bj = bj;
      // 	c1.minForce = c2.minForce = -mug*reducedMass;
      // 	c1.maxForce = c2.maxForce = mug*reducedMass;
      // 	// Copy over the relative vectors
      // 	c1.ri.copy(c.ri);
      // 	c1.rj.copy(c.rj);
      // 	c2.ri.copy(c.ri);
      // 	c2.rj.copy(c.rj);
      // 	// Construct tangents
      // 	c.ni.tangents(c1.t, c2.t);
      //           // Set spook params
      //           c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
      //           c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
      //           c1.enabled = c2.enabled = c.enabled;
      // 	// Add equations to solver
      // 	solver.addEquation(c1);
      // 	solver.addEquation(c2);
      // }

      if (bi.allowSleep && bi.type === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.type !== Body.STATIC) {
        const speedSquaredB = bj.velocity.lengthSquared() + bj.angularVelocity.lengthSquared();
        const speedLimitSquaredB = bj.sleepSpeedLimit ** 2;

        if (speedSquaredB >= speedLimitSquaredB * 2) {
          bi.wakeUpAfterNarrowphase = true;
        }
      }

      if (bj.allowSleep && bj.type === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.type !== Body.STATIC) {
        const speedSquaredA = bi.velocity.lengthSquared() + bi.angularVelocity.lengthSquared();
        const speedLimitSquaredA = bi.sleepSpeedLimit ** 2;

        if (speedSquaredA >= speedLimitSquaredA * 2) {
          bj.wakeUpAfterNarrowphase = true;
        }
      } // Now we know that i and j are in contact. Set collision matrix state


      this.collisionMatrix.set(bi, bj, true);

      if (!this.collisionMatrixPrevious.get(bi, bj)) {
        // First contact!
        // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.
        World_step_collideEvent.body = bj;
        World_step_collideEvent.contact = c;
        bi.dispatchEvent(World_step_collideEvent);
        World_step_collideEvent.body = bi;
        bj.dispatchEvent(World_step_collideEvent);
      }

      this.bodyOverlapKeeper.set(bi.id, bj.id);
      this.shapeOverlapKeeper.set(si.id, sj.id);
    }

    this.emitContactEvents();

    if (doProfiling) {
      profile.makeContactConstraints = performance.now() - profilingStart;
      profilingStart = performance.now();
    } // Wake up bodies


    for (i = 0; i !== N; i++) {
      const bi = bodies[i];

      if (bi.wakeUpAfterNarrowphase) {
        bi.wakeUp();
        bi.wakeUpAfterNarrowphase = false;
      }
    } // Add user-added constraints


    Nconstraints = constraints.length;

    for (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);
      }
    } // Solve the constrained system


    solver.solve(dt, this);

    if (doProfiling) {
      profile.solve = performance.now() - profilingStart;
    } // Remove all contacts from solver


    solver.removeAllEquations(); // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details

    const pow = Math.pow;

    for (i = 0; i !== N; i++) {
      const bi = bodies[i];

      if (bi.type & DYNAMIC) {
        // Only for dynamic bodies
        const ld = pow(1.0 - bi.linearDamping, dt);
        const v = bi.velocity;
        v.scale(ld, v);
        const av = bi.angularVelocity;

        if (av) {
          const ad = pow(1.0 - bi.angularDamping, dt);
          av.scale(ad, av);
        }
      }
    }

    this.dispatchEvent(World_step_preStepEvent); // Invoke pre-step callbacks

    for (i = 0; i !== N; i++) {
      const bi = bodies[i];

      if (bi.preStep) {
        bi.preStep.call(bi);
      }
    } // Leap frog
    // vnew = v + h*f/m
    // xnew = x + h*vnew


    if (doProfiling) {
      profilingStart = performance.now();
    }

    const stepnumber = this.stepnumber;
    const quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;
    const quatNormalizeFast = this.quatNormalizeFast;

    for (i = 0; i !== N; i++) {
      bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);
    }

    this.clearForces();
    this.broadphase.dirty = true;

    if (doProfiling) {
      profile.integrate = performance.now() - profilingStart;
    } // Update step number


    this.stepnumber += 1;
    this.dispatchEvent(World_step_postStepEvent); // Invoke post-step callbacks

    for (i = 0; i !== N; i++) {
      const bi = bodies[i];
      const postStep = bi.postStep;

      if (postStep) {
        postStep.call(bi);
      }
    } // Sleeping update


    let hasActiveBodies = true;

    if (this.allowSleep) {
      hasActiveBodies = false;

      for (i = 0; i !== N; i++) {
        const bi = bodies[i];
        bi.sleepTick(this.time);

        if (bi.sleepState !== Body.SLEEPING) {
          hasActiveBodies = true;
        }
      }
    }

    this.hasActiveBodies = hasActiveBodies;
  }

  emitContactEvents() {
    const hasBeginContact = this.hasAnyEventListener('beginContact');
    const hasEndContact = this.hasAnyEventListener('endContact');

    if (hasBeginContact || hasEndContact) {
      this.bodyOverlapKeeper.getDiff(additions, removals);
    }

    if (hasBeginContact) {
      for (let i = 0, l = additions.length; i < l; i += 2) {
        beginContactEvent.bodyA = this.getBodyById(additions[i]);
        beginContactEvent.bodyB = this.getBodyById(additions[i + 1]);
        this.dispatchEvent(beginContactEvent);
      }

      beginContactEvent.bodyA = beginContactEvent.bodyB = null;
    }

    if (hasEndContact) {
      for (let i = 0, l = removals.length; i < l; i += 2) {
        endContactEvent.bodyA = this.getBodyById(removals[i]);
        endContactEvent.bodyB = this.getBodyById(removals[i + 1]);
        this.dispatchEvent(endContactEvent);
      }

      endContactEvent.bodyA = endContactEvent.bodyB = null;
    }

    additions.length = removals.length = 0;
    const hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');
    const hasEndShapeContact = this.hasAnyEventListener('endShapeContact');

    if (hasBeginShapeContact || hasEndShapeContact) {
      this.shapeOverlapKeeper.getDiff(additions, removals);
    }

    if (hasBeginShapeContact) {
      for (let i = 0, l = additions.length; i < l; i += 2) {
        const shapeA = this.getShapeById(additions[i]);
        const shapeB = this.getShapeById(additions[i + 1]);
        beginShapeContactEvent.shapeA = shapeA;
        beginShapeContactEvent.shapeB = shapeB;
        if (shapeA) beginShapeContactEvent.bodyA = shapeA.body;
        if (shapeB) beginShapeContactEvent.bodyB = shapeB.body;
        this.dispatchEvent(beginShapeContactEvent);
      }

      beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;
    }

    if (hasEndShapeContact) {
      for (let i = 0, l = removals.length; i < l; i += 2) {
        const shapeA = this.getShapeById(removals[i]);
        const shapeB = this.getShapeById(removals[i + 1]);
        endShapeContactEvent.shapeA = shapeA;
        endShapeContactEvent.shapeB = shapeB;
        if (shapeA) endShapeContactEvent.bodyA = shapeA.body;
        if (shapeB) endShapeContactEvent.bodyB = shapeB.body;
        this.dispatchEvent(endShapeContactEvent);
      }

      endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;
    }
  }
  /**
   * Sets all body forces in the world to zero.
   */


  clearForces() {
    const bodies = this.bodies;
    const N = bodies.length;

    for (let i = 0; i !== N; i++) {
      const b = bodies[i];
      b.force;
      b.torque;
      b.force.set(0, 0, 0);
      b.torque.set(0, 0, 0);
    }
  }

} // Temp stuff

new AABB();
const tmpRay = new Ray(); // performance.now() fallback on Date.now()

const performance = globalThis.performance || {};

if (!performance.now) {
  let nowOffset = Date.now();

  if (performance.timing && performance.timing.navigationStart) {
    nowOffset = performance.timing.navigationStart;
  }

  performance.now = () => Date.now() - nowOffset;
}
// Reusable event objects to save memory.

const World_step_postStepEvent = {
  type: 'postStep'
}; // Dispatched before the world steps forward in time.

const World_step_preStepEvent = {
  type: 'preStep'
};
const World_step_collideEvent = {
  type: Body.COLLIDE_EVENT_NAME,
  body: null,
  contact: null
}; // Pools for unused objects

const World_step_oldContacts = [];
const World_step_frictionEquationPool = []; // Reusable arrays for collision pairs

const World_step_p1 = [];
const World_step_p2 = []; // Stuff for emitContactEvents

const additions = [];
const removals = [];
const beginContactEvent = {
  type: 'beginContact',
  bodyA: null,
  bodyB: null
};
const endContactEvent = {
  type: 'endContact',
  bodyA: null,
  bodyB: null
};
const beginShapeContactEvent = {
  type: 'beginShapeContact',
  bodyA: null,
  bodyB: null,
  shapeA: null,
  shapeB: null
};
const endShapeContactEvent = {
  type: 'endShapeContact',
  bodyA: null,
  bodyB: null,
  shapeA: null,
  shapeB: null
};




/***/ }),

/***/ "./Assets/Components/Animator.re.ts":
/*!******************************************!*\
  !*** ./Assets/Components/Animator.re.ts ***!
  \******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ Animator)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};


class Animator extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.animations = [];
    this._curAnimations = [];
    this.data = [];
    this._selected = 0;
    this.selectedOptions = this.animations.map((elem, i) => i.toString());
    this.stopped = false;
    this.stopping = false;
    this.playLabel = "Play";
    this.actions = {};
    this.animationFinishedListeners = [];
    this.animationFinished = /* @__PURE__ */ __name(() => {
      if (this.stopping) {
        this.stopped = true;
        this.stopping = false;
      }
      this.animationFinishedListeners.forEach((listener) => listener());
      if (this.activeAction.loop === three__WEBPACK_IMPORTED_MODULE_1__.LoopOnce && !this.activeAction.clampWhenFinished) {
        this.mix(this.defaultActionName, 1e-3, false);
      }
    }, "animationFinished");
  }
  animationsHaveChanged() {
    if (this._curAnimations.length !== this.animations.length)
      return true;
    for (let i = 0; i < this._curAnimations.length; i++) {
      if (this._curAnimations[i] !== this.animations[i])
        return true;
    }
    return false;
  }
  updateConfigs() {
    const newConfigs = [];
    for (let i = 0; i < this.animations.length; i++) {
      if (this.data[i]) {
        newConfigs[i] = this.data[i];
        continue;
      }
      newConfigs[i] = {
        actionName: i.toString(),
        playOnce: false,
        maxWeight: 1,
        duration: 1,
        speed: 1
      };
    }
    this._curAnimations = this.animations.slice();
    this.data.splice(0);
    newConfigs.forEach((config) => this.data.push(config));
    this._mixer = this._mixer = new three__WEBPACK_IMPORTED_MODULE_1__.AnimationMixer(this.object3d);
    this.animations.forEach((clip, i) => {
      const action = this._mixer.clipAction(clip);
      clip.name = this.data[i].actionName;
      this.data[i].playOnce && action.setLoop(three__WEBPACK_IMPORTED_MODULE_1__.LoopOnce, 0);
      this.actions[this.data[i].actionName] = { action, config: this.data[i] };
    });
  }
  get selected() {
    this.selectedOptions.splice(0, this.selectedOptions.length, ...this.animations.map((_, i) => i.toString()));
    this.isReady && this.animationsHaveChanged() && this.updateConfigs();
    return this._selected;
  }
  set selected(value) {
    this._selected = value;
    this.updateAnimationConfigInputs();
    this.animationsHaveChanged() && this.updateConfigs();
    if (this.playLabel === "Stop" && !rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning) {
      this.playAction();
    }
  }
  updateAnimationConfigInputs() {
    this.data = this.data;
    const activeConfig = this.data[this._selected];
    this.actionName = activeConfig.actionName;
    this.playOnce = activeConfig.playOnce;
    this.duration = activeConfig.duration;
    this.speed = activeConfig.speed;
  }
  get actionName() {
    const activeConfig = this.data[this.selected];
    return activeConfig ? activeConfig.actionName : "";
  }
  set actionName(value) {
    if (this.selected < 0)
      return;
    const activeConfig = this.data[this.selected];
    if (!activeConfig)
      return;
    activeConfig.actionName = value;
  }
  get playOnce() {
    const activeConfig = this.data[this.selected];
    return activeConfig ? activeConfig.playOnce : false;
  }
  set playOnce(value) {
    if (this.selected < 0)
      return;
    const activeConfig = this.data[this.selected];
    if (!activeConfig)
      return;
    activeConfig.playOnce = value;
  }
  get duration() {
    const activeConfig = this.data[this.selected];
    return activeConfig ? activeConfig.duration : 1;
  }
  set duration(value) {
    if (this.selected < 0)
      return;
    const activeConfig = this.data[this.selected];
    if (!activeConfig)
      return;
    activeConfig.duration = value;
  }
  get speed() {
    const activeConfig = this.data[this.selected];
    return activeConfig ? activeConfig.speed : 1;
  }
  set speed(value) {
    if (this.selected < 0)
      return;
    const activeConfig = this.data[this.selected];
    if (!activeConfig)
      return;
    activeConfig.speed = Number(value);
  }
  get isActive() {
    return !this.stopped && !this.stopping;
  }
  stop() {
    this.stopping = true;
  }
  resume() {
    this.stopped = false;
    this.stopping = false;
  }
  play() {
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning)
      return;
    if (this.playLabel === "Play" && !this.editorUpdate) {
      this.mixer;
      this.animationsHaveChanged() && this.updateConfigs();
      this.playAction();
      this.editorUpdate = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.onUpdate((sceneController) => {
        if (sceneController === rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime)
          return;
        this.mixer.update(sceneController.deltaTime * this.speed);
      });
    } else if (this.playLabel === "Stop") {
      this.playLabel = "Play";
      this.stopAction();
      this.editorUpdate?.stop();
      this.editorUpdate = void 0;
    }
  }
  stopAction() {
    this.mixer.existingAction(this.animations[this.selected])?.reset();
    this.mixer.stopAllAction();
  }
  playAction() {
    this.stopAction();
    const action = this.actions[this.actionName];
    if (!this.actions[this.actionName])
      return;
    this.playLabel = "Stop";
    action.action.play();
  }
  get mixer() {
    if (!this._mixer) {
      this._mixer = new three__WEBPACK_IMPORTED_MODULE_1__.AnimationMixer(this.object3d);
      this.animations.forEach((clip, i) => {
        const action = this._mixer.clipAction(clip);
        clip.name = this.data[i].actionName;
        this.data[i].playOnce && action.setLoop(three__WEBPACK_IMPORTED_MODULE_1__.LoopOnce, 0);
        this.actions[this.data[i].actionName] = { action, config: this.data[i] };
      });
    }
    return this._mixer;
  }
  awake() {
    this.editorUpdate?.stop();
    this.editorUpdate = void 0;
  }
  start() {
    this.mixer.existingAction(this.animations[this.selected])?.reset();
    this.mixer.stopAllAction();
    const configs = this.data;
    this.animations.forEach((clip, i) => {
      const clipConfig = configs[i];
      clipConfig.duration && (clip.duration = clipConfig.duration);
      const action = this.mixer.existingAction(clip);
      if (!action)
        return;
      action.play();
      clipConfig.playOnce && action.setLoop(three__WEBPACK_IMPORTED_MODULE_1__.LoopOnce, 0);
      this.setWeight(action, this.selected === i ? 1 : 0);
    });
    this.mixer.removeEventListener("finished", this.animationFinished);
    this.mixer.addEventListener("finished", this.animationFinished);
    this.activeAction = this.defaultAction;
    this.mix(Object.keys(this.actions)[0]);
  }
  update() {
    if (this.stopped)
      return;
    this.mixer.update(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.deltaTime * this.actions[this.activeAction.getClip().name].config.speed);
  }
  getAction(index) {
    return this.actions[index].action;
  }
  setWeight(action, weight) {
    action.enabled = true;
    action.time = 0;
    action.setEffectiveTimeScale(1);
    action.setEffectiveWeight(weight);
  }
  getWeight(actionName) {
    return this.getAction(actionName).getEffectiveWeight();
  }
  get defaultAction() {
    return this.getAction(this.defaultActionName);
  }
  get defaultActionName() {
    return Object.keys(this.actions)[0];
  }
  onAnimationFinished(cb) {
    this.animationFinishedListeners.push(cb);
  }
  mix(actionName, transitionTime = 0.1, warp = true, weight = 1) {
    const action = this.getAction(actionName);
    action.reset();
    this.setWeight(action, weight);
    action.crossFadeFrom(this.activeAction, transitionTime, warp);
    this.activeAction = action;
  }
}
__name(Animator, "Animator");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.list.animation()
], Animator.prototype, "animations", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.data()
], Animator.prototype, "data", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.select()
], Animator.prototype, "selected", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.text()
], Animator.prototype, "actionName", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], Animator.prototype, "playOnce", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], Animator.prototype, "duration", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], Animator.prototype, "speed", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.button()
], Animator.prototype, "play", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(Animator);


/***/ }),

/***/ "./Assets/Components/BallRaycastReceiver.re.ts":
/*!*****************************************************!*\
  !*** ./Assets/Components/BallRaycastReceiver.re.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ BallRaycastReceiver)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _RaycastReceiver_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./RaycastReceiver.re */ "./Assets/Components/RaycastReceiver.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};


class BallRaycastReceiver extends _RaycastReceiver_re__WEBPACK_IMPORTED_MODULE_1__["default"] {
  awake() {
  }
  start() {
    if (!this.highlightMaterial) {
      rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Debug.logError("BallRaycastReceiver has no highlight material set");
    }
  }
  update() {
  }
  onMouseOver(intersect) {
    var currentObj = intersect.object;
    this.originalMaterial = currentObj.material;
    if (this.highlightMaterial) {
      currentObj.material = this.highlightMaterial;
    }
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.rogueDOMContainer.style.cursor = "pointer";
    return true;
  }
  onMouseOut() {
    this.object3d.material = this.originalMaterial;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.rogueDOMContainer.style.cursor = "default";
    return true;
  }
}
__name(BallRaycastReceiver, "BallRaycastReceiver");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.material()
], BallRaycastReceiver.prototype, "highlightMaterial", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(BallRaycastReceiver);


/***/ }),

/***/ "./Assets/Components/CannonMovementController.re.ts":
/*!**********************************************************!*\
  !*** ./Assets/Components/CannonMovementController.re.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonMovementController)
/* harmony export */ });
/* harmony import */ var _RE_BeardScript_rogue_cannon_Components_CannonBody_re__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @RE/BeardScript/rogue-cannon/Components/CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
/* harmony import */ var Assets_Library_GetForwardVector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! Assets/Library/GetForwardVector */ "./Assets/Library/GetForwardVector.ts");
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _FloorCheckComponent_re__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./FloorCheckComponent.re */ "./Assets/Components/FloorCheckComponent.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};






class CannonMovementController extends rogue_engine__WEBPACK_IMPORTED_MODULE_2__.Component {
  constructor() {
    super(...arguments);
    this.speed = 1;
    this.jumpStrength = 3;
  }
  awake() {
    this.bodyComponent = rogue_engine__WEBPACK_IMPORTED_MODULE_2__.getComponent(_RE_BeardScript_rogue_cannon_Components_CannonBody_re__WEBPACK_IMPORTED_MODULE_0__["default"], this.object3d);
  }
  start() {
    this.vectorCalculator = new Assets_Library_GetForwardVector__WEBPACK_IMPORTED_MODULE_1__["default"](rogue_engine__WEBPACK_IMPORTED_MODULE_2__.Runtime.camera);
  }
  update() {
    let direction = { x: 0, y: 0, z: 0 };
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_2__.Input.keyboard.getKeyPressed("KeyW")) {
      direction.x += 1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_2__.Input.keyboard.getKeyPressed("KeyA")) {
      direction.y += -1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_2__.Input.keyboard.getKeyPressed("KeyS")) {
      direction.x += -1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_2__.Input.keyboard.getKeyPressed("KeyD")) {
      direction.y += 1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_2__.Input.keyboard.getKeyPressed("Space")) {
      direction.z = 1;
    }
    if (direction.x != 0) {
      this.moveForward(direction.x * this.speed);
    }
    if (direction.y != 0) {
      this.moveRight(direction.y * this.speed);
    }
    if (direction.z != 0) {
      const floorCheckComponent = rogue_engine__WEBPACK_IMPORTED_MODULE_2__.getComponent(_FloorCheckComponent_re__WEBPACK_IMPORTED_MODULE_4__["default"], this.object3d);
      if (floorCheckComponent) {
        if (floorCheckComponent.isOnFloor) {
          this.bodyComponent.body.applyImpulse(new cannon_es__WEBPACK_IMPORTED_MODULE_5__.Vec3(0, this.jumpStrength, 0), new cannon_es__WEBPACK_IMPORTED_MODULE_5__.Vec3(this.object3d.position.x, this.object3d.position.y, this.object3d.position.z));
        }
      }
    }
  }
  moveForward(distance) {
    let scaledVelocity = new three__WEBPACK_IMPORTED_MODULE_3__.Vector3();
    scaledVelocity.addScaledVector(this.vectorCalculator.getForward(), distance);
    this.bodyComponent.body.applyForce(new cannon_es__WEBPACK_IMPORTED_MODULE_5__.Vec3(scaledVelocity.x, scaledVelocity.y, scaledVelocity.z));
  }
  moveRight(distance) {
    let scaledVelocity = new three__WEBPACK_IMPORTED_MODULE_3__.Vector3();
    scaledVelocity.addScaledVector(this.vectorCalculator.getRight(), distance);
    this.bodyComponent.body.applyForce(new cannon_es__WEBPACK_IMPORTED_MODULE_5__.Vec3(scaledVelocity.x, scaledVelocity.y, scaledVelocity.z));
  }
}
__name(CannonMovementController, "CannonMovementController");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_2__.props.num()
], CannonMovementController.prototype, "speed", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_2__.props.num()
], CannonMovementController.prototype, "jumpStrength", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_2__.registerComponent(CannonMovementController);


/***/ }),

/***/ "./Assets/Components/FaceDirectionOfVelocityComponent.re.ts":
/*!******************************************************************!*\
  !*** ./Assets/Components/FaceDirectionOfVelocityComponent.re.ts ***!
  \******************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ FaceDirectionOfVelocityComponent)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

class FaceDirectionOfVelocityComponent extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  awake() {
  }
  start() {
  }
  update() {
  }
}
__name(FaceDirectionOfVelocityComponent, "FaceDirectionOfVelocityComponent");
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(FaceDirectionOfVelocityComponent);


/***/ }),

/***/ "./Assets/Components/FloorCheckComponent.re.ts":
/*!*****************************************************!*\
  !*** ./Assets/Components/FloorCheckComponent.re.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ FloorCheckComponent)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};


class FloorCheckComponent extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.down = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, -1, 0);
    this.near = 0;
    this.far = Infinity;
    this.isOnFloor = false;
    this.touchingFloorDistance = 1;
  }
  awake() {
    this.raycaster = new three__WEBPACK_IMPORTED_MODULE_1__.Raycaster(this.object3d.position, this.down, this.near, this.far);
    this.childrenToFilter = this.getAllChildrenUuids(this.object3d);
  }
  getAllChildrenUuids(child) {
    return child.children.flatMap((innerChild) => {
      if (innerChild.children.length > 0) {
        return this.getAllChildrenUuids(innerChild);
      }
      return innerChild.uuid;
    });
  }
  start() {
  }
  update() {
    this.raycaster.set(this.object3d.position, this.down);
    this.isOnFloor = false;
    let intersects = this.raycaster.intersectObjects(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.children);
    const notMeIntersects = intersects.filter((intersect) => {
      return !this.childrenToFilter.includes(intersect.object.uuid);
    });
    notMeIntersects.forEach((intersect) => {
      this.isOnFloor = this.isOnFloor || intersect.distance <= this.touchingFloorDistance;
    });
  }
}
__name(FloorCheckComponent, "FloorCheckComponent");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], FloorCheckComponent.prototype, "near", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], FloorCheckComponent.prototype, "far", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], FloorCheckComponent.prototype, "touchingFloorDistance", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(FloorCheckComponent);


/***/ }),

/***/ "./Assets/Components/FloorRaycastReceiver.re.ts":
/*!******************************************************!*\
  !*** ./Assets/Components/FloorRaycastReceiver.re.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ FloorRaycastReceiver)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _RaycastReceiver_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./RaycastReceiver.re */ "./Assets/Components/RaycastReceiver.re.ts");
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });


class FloorRaycastReceiver extends _RaycastReceiver_re__WEBPACK_IMPORTED_MODULE_1__["default"] {
  awake() {
  }
  start() {
  }
  update() {
  }
  onMouseOver(intersect) {
    let positionOnObject = { x: (intersect.uv.x - 0.5) * intersect.object.geometry.parameters.width, z: -(intersect.uv.y - 0.5) * intersect.object.geometry.parameters.depth };
    const targetSelector = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.getObjectByName("GridTarget");
    if (!targetSelector) {
      return true;
    }
    targetSelector.position.setX(Math.floor(positionOnObject.x) + 0.5);
    targetSelector.position.setY(0);
    targetSelector.position.setZ(Math.floor(positionOnObject.z) + 0.5);
    return true;
  }
  onMouseOut() {
    return true;
  }
}
__name(FloorRaycastReceiver, "FloorRaycastReceiver");
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(FloorRaycastReceiver);


/***/ }),

/***/ "./Assets/Components/GameLogic.re.ts":
/*!*******************************************!*\
  !*** ./Assets/Components/GameLogic.re.ts ***!
  \*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ GameLogic)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};


class GameLogic extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.placementMode = 3;
  }
  awake() {
  }
  start() {
    for (let i = 0; i < 100; i++) {
      const newBuilding = this.buildings[Math.floor(3 * Math.random())].instantiate();
      const randomPosition = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(Math.floor(98 * Math.random()) - 49, 0.1, Math.floor(98 * Math.random()) - 49);
      newBuilding.position.copy(randomPosition);
    }
    this.focusPoint = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.getObjectByName("FocusPoint");
  }
  update() {
  }
}
__name(GameLogic, "GameLogic");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.list.prefab()
], GameLogic.prototype, "buildings", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(GameLogic);


/***/ }),

/***/ "./Assets/Components/MovementController.re.ts":
/*!****************************************************!*\
  !*** ./Assets/Components/MovementController.re.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ MovementController)
/* harmony export */ });
/* harmony import */ var Assets_Library_GetForwardVector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! Assets/Library/GetForwardVector */ "./Assets/Library/GetForwardVector.ts");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_1__);
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};


class MovementController extends rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Component {
  constructor() {
    super(...arguments);
    this.speed = 1;
  }
  awake() {
  }
  start() {
    this.vectorCalculator = new Assets_Library_GetForwardVector__WEBPACK_IMPORTED_MODULE_0__["default"](rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Runtime.camera);
  }
  update() {
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyW")) {
      this.moveForward(1 * this.speed);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyA")) {
      this.moveRight(-1 * this.speed);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyS")) {
      this.moveForward(-1 * this.speed);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyD")) {
      this.moveRight(1 * this.speed);
    }
  }
  moveForward(distance) {
    this.object3d.position.addScaledVector(this.vectorCalculator.getForward(), distance);
  }
  moveRight(distance) {
    this.object3d.position.addScaledVector(this.vectorCalculator.getRight(), distance);
  }
}
__name(MovementController, "MovementController");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_1__.props.num()
], MovementController.prototype, "speed", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_1__.registerComponent(MovementController);


/***/ }),

/***/ "./Assets/Components/RapierMovementController.re.ts":
/*!**********************************************************!*\
  !*** ./Assets/Components/RapierMovementController.re.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierMovementController)
/* harmony export */ });
/* harmony import */ var Assets_Library_GetForwardVector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! Assets/Library/GetForwardVector */ "./Assets/Library/GetForwardVector.ts");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _FloorCheckComponent_re__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./FloorCheckComponent.re */ "./Assets/Components/FloorCheckComponent.re.ts");
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var _RE_RogueEngine_rogue_rapier_Components_RapierBody_re__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @RE/RogueEngine/rogue-rapier/Components/RapierBody.re */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierBody.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};






class RapierMovementController extends rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Component {
  constructor() {
    super(...arguments);
    this.speed = 1;
    this.jumpStrength = 10;
    this.jumpVector = new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_5__["default"].Vector3(0, 1, 0);
    this.scaledVelocity = new three__WEBPACK_IMPORTED_MODULE_2__.Vector3(0, 0, 0);
    this.rapierScaledVelocity = new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_5__["default"].Vector3(0, 0, 0);
  }
  awake() {
    this.bodyComponent = rogue_engine__WEBPACK_IMPORTED_MODULE_1__.getComponent(_RE_RogueEngine_rogue_rapier_Components_RapierBody_re__WEBPACK_IMPORTED_MODULE_4__["default"], this.object3d);
  }
  start() {
    this.vectorCalculator = new Assets_Library_GetForwardVector__WEBPACK_IMPORTED_MODULE_0__["default"](rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Runtime.camera);
  }
  update() {
    let direction = { x: 0, y: 0, z: 0 };
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyW")) {
      direction.x += 1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyA")) {
      direction.y += -1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyS")) {
      direction.x += -1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("KeyD")) {
      direction.y += 1;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_1__.Input.keyboard.getKeyPressed("Space")) {
      direction.z = 1;
    }
    if (direction.x != 0) {
      this.moveForward(direction.x * this.speed);
    }
    if (direction.y != 0) {
      this.moveRight(direction.y * this.speed);
    }
    if (direction.z != 0) {
      const floorCheckComponent = rogue_engine__WEBPACK_IMPORTED_MODULE_1__.getComponent(_FloorCheckComponent_re__WEBPACK_IMPORTED_MODULE_3__["default"], this.object3d);
      if (floorCheckComponent) {
        if (floorCheckComponent.isOnFloor) {
          this.jumpVector.y = this.jumpStrength;
          this.bodyComponent.body.applyImpulse(this.jumpVector, true);
        }
      }
    }
  }
  moveForward(distance) {
    this.scaledVelocity.set(0, 0, 0);
    this.scaledVelocity.addScaledVector(this.vectorCalculator.getForward(), distance);
    this.rapierScaledVelocity.x = this.scaledVelocity.x;
    this.rapierScaledVelocity.y = this.scaledVelocity.y;
    this.rapierScaledVelocity.z = this.scaledVelocity.z;
    this.bodyComponent.body.applyImpulse(this.rapierScaledVelocity, true);
  }
  moveRight(distance) {
    this.scaledVelocity.set(0, 0, 0);
    this.scaledVelocity.addScaledVector(this.vectorCalculator.getRight(), distance);
    this.rapierScaledVelocity.x = this.scaledVelocity.x;
    this.rapierScaledVelocity.y = this.scaledVelocity.y;
    this.rapierScaledVelocity.z = this.scaledVelocity.z;
    this.bodyComponent.body.applyImpulse(this.rapierScaledVelocity, true);
  }
}
__name(RapierMovementController, "RapierMovementController");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_1__.props.num()
], RapierMovementController.prototype, "speed", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_1__.props.num()
], RapierMovementController.prototype, "jumpStrength", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_1__.registerComponent(RapierMovementController);


/***/ }),

/***/ "./Assets/Components/RaycastReceiver.re.ts":
/*!*************************************************!*\
  !*** ./Assets/Components/RaycastReceiver.re.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RaycastReceiver)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

class RaycastReceiver extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  onMouseOver(intersect) {
    throw new Error("Abstract class: Please inherit from this class to use it's behavior");
  }
  onMouseOut() {
    throw new Error("Abstract class: Please inherit from this class to use it's behavior");
  }
}
__name(RaycastReceiver, "RaycastReceiver");
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RaycastReceiver);


/***/ }),

/***/ "./Assets/Components/RaycastReporter.re.ts":
/*!*************************************************!*\
  !*** ./Assets/Components/RaycastReporter.re.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RaycastReporter)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _RaycastReceiver_re__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./RaycastReceiver.re */ "./Assets/Components/RaycastReceiver.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};



class RaycastReporter extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.receiverClass = ["RaycastReceiver"];
    this.allHovered = [];
  }
  awake() {
  }
  start() {
    this.mouse = new three__WEBPACK_IMPORTED_MODULE_1__.Vector2(0, 0);
    this.raycaster = new three__WEBPACK_IMPORTED_MODULE_1__.Raycaster();
    this.updated = false;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.touch.enabled = true;
  }
  normalizeScreenInput(browserVector, gameVector) {
    const bounds = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.rogueDOMContainer.getBoundingClientRect();
    gameVector.x = (browserVector.x - bounds.left) / bounds.width * 2 - 1;
    gameVector.y = -((browserVector.y - bounds.top) / bounds.height) * 2 + 1;
  }
  getMouseInput() {
    if (!rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.isMoving) {
      return;
    }
    this.normalizeScreenInput(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse, this.mouse);
    this.updated = true;
  }
  getTouchInput() {
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.touch.touches.length == 0) {
      return;
    }
    this.normalizeScreenInput(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.touch.touches[0], this.mouse);
    this.updated = true;
  }
  update() {
    this.updated = false;
    this.getMouseInput();
    this.getTouchInput();
    if (!this.updated) {
      return;
    }
    this.raycaster.setFromCamera(this.mouse, this.object3d);
    let intersects = this.raycaster.intersectObjects(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.children);
    let listeningComponents = [];
    intersects.forEach((intersect) => {
      let object3d = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.getObjectByProperty("uuid", intersect.object.uuid);
      if (object3d == null) {
        console.error("Could not find object in current scene");
        return;
      }
      let component = this.crawlSceneToFindReceiver(object3d);
      if (component == null) {
        return;
      }
      listeningComponents = listeningComponents.filter((dataThing) => {
        if (component == null) {
          return;
        }
        dataThing.component.object3d.uuid != component.object3d.uuid;
      });
      listeningComponents.push(new DataThing(component, intersect));
    });
    for (let i = 0; i < this.allHovered.length; i++) {
      let dataThing = this.allHovered[i];
      if (!listeningComponents.includes(dataThing)) {
        dataThing.component.onMouseOut();
      }
    }
    this.allHovered = [];
    for (let i = 0; i < listeningComponents.length; i++) {
      let dataThing = listeningComponents[i];
      this.allHovered.push(dataThing);
      if (dataThing.component && dataThing.component.onMouseOver(dataThing.intersect) === false) {
        break;
      }
    }
  }
  crawlSceneToFindReceiver(object3d) {
    const component = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_RaycastReceiver_re__WEBPACK_IMPORTED_MODULE_2__["default"], object3d);
    if (component != null) {
      return component;
    }
    if (object3d.parent == null) {
      return null;
    }
    return this.crawlSceneToFindReceiver(object3d.parent);
  }
}
__name(RaycastReporter, "RaycastReporter");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.PropList("String")
], RaycastReporter.prototype, "receiverClass", 2);
class DataThing {
  constructor(component, intersect) {
    this.component = component;
    this.intersect = intersect;
  }
}
__name(DataThing, "DataThing");
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RaycastReporter);


/***/ }),

/***/ "./Assets/Library/GetForwardVector.ts":
/*!********************************************!*\
  !*** ./Assets/Library/GetForwardVector.ts ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ GetForwardVector)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });


class GetForwardVector {
  constructor(object3d) {
    this.vector = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.object3d = object3d;
  }
  getForward() {
    this.vector.set(0, 0, 0);
    if (!this.object3d) {
      rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Debug.logError("No Object3D provided to get forward vector from.");
      return this.vector;
    }
    this.vector.setFromMatrixColumn(this.object3d.matrix, 0);
    this.vector.crossVectors(this.object3d.up, this.vector);
    return this.vector.normalize();
  }
  getRight() {
    if (!this.object3d) {
      rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Debug.logError("No Object3D provided to get right vector from.");
      return this.vector;
    }
    this.vector.setFromMatrixColumn(this.object3d.matrix, 0);
    return this.vector.normalize();
  }
}
__name(GetForwardVector, "GetForwardVector");


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts":
/*!************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts ***!
  \************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonBody)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




const _CannonBody = class extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this._isTrigger = false;
    this._angularDamping = 0;
    this._linearDamping = 0;
    this._angularFactor = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(1, 1, 1);
    this._linearFactor = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(1, 1, 1);
    this._mass = 1;
    this._useDefaultMass = true;
    this._type = 0;
    this.typeOptions = [
      "Dynamic",
      "Static",
      "Kinematic"
    ];
    this.worldPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.worldRot = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.newBodyPos = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3();
    this.newBodyRot = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Quaternion();
    this.newPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.newRot = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.matrixA = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixB = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixC = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.onCollisionEnterListeners = [];
    this.onCollisionStayListeners = [];
    this.onCollisionExitListeners = [];
    this.handleOnCollide = /* @__PURE__ */ __name((event) => {
      const bj = event.contact.bj;
      const bi = event.contact.bi;
      const collision = {
        other: bj !== this.body ? bj : bi,
        contact: event.contact
      };
      this.triggerCollision = collision;
    }, "handleOnCollide");
  }
  get type() {
    return this._type;
  }
  set type(value) {
    this._type = value;
    let type = 1;
    if (value === 0)
      type = 1;
    if (value === 1)
      type = 2;
    if (value === 2)
      type = 4;
    this.body && (this.body.type = type);
  }
  get angularDamping() {
    return this._angularDamping;
  }
  set angularDamping(value) {
    this._angularDamping = value;
    this.body && (this.body.angularDamping = value);
  }
  get linearDamping() {
    return this._linearDamping;
  }
  set linearDamping(value) {
    this._linearDamping = value;
    this.body && (this.body.linearDamping = value);
  }
  get mass() {
    return this._mass;
  }
  set mass(value) {
    this._mass = value;
    this.body && (this.body.mass = value);
    this.body && this.body.updateMassProperties();
  }
  get linearFactor() {
    return this._linearFactor;
  }
  set linearFactor(value) {
    this._linearFactor = value;
    this.body && this.body.linearFactor.set(value.x, value.y, value.z);
  }
  get angularFactor() {
    return this._angularFactor;
  }
  set angularFactor(value) {
    this._angularFactor = value;
    this.body && this.body.angularFactor.set(value.x, value.y, value.z);
  }
  get isTrigger() {
    return this._isTrigger;
  }
  set isTrigger(value) {
    this._isTrigger = value;
    this.body && (this.body.isTrigger = value);
  }
  static findByBody(body) {
    let bodyComponent;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.traverseComponents((component) => {
      if (bodyComponent)
        return;
      if (component instanceof _CannonBody && component.body === body) {
        bodyComponent = component;
      }
    });
    return bodyComponent;
  }
  awake() {
    if (!this.body) {
      this.createBody();
    }
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.onStop(() => {
      this.handleOnCollide && this.body.removeEventListener("collide", this.handleOnCollide);
    });
  }
  start() {
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().addBody(this.body);
    this.copyObjectTransform();
  }
  onDisabled() {
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().removeBody(this.body);
  }
  beforeUpdate() {
    if (this.body.mass !== this._mass) {
      this.mass = this._mass;
    }
    this.body && (this.body.type = this.getBodyType());
    this.body.type !== cannon_es__WEBPACK_IMPORTED_MODULE_3__.BODY_TYPES.STATIC && this.updatePhysics();
    if (this.triggerCollision !== void 0 && this.onCollideCB) {
      this.onCollideCB(this.triggerCollision);
      this.triggerCollision = void 0;
    }
  }
  onBeforeRemoved() {
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().removeBody(this.body);
  }
  onCollisionEnter(cb) {
    this.onCollisionEnterListeners.push(cb);
  }
  onCollisionStay(cb) {
    this.onCollisionStayListeners.push(cb);
  }
  onCollisionExit(cb) {
    this.onCollisionExitListeners.push(cb);
  }
  onCollide(callback) {
    this.onCollideCB = callback;
    this.body.removeEventListener("collide", this.handleOnCollide);
    this.body.addEventListener("collide", this.handleOnCollide);
  }
  setQuaternion(quaternion) {
    const q = quaternion;
    this.body.quaternion.set(q.x, q.y, q.z, q.w);
  }
  setPosition(position) {
    const pos = position;
    this.body.position.set(pos.x, pos.y, pos.z);
  }
  getBodyType() {
    let type = 1;
    if (this._type === 0)
      type = 1;
    if (this._type === 1)
      type = 2;
    if (this._type === 2)
      type = 4;
    return type;
  }
  createBody() {
    this.body = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Body({
      type: this.getBodyType(),
      angularDamping: this.angularDamping,
      linearDamping: this.linearDamping,
      linearFactor: new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3(this.linearFactor.x, this.linearFactor.y, this.linearFactor.z),
      angularFactor: new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3(this.angularFactor.x, this.angularFactor.y, this.angularFactor.z),
      isTrigger: this.isTrigger,
      mass: this._mass
    });
    this.copyObjectTransform();
  }
  createShape() {
  }
  copyObjectTransform() {
    this.object3d.parent?.updateMatrixWorld(true);
    this.object3d.getWorldPosition(this.worldPos);
    this.object3d.getWorldQuaternion(this.worldRot);
    this.newBodyPos.set(this.worldPos.x, this.worldPos.y, this.worldPos.z);
    this.newBodyRot.set(this.worldRot.x, this.worldRot.y, this.worldRot.z, this.worldRot.w);
    this.body.quaternion.copy(this.newBodyRot);
    this.body.position.copy(this.newBodyPos);
  }
  copyBodyTransform() {
    this.copyBodyPosition();
    this.copyBodyRotation();
  }
  copyBodyPosition() {
    this.newPos.set(this.body.interpolatedPosition.x, this.body.interpolatedPosition.y, this.body.interpolatedPosition.z);
    if (!this.object3d.parent)
      return;
    this.object3d.parent?.worldToLocal(this.newPos);
    this.object3d.position.copy(this.newPos);
  }
  copyBodyRotation() {
    this.newRot.set(this.body.quaternion.x, this.body.quaternion.y, this.body.quaternion.z, this.body.quaternion.w);
    this.matrixA.makeRotationFromQuaternion(this.newRot);
    this.object3d.updateMatrixWorld();
    this.matrixB.copy(this.object3d.parent.matrixWorld).invert();
    this.matrixC.extractRotation(this.matrixB);
    this.matrixA.premultiply(this.matrixC);
    this.object3d.quaternion.setFromRotationMatrix(this.matrixA);
  }
  updatePhysics() {
    this.copyBodyTransform();
  }
};
let CannonBody = _CannonBody;
__name(CannonBody, "CannonBody");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.select()
], CannonBody.prototype, "type", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonBody.prototype, "angularDamping", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonBody.prototype, "linearDamping", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonBody.prototype, "mass", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonBody.prototype, "linearFactor", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonBody.prototype, "angularFactor", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], CannonBody.prototype, "isTrigger", 1);

rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonBody);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonConfig.re.ts":
/*!**************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonConfig.re.ts ***!
  \**************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonConfig)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class CannonConfig extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this._defaultFriction = 0.01;
    this._defaultRestitution = 0;
    this.maxSubSteps = 1;
    this.gravity = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, -9.82, 0);
    this.contacts = [];
    this.activeCollisions = {};
  }
  get defaultFriction() {
    return this._defaultFriction;
  }
  set defaultFriction(value) {
    this._defaultFriction = value;
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().defaultContactMaterial.friction = value;
  }
  get defaultRestitution() {
    return this._defaultRestitution;
  }
  set defaultRestitution(value) {
    this._defaultRestitution = value;
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().defaultContactMaterial.restitution = value;
  }
  start() {
    this.contacts = [];
    this.activeCollisions = {};
    cannon_es__WEBPACK_IMPORTED_MODULE_4__.Body.idCounter = 0;
    cannon_es__WEBPACK_IMPORTED_MODULE_4__.ContactEquation.idCounter = 0;
    cannon_es__WEBPACK_IMPORTED_MODULE_4__.Shape.idCounter = 0;
    cannon_es__WEBPACK_IMPORTED_MODULE_4__.Equation.idCounter = 0;
    const world = new cannon_es__WEBPACK_IMPORTED_MODULE_4__.World();
    world.nextId = 0;
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.setWorld(world);
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().gravity.set(this.gravity.x, this.gravity.y, this.gravity.z);
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().broadphase = new cannon_es__WEBPACK_IMPORTED_MODULE_4__.NaiveBroadphase();
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().defaultContactMaterial.friction = this.defaultFriction;
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().defaultContactMaterial.restitution = this.defaultRestitution;
  }
  beforeUpdate() {
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().step(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.deltaTime, rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.deltaTime, this.maxSubSteps || 1);
  }
  afterUpdate() {
    this.checkCollisions();
  }
  checkCollisions() {
    const contacts = _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().contacts;
    const newContacts = [];
    contacts.forEach((contact) => {
      newContacts[contact.id] = contact;
      const key1 = contact.bi.id + "_" + contact.bj.id;
      const key2 = contact.bj.id + "_" + contact.bi.id;
      const key1Collision = this.activeCollisions[key1];
      const key2Collision = this.activeCollisions[key2];
      if (!this.contacts[contact.id] && !key1Collision && !key2Collision) {
        this.activeCollisions[key1] = true;
        this.activeCollisions[key2] = true;
        this.sendNewCollisionEvents(contact);
      }
    });
    this.contacts.forEach((contact) => {
      const key1 = contact.bi.id + "_" + contact.bj.id;
      const key2 = contact.bj.id + "_" + contact.bi.id;
      const foundActiveCollision = this.findActiveCollision(newContacts, contact);
      const newContact = newContacts[contact.id];
      if (newContact && newContact.enabled || foundActiveCollision) {
        this.sendOnCollisionStayEvents(contact);
      }
      if ((!newContact || newContact && !newContact.enabled) && !foundActiveCollision) {
        this.activeCollisions[key1] = false;
        this.activeCollisions[key2] = false;
        this.sendOnCollisionExitEvents(contact);
      }
    });
    this.contacts = newContacts;
  }
  findActiveCollision(contactList, sample) {
    return contactList.find((contact) => {
      if (!contact || !contact.enabled)
        return false;
      if (contact.bi === sample.bi && contact.bj === sample.bj)
        return true;
      if (contact.bi === sample.bj && contact.bj === sample.bi)
        return true;
      return false;
    });
  }
  sendOnCollisionStayEvents(contact) {
    const bodyA = _CannonBody_re__WEBPACK_IMPORTED_MODULE_3__["default"].findByBody(contact.bi);
    const bodyB = _CannonBody_re__WEBPACK_IMPORTED_MODULE_3__["default"].findByBody(contact.bj);
    if (!bodyB || !bodyA)
      return;
    bodyA.onCollisionStayListeners.forEach((cb) => {
      cb({ other: bodyB, contact });
    });
    bodyB.onCollisionStayListeners.forEach((cb) => {
      cb({ other: bodyA, contact });
    });
  }
  sendOnCollisionExitEvents(contact) {
    const bodyA = _CannonBody_re__WEBPACK_IMPORTED_MODULE_3__["default"].findByBody(contact.bi);
    const bodyB = _CannonBody_re__WEBPACK_IMPORTED_MODULE_3__["default"].findByBody(contact.bj);
    if (!bodyB || !bodyA)
      return;
    bodyA.onCollisionExitListeners.forEach((cb) => {
      cb({ other: bodyB, contact });
    });
    bodyB.onCollisionExitListeners.forEach((cb) => {
      cb({ other: bodyA, contact });
    });
  }
  sendNewCollisionEvents(contact) {
    const bodyA = _CannonBody_re__WEBPACK_IMPORTED_MODULE_3__["default"].findByBody(contact.bi);
    const bodyB = _CannonBody_re__WEBPACK_IMPORTED_MODULE_3__["default"].findByBody(contact.bj);
    if (!bodyB || !bodyA)
      return;
    bodyA.onCollisionEnterListeners.forEach((cb) => {
      cb({ other: bodyB, contact });
    });
    bodyB.onCollisionEnterListeners.forEach((cb) => {
      cb({ other: bodyA, contact });
    });
  }
}
__name(CannonConfig, "CannonConfig");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonConfig.prototype, "maxSubSteps", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonConfig.prototype, "defaultFriction", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonConfig.prototype, "defaultRestitution", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonConfig.prototype, "gravity", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonConfig);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonConstraint.ts":
/*!***************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonConstraint.ts ***!
  \***************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonConstraint)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });



class CannonConstraint extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  start() {
    this.createConstraint();
  }
  getCannonBodyComponent(object3d) {
    const cannonBody = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"], object3d);
    if (!cannonBody) {
      throw "CannonHinge targets must have a Cannon Body Component";
    }
    return cannonBody;
  }
  createConstraint() {
  }
  onRemoved() {
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().removeConstraint(this.constraint);
  }
}
__name(CannonConstraint, "CannonConstraint");


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonDistanceConstraint.re.ts":
/*!**************************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonDistanceConstraint.re.ts ***!
  \**************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonDistanceConstraint)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonConstraint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CannonConstraint */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonConstraint.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonDistanceConstraint extends _CannonConstraint__WEBPACK_IMPORTED_MODULE_1__["default"] {
  constructor() {
    super(...arguments);
    this.distance = 1;
    this.maxForce = 1e6;
  }
  createConstraint() {
    if (!this.target)
      throw "CannonHinge requires a target";
    const bodyA = this.getCannonBodyComponent(this.object3d).body;
    const bodyB = this.getCannonBodyComponent(this.target).body;
    this.constraint = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.DistanceConstraint(bodyA, bodyB, this.distance, this.maxForce);
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().addConstraint(this.constraint);
  }
}
__name(CannonDistanceConstraint, "CannonDistanceConstraint");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], CannonDistanceConstraint.prototype, "target", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonDistanceConstraint.prototype, "distance", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonDistanceConstraint.prototype, "maxForce", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonDistanceConstraint);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonHingeConstraint.re.ts":
/*!***********************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonHingeConstraint.re.ts ***!
  \***********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonHingeConstraint)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonConstraint__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CannonConstraint */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonConstraint.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class CannonHingeConstraint extends _CannonConstraint__WEBPACK_IMPORTED_MODULE_2__["default"] {
  constructor() {
    super(...arguments);
    this.pivotA = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0.1, 0, 0);
    this.axisA = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, 1, 0);
    this.pivotB = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(-1, 0, 0);
    this.axisB = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, 1, 0);
    this.maxForce = 1e6;
  }
  createConstraint() {
    if (!this.target)
      throw "CannonHinge requires a target";
    const bodyA = this.getCannonBodyComponent(this.object3d).body;
    const bodyB = this.getCannonBodyComponent(this.target).body;
    this.constraint = new cannon_es__WEBPACK_IMPORTED_MODULE_4__.HingeConstraint(bodyA, bodyB, {
      pivotA: new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.pivotA.x, this.pivotA.y, this.pivotA.z),
      axisA: new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.axisA.x, this.axisA.y, this.axisA.z),
      pivotB: new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.pivotB.x, this.pivotB.y, this.pivotB.z),
      axisB: new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.axisB.x, this.axisB.y, this.axisB.z),
      collideConnected: this.collideConnected,
      maxForce: this.maxForce
    });
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_3__.getWorld().addConstraint(this.constraint);
  }
}
__name(CannonHingeConstraint, "CannonHingeConstraint");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], CannonHingeConstraint.prototype, "target", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonHingeConstraint.prototype, "pivotA", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonHingeConstraint.prototype, "axisA", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonHingeConstraint.prototype, "pivotB", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonHingeConstraint.prototype, "axisB", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], CannonHingeConstraint.prototype, "collideConnected", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonHingeConstraint.prototype, "maxForce", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonHingeConstraint);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonLockConstraint.re.ts":
/*!**********************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonLockConstraint.re.ts ***!
  \**********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonLockConstraint)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonConstraint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CannonConstraint */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonConstraint.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonLockConstraint extends _CannonConstraint__WEBPACK_IMPORTED_MODULE_1__["default"] {
  constructor() {
    super(...arguments);
    this.maxForce = 1e6;
  }
  createConstraint() {
    if (!this.target)
      throw "CannonHinge requires a target";
    const bodyA = this.getCannonBodyComponent(this.object3d).body;
    const bodyB = this.getCannonBodyComponent(this.target).body;
    this.constraint = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.LockConstraint(bodyA, bodyB, {
      maxForce: this.maxForce
    });
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().addConstraint(this.constraint);
  }
}
__name(CannonLockConstraint, "CannonLockConstraint");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], CannonLockConstraint.prototype, "target", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonLockConstraint.prototype, "maxForce", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonLockConstraint);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonPointToPointConstraint.re.ts":
/*!******************************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonPointToPointConstraint.re.ts ***!
  \******************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonPointToPointConstraint)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonConstraint__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CannonConstraint */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonConstraint.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class CannonPointToPointConstraint extends _CannonConstraint__WEBPACK_IMPORTED_MODULE_2__["default"] {
  constructor() {
    super(...arguments);
    this.privotA = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.privotB = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.maxForce = 1e6;
  }
  createConstraint() {
    if (!this.target)
      throw "CannonHinge requires a target";
    const bodyA = this.getCannonBodyComponent(this.object3d).body;
    const bodyB = this.getCannonBodyComponent(this.target).body;
    this.constraint = new cannon_es__WEBPACK_IMPORTED_MODULE_4__.PointToPointConstraint(bodyA, new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.privotA.x, this.privotA.y, this.privotA.z), bodyB, new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.privotB.x, this.privotB.y, this.privotB.z), this.maxForce);
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_3__.getWorld().addConstraint(this.constraint);
  }
}
__name(CannonPointToPointConstraint, "CannonPointToPointConstraint");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], CannonPointToPointConstraint.prototype, "target", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonPointToPointConstraint.prototype, "privotA", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonPointToPointConstraint.prototype, "privotB", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonPointToPointConstraint.prototype, "maxForce", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonPointToPointConstraint);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Controllers/CannonSimpleCharacterController.re.ts":
/*!*********************************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Controllers/CannonSimpleCharacterController.re.ts ***!
  \*********************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonSimpleCharacterController)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};



class CannonSimpleCharacterController extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.fwdSpeed = 3;
    this.jumpSpeed = 5;
    this.canJump = false;
    this.contactNormal = new cannon_es__WEBPACK_IMPORTED_MODULE_2__.Vec3();
    this.upAxis = new cannon_es__WEBPACK_IMPORTED_MODULE_2__.Vec3(0, 1, 0);
    this.inputAngularVelocity = new cannon_es__WEBPACK_IMPORTED_MODULE_2__.Vec3();
    this.inputVelocity = new cannon_es__WEBPACK_IMPORTED_MODULE_2__.Vec3();
  }
  awake() {
    this.rigidbody = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"], this.object3d);
    this.rigidbody?.onCollide((event) => {
      event.contact.ni.negate(this.contactNormal);
      if (this.contactNormal.dot(this.upAxis) > 0.5) {
        this.canJump = true;
      }
    });
    if (!this.rigidbody)
      return;
    this.rigidbody.body.type = cannon_es__WEBPACK_IMPORTED_MODULE_2__.Body.DYNAMIC;
  }
  update() {
    if (!this.rigidbody)
      return;
    this.inputVelocity.setZero();
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyW")) {
      this.inputVelocity.z = -1;
    } else if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyS")) {
      this.inputVelocity.z = 1;
    } else {
      this.inputVelocity.z = 0;
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyA")) {
      this.inputVelocity.x = -1;
    } else if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyD")) {
      this.inputVelocity.x = 1;
    } else {
      this.inputVelocity.x = 0;
    }
    this.inputVelocity.normalize();
    this.inputVelocity.scale(this.fwdSpeed, this.inputVelocity);
    if (this.canJump && rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyDown("Space")) {
      this.rigidbody.body.velocity.y = this.jumpSpeed;
      this.canJump = false;
    }
    this.rigidbody.body.angularVelocity.y = this.inputAngularVelocity.y;
    this.rigidbody.body.vectorToWorldFrame(this.inputVelocity, this.inputVelocity);
    if (!this.canJump)
      return;
    this.rigidbody.body.velocity.x = this.inputVelocity.x;
    this.rigidbody.body.velocity.z = this.inputVelocity.z;
  }
}
__name(CannonSimpleCharacterController, "CannonSimpleCharacterController");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonSimpleCharacterController.prototype, "fwdSpeed", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonSimpleCharacterController.prototype, "jumpSpeed", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonSimpleCharacterController);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Controllers/CannonVehicleController.re.ts":
/*!*************************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Controllers/CannonVehicleController.re.ts ***!
  \*************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonVehicleController)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Objects_CannonRaycastVehicle_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Objects/CannonRaycastVehicle.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonRaycastVehicle.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};


class CannonVehicleController extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.maxForce = 200;
    this.reverseForce = 50;
    this.breakForce = 250;
    this.maxSteering = 0.5;
  }
  start() {
    this.raycastVehicle = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponentByName("CannonRaycastVehicle", this.object3d);
  }
  update() {
    if (!(this.raycastVehicle instanceof _Objects_CannonRaycastVehicle_re__WEBPACK_IMPORTED_MODULE_1__["default"]))
      return;
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyW")) {
      this.releaseBreaks();
      this.raycastVehicle.vehicle.applyEngineForce(this.maxForce, 2);
      this.raycastVehicle.vehicle.applyEngineForce(this.maxForce, 3);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyS")) {
      const speed = -this.raycastVehicle.vehicle.currentVehicleSpeedKmHour;
      if (speed <= 0) {
        this.releaseBreaks();
        this.raycastVehicle.vehicle.applyEngineForce(-this.reverseForce, 2);
        this.raycastVehicle.vehicle.applyEngineForce(-this.reverseForce, 3);
      } else if (speed > 0.05) {
        this.raycastVehicle.vehicle.applyEngineForce(-this.maxForce, 2);
        this.raycastVehicle.vehicle.applyEngineForce(-this.maxForce, 3);
      }
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyUp("KeyW")) {
      this.raycastVehicle.vehicle.applyEngineForce(0, 2);
      this.raycastVehicle.vehicle.applyEngineForce(0, 3);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyUp("KeyS")) {
      const speed = Math.abs(this.raycastVehicle.vehicle.currentVehicleSpeedKmHour);
      this.raycastVehicle.vehicle.applyEngineForce(0, 2);
      this.raycastVehicle.vehicle.applyEngineForce(0, 3);
      if (speed < 1) {
        this.break();
      } else {
        this.releaseBreaks();
      }
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyA")) {
      this.raycastVehicle.vehicle.setSteeringValue(this.maxSteering, 0);
      this.raycastVehicle.vehicle.setSteeringValue(this.maxSteering, 1);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("KeyD")) {
      this.raycastVehicle.vehicle.setSteeringValue(-this.maxSteering, 0);
      this.raycastVehicle.vehicle.setSteeringValue(-this.maxSteering, 1);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyUp("KeyA")) {
      this.raycastVehicle.vehicle.setSteeringValue(0, 0);
      this.raycastVehicle.vehicle.setSteeringValue(0, 1);
    }
    if (rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyUp("KeyD")) {
      this.raycastVehicle.vehicle.setSteeringValue(0, 0);
      this.raycastVehicle.vehicle.setSteeringValue(0, 1);
    }
  }
  break() {
    this.raycastVehicle.vehicle.setBrake(this.breakForce, 0);
    this.raycastVehicle.vehicle.setBrake(this.breakForce, 1);
    this.raycastVehicle.vehicle.setBrake(this.breakForce, 2);
    this.raycastVehicle.vehicle.setBrake(this.breakForce, 3);
  }
  releaseBreaks() {
    this.raycastVehicle.vehicle.setBrake(0, 0);
    this.raycastVehicle.vehicle.setBrake(0, 1);
    this.raycastVehicle.vehicle.setBrake(0, 2);
    this.raycastVehicle.vehicle.setBrake(0, 3);
  }
}
__name(CannonVehicleController, "CannonVehicleController");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonVehicleController.prototype, "maxForce", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonVehicleController.prototype, "reverseForce", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonVehicleController.prototype, "breakForce", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonVehicleController.prototype, "maxSteering", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonVehicleController);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/CannonContactMaterial.re.ts":
/*!********************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/CannonContactMaterial.re.ts ***!
  \********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonContactMaterial)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};



class CannonContactMaterial extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  start() {
    this.createContactMaterial();
  }
  getMaterial(materialName) {
    return _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_1__.getWorld().materials.find((material) => material.name === materialName);
  }
  createContactMaterial() {
    const cannonMaterialA = this.getMaterial(this.materialA);
    const cannonMaterialB = this.getMaterial(this.materialB);
    if (!cannonMaterialA || !cannonMaterialB)
      return;
    this.contactMaterial = new cannon_es__WEBPACK_IMPORTED_MODULE_2__.ContactMaterial(cannonMaterialA, cannonMaterialB, {
      friction: this.friction,
      restitution: this.restitution
    });
    this.contactMaterial.friction = this.friction;
    this.contactMaterial.restitution = this.restitution;
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_1__.getWorld().addContactMaterial(this.contactMaterial);
  }
}
__name(CannonContactMaterial, "CannonContactMaterial");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.text()
], CannonContactMaterial.prototype, "materialA", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.text()
], CannonContactMaterial.prototype, "materialB", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonContactMaterial.prototype, "friction", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonContactMaterial.prototype, "restitution", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonContactMaterial);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/CannonMaterial.re.ts":
/*!*************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/CannonMaterial.re.ts ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonMaterial)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonMaterial extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  awake() {
    this.createMaterial();
  }
  start() {
    this.setMaterial();
  }
  createMaterial() {
    this.material = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Material(this.name);
    this.material.friction = this.friction;
    this.material.restitution = this.restitution;
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().addMaterial(this.material);
  }
  setMaterial() {
    const cannonBody = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"], this.object3d);
    if (cannonBody) {
      cannonBody.body.shapes.forEach((shape) => shape.material = this.material);
    }
  }
}
__name(CannonMaterial, "CannonMaterial");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonMaterial.prototype, "friction", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonMaterial.prototype, "restitution", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonMaterial);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/SetCannonMaterial.re.ts":
/*!****************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/SetCannonMaterial.re.ts ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ SetCannonMaterial)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};



class SetCannonMaterial extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  start() {
    this.setMaterial();
  }
  getMaterial() {
    return _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld().materials.find((material) => material.name === this.materialName);
  }
  setMaterial() {
    const material = this.getMaterial();
    if (!material)
      return;
    this.material = material;
    const cannonBody = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"], this.object3d);
    if (cannonBody) {
      cannonBody.body.shapes.forEach((shape) => shape.material = this.material);
    }
  }
}
__name(SetCannonMaterial, "SetCannonMaterial");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.text()
], SetCannonMaterial.prototype, "materialName", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(SetCannonMaterial);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonRaycastVehicle.re.ts":
/*!******************************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonRaycastVehicle.re.ts ***!
  \******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonRaycastVehicle)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonRaycastVehicle extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.mass = 500;
    this.suspensionStiffness = 30;
    this.suspensionRestLength = 0.1;
    this.frictionSlip = 0.7;
    this.maxSuspensionTravel = 0.2;
    this.customSlidingRotationalSpeed = -30;
    this.useCustomSlidingRotationalSpeed = true;
  }
  start() {
    if (!_Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld())
      return;
    let body = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"], this.object3d);
    if (!body) {
      body = new _CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"]("CarBody", this.object3d);
      body.mass = this.mass;
      rogue_engine__WEBPACK_IMPORTED_MODULE_0__.addComponent(body);
    }
    if (!this.chasis)
      return;
    const chassisBody = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"], this.chasis);
    if (!(chassisBody instanceof _CannonBody_re__WEBPACK_IMPORTED_MODULE_1__["default"]))
      return;
    this.vehicle = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.RaycastVehicle({
      chassisBody: body.body,
      indexForwardAxis: 2,
      indexUpAxis: 1,
      indexRightAxis: 0
    });
    this.vehicle.addToWorld(_Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_2__.getWorld());
  }
}
__name(CannonRaycastVehicle, "CannonRaycastVehicle");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], CannonRaycastVehicle.prototype, "chasis", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "mass", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "suspensionStiffness", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "suspensionRestLength", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "frictionSlip", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "dampingRelaxation", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "dampingCompression", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "maxSuspensionForce", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "rollInfluence", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "maxSuspensionTravel", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonRaycastVehicle.prototype, "customSlidingRotationalSpeed", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], CannonRaycastVehicle.prototype, "useCustomSlidingRotationalSpeed", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonRaycastVehicle);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonSpring.re.ts":
/*!**********************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonSpring.re.ts ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonSpring)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class CannonSpring extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.anchorA = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.anchorB = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.restLength = 0;
    this.stiffness = 50;
    this.damping = 1;
    this.applyForce = /* @__PURE__ */ __name(() => {
      this.spring.applyForce();
    }, "applyForce");
  }
  start() {
    this.createSpring();
  }
  getCannonBodyComponent(object3d) {
    const cannonBody = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_2__["default"], object3d);
    if (!cannonBody) {
      throw "CannonSpring targets must have a Cannon Body Component";
    }
    return cannonBody;
  }
  createSpring() {
    if (!this.target)
      throw "CannonSpring requires a target";
    const bodyA = this.getCannonBodyComponent(this.object3d).body;
    const bodyB = this.getCannonBodyComponent(this.target).body;
    this.spring = new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Spring(bodyA, bodyB, {
      localAnchorA: new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.anchorA.x, this.anchorA.y, this.anchorA.z),
      localAnchorB: new cannon_es__WEBPACK_IMPORTED_MODULE_4__.Vec3(this.anchorB.x, this.anchorB.y, this.anchorB.z),
      restLength: this.restLength,
      stiffness: this.stiffness,
      damping: this.damping
    });
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_3__.getWorld().addEventListener("postStep", this.applyForce);
  }
  onBeforeRemoved() {
    _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_3__.getWorld().removeEventListener("postStep", this.applyForce);
  }
}
__name(CannonSpring, "CannonSpring");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], CannonSpring.prototype, "target", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonSpring.prototype, "anchorA", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonSpring.prototype, "anchorB", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonSpring.prototype, "restLength", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonSpring.prototype, "stiffness", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonSpring.prototype, "damping", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonSpring);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonWheel.re.ts":
/*!*********************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonWheel.re.ts ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonWheel)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonRaycastVehicle_re__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CannonRaycastVehicle.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonRaycastVehicle.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonWheel extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.radiusOffset = 0;
    this.connectionPoint = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, 0, 0);
    this.matrixA = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixB = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixC = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
  }
  start() {
    this.raycastVehicle = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonRaycastVehicle_re__WEBPACK_IMPORTED_MODULE_2__["default"], this.object3d);
    if (!(this.raycastVehicle instanceof _CannonRaycastVehicle_re__WEBPACK_IMPORTED_MODULE_2__["default"]))
      return;
    let radius = 0.3;
    if (this.wheel) {
      this.connectionPoint.copy(this.wheel.position);
      const bbox = new three__WEBPACK_IMPORTED_MODULE_1__.Box3().setFromObject(this.wheel);
      radius = bbox.max.x - bbox.min.x;
    }
    this.wheelInfo = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.WheelInfo({
      radius: radius + this.radiusOffset,
      directionLocal: new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3(0, -1, 0),
      suspensionStiffness: this.raycastVehicle.suspensionStiffness,
      suspensionRestLength: this.raycastVehicle.suspensionRestLength,
      frictionSlip: this.raycastVehicle.frictionSlip,
      dampingRelaxation: this.raycastVehicle.dampingRelaxation,
      dampingCompression: this.raycastVehicle.dampingCompression,
      maxSuspensionForce: this.raycastVehicle.maxSuspensionForce,
      rollInfluence: this.raycastVehicle.rollInfluence,
      axleLocal: new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3(-1, 0, 0),
      chassisConnectionPointLocal: new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3(this.connectionPoint.x, this.connectionPoint.y, this.connectionPoint.z),
      maxSuspensionTravel: this.raycastVehicle.maxSuspensionTravel,
      customSlidingRotationalSpeed: this.raycastVehicle.customSlidingRotationalSpeed,
      useCustomSlidingRotationalSpeed: this.raycastVehicle.useCustomSlidingRotationalSpeed
    });
    this.raycastVehicle.vehicle.wheelInfos.push(this.wheelInfo);
  }
  afterUpdate() {
    if (!this.wheel)
      return;
    const wheel = this.wheelInfo;
    if (!wheel)
      return;
    const pos = wheel.worldTransform.position;
    const rot = wheel.worldTransform.quaternion;
    this.wheel.position.set(pos.x, pos.y, pos.z);
    this.wheel.parent?.worldToLocal(this.wheel.position);
    this.wheel.quaternion.set(rot.x, rot.y, rot.z, rot.w);
    this.matrixA.makeRotationFromQuaternion(this.wheel.quaternion);
    this.wheel.updateMatrixWorld();
    this.matrixB.copy(this.wheel.parent.matrixWorld).invert();
    this.matrixC.extractRotation(this.matrixB);
    this.matrixA.premultiply(this.matrixC);
    this.wheel.quaternion.setFromRotationMatrix(this.matrixA);
  }
}
__name(CannonWheel, "CannonWheel");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], CannonWheel.prototype, "wheel", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonWheel.prototype, "radiusOffset", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonWheel);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonBox.re.ts":
/*!******************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonBox.re.ts ***!
  \******************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonBox)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonShape__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CannonShape */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonShape.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonBox extends _CannonShape__WEBPACK_IMPORTED_MODULE_2__["default"] {
  constructor() {
    super(...arguments);
    this.sizeOffset = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(1, 1, 1);
    this._collisionResponse = true;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  get collisionResponse() {
    return this._collisionResponse;
  }
  set collisionResponse(value) {
    this._collisionResponse = value;
    if (!this.shape)
      return;
    this.shape.collisionResponse = value;
  }
  createShape() {
    this.object3d.getWorldScale(this.worldScale);
    this.shape = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Box(new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3(this.sizeOffset.x * (this.worldScale.x / 2), this.sizeOffset.y * (this.worldScale.y / 2), this.sizeOffset.z * (this.worldScale.z / 2)));
    this.shape.collisionResponse = this._collisionResponse;
  }
}
__name(CannonBox, "CannonBox");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonBox.prototype, "sizeOffset", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], CannonBox.prototype, "collisionResponse", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonBox);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonCylinder.re.ts":
/*!***********************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonCylinder.re.ts ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonCylinder)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonShape__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CannonShape */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonShape.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonCylinder extends _CannonShape__WEBPACK_IMPORTED_MODULE_2__["default"] {
  constructor() {
    super(...arguments);
    this.radiusTopOffset = 1;
    this.radiusBottomOffset = 1;
    this.heightOffset = 1;
    this.segments = 100;
    this._collisionResponse = true;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  get collisionResponse() {
    return this._collisionResponse;
  }
  set collisionResponse(value) {
    this._collisionResponse = value;
    if (!this.shape)
      return;
    this.shape.collisionResponse = value;
  }
  createShape() {
    this.object3d.getWorldScale(this.worldScale);
    this.shape = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Cylinder(this.radiusTopOffset * this.worldScale.x, this.radiusBottomOffset * this.worldScale.x, this.heightOffset * this.worldScale.y, this.segments);
    this.shape.collisionResponse = this._collisionResponse;
  }
}
__name(CannonCylinder, "CannonCylinder");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonCylinder.prototype, "radiusTopOffset", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonCylinder.prototype, "radiusBottomOffset", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonCylinder.prototype, "heightOffset", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonCylinder.prototype, "segments", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], CannonCylinder.prototype, "collisionResponse", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonCylinder);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonShape.ts":
/*!*****************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonShape.ts ***!
  \*****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonShape)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _CannonBody_re__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../CannonBody.re */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });




class CannonShape extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.localPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.worldPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.oldPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.localRot = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.worldQuaternion = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.matrixA = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixB = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixC = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
  }
  static findByShape(shape) {
    let shapeComponent;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.traverseComponents((component) => {
      if (shapeComponent)
        return;
      if (component instanceof CannonShape && component.shape === shape) {
        shapeComponent = component;
      }
    });
    return shapeComponent;
  }
  awake() {
    this.createShape();
  }
  start() {
    if (!this.shape)
      return;
    this.bodyComponent = this.getBodyComponent(this.object3d);
    if (!this.bodyComponent)
      return;
    if (!this.bodyComponent.body)
      return;
    this.body = this.bodyComponent.body;
    const bodyIsShape = this.object3d === this.bodyComponent.object3d;
    this.object3d.getWorldPosition(this.worldPos);
    this.localPos.copy(this.worldPos);
    this.bodyComponent.object3d.updateWorldMatrix(true, true);
    this.bodyComponent.object3d.worldToLocal(this.localPos);
    let position = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3(this.localPos.x, this.localPos.y, this.localPos.z);
    this.object3d.updateWorldMatrix(true, true);
    this.object3d.getWorldQuaternion(this.worldQuaternion);
    this.matrixA.makeRotationFromQuaternion(this.worldQuaternion);
    this.object3d.updateWorldMatrix(true, true);
    this.matrixB.copy(this.bodyComponent.object3d.matrixWorld).invert();
    this.matrixC.extractRotation(this.matrixB);
    this.matrixA.premultiply(this.matrixC);
    this.localRot.setFromRotationMatrix(this.matrixA);
    let rotation = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Quaternion(this.localRot.x, this.localRot.y, this.localRot.z, this.localRot.w);
    if (bodyIsShape) {
      this.body.addShape(this.shape);
    } else {
      this.body.addShape(this.shape, position, rotation);
    }
  }
  update() {
    if (!this.shape)
      return;
    if (!this.shape.body)
      return;
    if (this.shape.body.type === cannon_es__WEBPACK_IMPORTED_MODULE_3__.BODY_TYPES.STATIC || this.shape.body.mass === 0)
      return;
    const shapeIndex = this.shape.body?.shapes.indexOf(this.shape);
    if (shapeIndex === void 0)
      return;
    this.oldPos.copy(this.worldPos);
    this.object3d.getWorldPosition(this.worldPos);
    if (this.oldPos.equals(this.worldPos))
      return;
    this.localPos.copy(this.worldPos);
    this.bodyComponent?.object3d.updateWorldMatrix(true, true);
    this.bodyComponent?.object3d.worldToLocal(this.localPos);
    this.shape.body?.shapeOffsets[shapeIndex].set(this.localPos.x, this.localPos.y, this.localPos.z);
    this.shape.updateBoundingSphereRadius();
    this.shape.body?.updateAABB();
  }
  onDisabled() {
    this.body?.removeShape(this.shape);
  }
  onBeforeObjectRemoved() {
    this.body?.removeShape(this.shape);
  }
  getBodyComponent(object3d) {
    const bodyComponent = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_CannonBody_re__WEBPACK_IMPORTED_MODULE_2__["default"], object3d);
    if (bodyComponent) {
      return bodyComponent;
    }
    if (!object3d.parent)
      return;
    return this.getBodyComponent(object3d.parent);
  }
  createShape() {
  }
}
__name(CannonShape, "CannonShape");


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonSphere.re.ts":
/*!*********************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonSphere.re.ts ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonSphere)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonShape__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CannonShape */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonShape.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};



class CannonSphere extends _CannonShape__WEBPACK_IMPORTED_MODULE_1__["default"] {
  constructor() {
    super(...arguments);
    this.radiusOffset = 1;
    this._collisionResponse = true;
  }
  get collisionResponse() {
    return this._collisionResponse;
  }
  set collisionResponse(value) {
    this._collisionResponse = value;
    if (!this.shape)
      return;
    this.shape.collisionResponse = value;
  }
  createShape() {
    const scale = this.object3d.scale;
    const maxSide = Math.max(scale.x, scale.y, scale.z);
    this.shape = new cannon_es__WEBPACK_IMPORTED_MODULE_2__.Sphere(this.radiusOffset * maxSide);
    this.shape.collisionResponse = this._collisionResponse;
  }
}
__name(CannonSphere, "CannonSphere");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], CannonSphere.prototype, "radiusOffset", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], CannonSphere.prototype, "collisionResponse", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonSphere);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonTrimesh.re.ts":
/*!**********************************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonTrimesh.re.ts ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CannonTrimesh)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
/* harmony import */ var _CannonShape__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CannonShape */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonShape.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class CannonTrimesh extends _CannonShape__WEBPACK_IMPORTED_MODULE_2__["default"] {
  constructor() {
    super(...arguments);
    this.sizeOffset = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(1, 1, 1);
    this._collisionResponse = true;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.worldPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.tmpVec0 = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3();
    this.tmpVec1 = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3();
    this.tmpVec2 = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3();
    this.tmpQuat0 = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Vec3();
  }
  get collisionResponse() {
    return this._collisionResponse;
  }
  set collisionResponse(value) {
    this._collisionResponse = value;
    if (!this.shape)
      return;
    this.shape.collisionResponse = value;
  }
  createShape() {
    if (!(this.object3d instanceof three__WEBPACK_IMPORTED_MODULE_1__.Mesh))
      return;
    this.object3d.updateWorldMatrix(true, true);
    this.object3d.getWorldScale(this.worldScale);
    this.object3d.getWorldPosition(this.worldPos);
    this.object3d.getWorldQuaternion(this.worldQuaternion);
    const mesh = this.object3d;
    let geometry = mesh.geometry;
    geometry.computeBoundingSphere();
    geometry.normalizeNormals();
    if (geometry.index !== null) {
      const nonIndexedGeo = geometry.toNonIndexed();
      geometry.copy(nonIndexedGeo);
    }
    const vertices = this.getVertices(geometry);
    if (!vertices.length)
      return;
    const indices = Object.keys(vertices).map(Number);
    this.shape = new cannon_es__WEBPACK_IMPORTED_MODULE_3__.Trimesh(vertices, indices);
    this.shape.collisionResponse = this._collisionResponse;
  }
  getVertices(geometry) {
    const position = geometry.attributes.position;
    const vertices = new Float32Array(position.count * 3);
    for (let i = 0; i < position.count; i++) {
      vertices[i * 3] = position.getX(i) * this.worldScale.x;
      vertices[i * 3 + 1] = position.getY(i) * this.worldScale.y;
      vertices[i * 3 + 2] = position.getZ(i) * this.worldScale.z;
    }
    return vertices;
  }
}
__name(CannonTrimesh, "CannonTrimesh");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], CannonTrimesh.prototype, "sizeOffset", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], CannonTrimesh.prototype, "collisionResponse", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(CannonTrimesh);


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts":
/*!***************************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts ***!
  \***************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   copyCannonQuaternion: () => (/* binding */ copyCannonQuaternion),
/* harmony export */   copyCannonV3: () => (/* binding */ copyCannonV3),
/* harmony export */   copyThreeQuaternion: () => (/* binding */ copyThreeQuaternion),
/* harmony export */   copyThreeV3: () => (/* binding */ copyThreeV3),
/* harmony export */   getWorld: () => (/* binding */ getWorld),
/* harmony export */   setWorld: () => (/* binding */ setWorld)
/* harmony export */ });
/* harmony import */ var cannon_es__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cannon-es */ "./node_modules/cannon-es/dist/cannon-es.js");
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

let RogueCannon = { world: new cannon_es__WEBPACK_IMPORTED_MODULE_0__.World() };
function getWorld() {
  return RogueCannon.world;
}
__name(getWorld, "getWorld");
function setWorld(newWorld) {
  RogueCannon.world = newWorld;
}
__name(setWorld, "setWorld");
function copyThreeV3(vector3, target) {
  target.set(vector3.x, vector3.y, vector3.z);
}
__name(copyThreeV3, "copyThreeV3");
function copyThreeQuaternion(quaternion, target) {
  const q = quaternion;
  target.set(q.x, q.y, q.z, q.w);
}
__name(copyThreeQuaternion, "copyThreeQuaternion");
function copyCannonV3(vector3, target) {
  target.set(vector3.x, vector3.y, vector3.z);
}
__name(copyCannonV3, "copyCannonV3");
function copyCannonQuaternion(quaternion, target) {
  const q = quaternion;
  target.set(q.x, q.y, q.z, q.w);
}
__name(copyCannonQuaternion, "copyCannonQuaternion");


/***/ }),

/***/ "./Assets/rogue_packages/BeardScript/rogue-cannon/index.ts":
/*!*****************************************************************!*\
  !*** ./Assets/rogue_packages/BeardScript/rogue-cannon/index.ts ***!
  \*****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   RogueCannon: () => (/* reexport module object */ _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_0__)
/* harmony export */ });
/* harmony import */ var _Lib_RogueCannon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Lib/RogueCannon */ "./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");



/***/ }),

/***/ "./Assets/rogue_packages/EyeOfMidas/targeted-orbit-camera/TargetedOrbitCamera.re.ts":
/*!******************************************************************************************!*\
  !*** ./Assets/rogue_packages/EyeOfMidas/targeted-orbit-camera/TargetedOrbitCamera.re.ts ***!
  \******************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ TargetedOrbitCamera)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};


class TargetedOrbitCamera extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.enableRotate = true;
    this.rotateSpeed = 1;
    this.minAzimuthAngle = -6.28;
    this.maxAzimuthAngle = 6.28;
    this.minPolarAngle = 0;
    this.maxPolarAngle = 1.56;
    this.enableDolly = true;
    this.dollySpeed = 1;
    this.minDistance = 1;
    this.maxDistance = 50;
    this.offset = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.rotateMouseButton = 2;
    this.useCameraLock = false;
    this.rotateStart = new three__WEBPACK_IMPORTED_MODULE_1__.Vector2();
    this.rotateEnd = new three__WEBPACK_IMPORTED_MODULE_1__.Vector2();
    this.rotateDelta = new three__WEBPACK_IMPORTED_MODULE_1__.Vector2();
    this.scale = 1;
    this.EPS = 1e-6;
    this.twoPI = 2 * Math.PI;
    this.spherical = new three__WEBPACK_IMPORTED_MODULE_1__.Spherical();
    this.sphericalDelta = new three__WEBPACK_IMPORTED_MODULE_1__.Spherical();
    this.quat = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion().setFromUnitVectors(new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, 1, 0), new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, 1, 0));
    this.quatInverse = this.quat.clone().invert();
    this.lastPosition = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.lastQuaternion = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.initialOffset = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  awake() {
    if (this.useCameraLock) {
      const container = document.getElementById(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.containerId);
      if (container) {
        container.onmousedown = this.lock.bind(this);
        rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.onStop(this.dispose);
      }
    }
  }
  start() {
    if (!this.target) {
      rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Debug.logError("Orbit controls not set to an Object3D Target.");
      return;
    }
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.rogueDOMContainer.addEventListener("contextmenu", (event) => {
      event.preventDefault();
    });
    this.quat = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion().setFromUnitVectors(this.object3d.up, new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, 1, 0));
    this.quatInverse = this.quat.clone().invert();
    this.initialOffset.copy(this.object3d.position).sub(this.target.position);
    this.offset.copy(this.initialOffset);
  }
  update() {
    if (!this.target) {
      return;
    }
    if (this.useCameraLock && !!document.pointerLockElement) {
      if (this.enableRotate && rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.isMoving) {
        let normalizedScreenMovement = new three__WEBPACK_IMPORTED_MODULE_1__.Vector2(0, 0);
        this.normalizeScreenMovement({ x: rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.movementX, y: rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.movementY }, normalizedScreenMovement);
        this.rotateLeft(this.twoPI * normalizedScreenMovement.x);
        this.rotateUp(this.twoPI * -normalizedScreenMovement.y);
      }
    } else {
      let normalizedScreenPosition = new three__WEBPACK_IMPORTED_MODULE_1__.Vector2(0, 0);
      this.normalizeScreenInput(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse, normalizedScreenPosition);
      if (this.enableRotate && rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.getButtonDown(this.rotateMouseButton)) {
        this.rotateStart.set(normalizedScreenPosition.x, normalizedScreenPosition.y);
      }
      if (this.enableRotate && rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.getButtonPressed(this.rotateMouseButton)) {
        this.rotateEnd.set(normalizedScreenPosition.x, normalizedScreenPosition.y);
        this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart).multiplyScalar(this.rotateSpeed);
        this.rotateLeft(this.twoPI * this.rotateDelta.x);
        this.rotateUp(this.twoPI * -this.rotateDelta.y);
        this.rotateStart.copy(this.rotateEnd);
      }
    }
    if (this.enableDolly && rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.wheelY > 0) {
      this.dollyOut();
    }
    if (this.enableDolly && rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.wheelY < 0) {
      this.dollyIn();
    }
    this.updateCamera();
    if (this.useCameraLock && rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.keyboard.getKeyPressed("Escape")) {
      this.unlock();
    }
  }
  dispose() {
    const container = document.getElementById(rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.containerId);
    if (container) {
      container.onmousedown = null;
    }
  }
  rotateLeft(angle) {
    this.sphericalDelta.theta -= angle;
  }
  rotateUp(angle) {
    this.sphericalDelta.phi -= angle;
  }
  updateCamera() {
    this.offset.applyQuaternion(this.quat);
    this.spherical.setFromVector3(this.offset);
    this.spherical.theta += this.sphericalDelta.theta;
    this.spherical.phi += this.sphericalDelta.phi;
    let min = this.minAzimuthAngle;
    let max = this.maxAzimuthAngle;
    if (isFinite(min) && isFinite(max)) {
      if (min < -Math.PI) {
        min += this.twoPI;
      } else if (min > Math.PI) {
        min -= this.twoPI;
      }
      if (max < -Math.PI) {
        max += this.twoPI;
      } else if (max > Math.PI) {
        max -= this.twoPI;
      }
      if (min <= max) {
        this.spherical.theta = Math.max(min, Math.min(max, this.spherical.theta));
      } else {
        this.spherical.theta = this.spherical.theta > (min + max) / 2 ? Math.max(min, this.spherical.theta) : Math.min(max, this.spherical.theta);
      }
    }
    this.spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this.spherical.phi));
    this.spherical.makeSafe();
    this.spherical.radius *= this.scale;
    this.spherical.radius = Math.max(this.minDistance, Math.min(this.maxDistance, this.spherical.radius));
    this.offset.setFromSpherical(this.spherical);
    this.offset.applyQuaternion(this.quatInverse);
    this.object3d.position.copy(this.target.position).add(this.offset);
    this.object3d.lookAt(this.target.position);
    this.sphericalDelta.set(0, 0, 0);
    this.scale = 1;
    if (this.lastPosition.distanceToSquared(this.object3d.position) > this.EPS || 8 * (1 - this.lastQuaternion.dot(this.object3d.quaternion)) > this.EPS) {
      this.lastPosition.copy(this.object3d.position);
      this.lastQuaternion.copy(this.object3d.quaternion);
    }
  }
  dollyOut() {
    this.scale /= Math.pow(0.95, this.dollySpeed);
  }
  dollyIn() {
    this.scale *= Math.pow(0.95, this.dollySpeed);
  }
  normalizeScreenInput(browserVector, gameVector) {
    const bounds = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.rogueDOMContainer.getBoundingClientRect();
    gameVector.x = (browserVector.x - bounds.left) / bounds.width * 2 - 1;
    gameVector.y = -((browserVector.y - bounds.top) / bounds.height) * 2 + 1;
  }
  normalizeScreenMovement(browserVector, gameVector) {
    const bounds = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.rogueDOMContainer.getBoundingClientRect();
    gameVector.x = browserVector.x / bounds.width;
    gameVector.y = -(browserVector.y / bounds.height);
  }
  lock() {
    if (!this.useCameraLock) {
      return;
    }
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.lock();
  }
  unlock() {
    if (!this.useCameraLock) {
      return;
    }
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Input.mouse.unlock();
  }
}
__name(TargetedOrbitCamera, "TargetedOrbitCamera");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.object3d()
], TargetedOrbitCamera.prototype, "target", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], TargetedOrbitCamera.prototype, "enableRotate", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "rotateSpeed", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "minAzimuthAngle", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "maxAzimuthAngle", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "minPolarAngle", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "maxPolarAngle", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], TargetedOrbitCamera.prototype, "enableDolly", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "dollySpeed", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "minDistance", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "maxDistance", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], TargetedOrbitCamera.prototype, "offset", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], TargetedOrbitCamera.prototype, "rotateMouseButton", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], TargetedOrbitCamera.prototype, "useCameraLock", 2);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(TargetedOrbitCamera);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierBall.re.ts":
/*!**********************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierBall.re.ts ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierBall)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierCollider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RapierCollider */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class RapierBall extends _RapierCollider__WEBPACK_IMPORTED_MODULE_3__["default"] {
  constructor() {
    super(...arguments);
    this._radiusOffset = 0;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  get radiusOffset() {
    return this._radiusOffset;
  }
  set radiusOffset(value) {
    const oldValue = this._radiusOffset;
    this._radiusOffset = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  createShape() {
    this.object3d.getWorldScale(this.worldScale);
    const maxSide = Math.max(this.worldScale.x, this.worldScale.y, this.worldScale.z);
    let colliderDesc = _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ColliderDesc.ball(this.radiusOffset + maxSide);
    this.collider = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.createCollider(colliderDesc, this.body);
  }
}
__name(RapierBall, "RapierBall");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierBall.prototype, "radiusOffset", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierBall);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCapsule.re.ts":
/*!*************************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCapsule.re.ts ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierCapsule)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierCollider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RapierCollider */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class RapierCapsule extends _RapierCollider__WEBPACK_IMPORTED_MODULE_3__["default"] {
  constructor() {
    super(...arguments);
    this._halfHeight = 0.5;
    this._radius = 0.5;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  get halfHeight() {
    return this._halfHeight;
  }
  set halfHeight(value) {
    const oldValue = this._halfHeight;
    this._halfHeight = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  get radius() {
    return this._radius;
  }
  set radius(value) {
    const oldValue = this._radius;
    this._radius = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  createShape() {
    this.object3d.getWorldScale(this.worldScale);
    const maxSide = Math.max(this.worldScale.x, this.worldScale.z);
    let colliderDesc = _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ColliderDesc.capsule(this.halfHeight * this.worldScale.y, this.radius * maxSide);
    this.collider = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.createCollider(colliderDesc, this.body);
  }
}
__name(RapierCapsule, "RapierCapsule");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCapsule.prototype, "halfHeight", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCapsule.prototype, "radius", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierCapsule);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts":
/*!***********************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierCollider)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierBody_re__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../RapierBody.re */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierBody.re.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





const _RapierCollider = class extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.initialized = false;
    this.localPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.worldPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.localRot = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.worldQuaternion = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.isSensor = false;
    this.collisionEvents = false;
  }
  static findByShape(shape) {
    let shapeComponent;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.traverseComponents((component) => {
      if (shapeComponent)
        return;
      if (component instanceof _RapierCollider && component.collider === shape) {
        shapeComponent = component;
      }
    });
    return shapeComponent;
  }
  init() {
    this.bodyComponent = this.getBodyComponent(this.object3d);
    if (!this.bodyComponent)
      return;
    if (!this.bodyComponent.body)
      return;
    this.body = this.bodyComponent.body;
    this.createShape();
    this.collider.setSensor(this.isSensor);
    this.collisionEvents && this.collider.setActiveEvents(_dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ActiveEvents.COLLISION_EVENTS);
    this.setColliderPos();
    this.setColliderRot();
    this.initialized = true;
  }
  setColliderPos() {
    this.object3d.updateWorldMatrix(true, true);
    this.object3d.getWorldPosition(this.worldPos);
    this.collider.setTranslation(this.worldPos);
  }
  setColliderRot() {
    this.object3d.updateWorldMatrix(true, true);
    this.object3d.getWorldQuaternion(this.worldQuaternion);
    this.collider.setRotation(this.worldQuaternion);
  }
  beforeUpdate() {
    if (!_Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].initialized)
      return;
    if (!this.initialized)
      this.init();
    if (!this.collider)
      return;
    this.setColliderPos();
    this.setColliderRot();
  }
  onDisabled() {
    _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
  }
  onBeforeObjectRemoved() {
    _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
  }
  getBodyComponent(object3d) {
    const bodyComponent = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponent(_RapierBody_re__WEBPACK_IMPORTED_MODULE_3__["default"], object3d);
    if (bodyComponent) {
      return bodyComponent;
    }
    if (!object3d.parent)
      return;
    return this.getBodyComponent(object3d.parent);
  }
  createShape() {
  }
};
let RapierCollider = _RapierCollider;
__name(RapierCollider, "RapierCollider");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierCollider.prototype, "isSensor", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierCollider.prototype, "collisionEvents", 2);



/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCone.re.ts":
/*!**********************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCone.re.ts ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierCone)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierCollider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RapierCollider */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class RapierCone extends _RapierCollider__WEBPACK_IMPORTED_MODULE_3__["default"] {
  constructor() {
    super(...arguments);
    this._halfHeight = 0.5;
    this._radius = 0.5;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  get halfHeight() {
    return this._halfHeight;
  }
  set halfHeight(value) {
    const oldValue = this._halfHeight;
    this._halfHeight = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  get radius() {
    return this._radius;
  }
  set radius(value) {
    const oldValue = this._radius;
    this._radius = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  createShape() {
    this.object3d.getWorldScale(this.worldScale);
    const maxSide = Math.max(this.worldScale.x, this.worldScale.z);
    let colliderDesc = _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ColliderDesc.cone(this.halfHeight * this.worldScale.y, this.radius * maxSide);
    this.collider = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.createCollider(colliderDesc, this.body);
  }
}
__name(RapierCone, "RapierCone");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCone.prototype, "halfHeight", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCone.prototype, "radius", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierCone);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCuboid.re.ts":
/*!************************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCuboid.re.ts ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierCuboid)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierCollider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RapierCollider */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class RapierCuboid extends _RapierCollider__WEBPACK_IMPORTED_MODULE_3__["default"] {
  constructor() {
    super(...arguments);
    this._sizeOffsetX = 1;
    this._sizeOffsetY = 1;
    this._sizeOffsetZ = 1;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  get sizeOffsetX() {
    return this._sizeOffsetX;
  }
  set sizeOffsetX(value) {
    const oldValue = this._sizeOffsetX;
    this._sizeOffsetX = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  get sizeOffsetY() {
    return this._sizeOffsetY;
  }
  set sizeOffsetY(value) {
    const oldValue = this._sizeOffsetY;
    this._sizeOffsetY = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  get sizeOffsetZ() {
    return this._sizeOffsetZ;
  }
  set sizeOffsetZ(value) {
    const oldValue = this._sizeOffsetZ;
    this._sizeOffsetZ = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  createShape() {
    this.object3d.getWorldScale(this.worldScale);
    let colliderDesc = _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ColliderDesc.cuboid(this._sizeOffsetX * (this.worldScale.x / 2), this._sizeOffsetY * (this.worldScale.y / 2), this._sizeOffsetZ * (this.worldScale.z / 2));
    this.collider = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.createCollider(colliderDesc, this.body);
  }
}
__name(RapierCuboid, "RapierCuboid");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCuboid.prototype, "sizeOffsetX", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCuboid.prototype, "sizeOffsetY", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCuboid.prototype, "sizeOffsetZ", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierCuboid);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCylinder.re.ts":
/*!**************************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCylinder.re.ts ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierCylinder)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierCollider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RapierCollider */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class RapierCylinder extends _RapierCollider__WEBPACK_IMPORTED_MODULE_3__["default"] {
  constructor() {
    super(...arguments);
    this._halfHeight = 0.5;
    this._radius = 1;
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
  }
  get halfHeight() {
    return this._halfHeight;
  }
  set halfHeight(value) {
    const oldValue = this._halfHeight;
    this._halfHeight = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  get radius() {
    return this._radius;
  }
  set radius(value) {
    const oldValue = this._radius;
    this._radius = value;
    if (oldValue !== value && this.collider && _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world) {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.removeCollider(this.collider, false);
      this.init();
    }
  }
  createShape() {
    this.object3d.getWorldScale(this.worldScale);
    const maxSide = Math.max(this.worldScale.x, this.worldScale.z);
    let colliderDesc = _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ColliderDesc.cylinder(this.halfHeight * this.worldScale.y, this.radius * maxSide);
    this.collider = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.createCollider(colliderDesc, this.body);
  }
}
__name(RapierCylinder, "RapierCylinder");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCylinder.prototype, "halfHeight", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierCylinder.prototype, "radius", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierCylinder);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierTrimesh.re.ts":
/*!*************************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierTrimesh.re.ts ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierTrimesh)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierCollider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RapierCollider */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts");
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });





class RapierTrimesh extends _RapierCollider__WEBPACK_IMPORTED_MODULE_3__["default"] {
  constructor() {
    super(...arguments);
    this.worldScale = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.worldPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.tmpVec0 = new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].Vector3(0, 0, 0);
    this.tmpVec1 = new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].Vector3(0, 0, 0);
    this.tmpVec2 = new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].Vector3(0, 0, 0);
    this.tmpQuat0 = new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].Vector3(0, 0, 0);
  }
  createShape() {
    if (!(this.object3d instanceof three__WEBPACK_IMPORTED_MODULE_1__.Mesh))
      return;
    this.object3d.updateWorldMatrix(true, true);
    this.object3d.getWorldScale(this.worldScale);
    this.object3d.getWorldPosition(this.worldPos);
    this.object3d.getWorldQuaternion(this.worldQuaternion);
    const mesh = this.object3d;
    let geometry = mesh.geometry;
    const vertices = this.getVertices(geometry);
    if (!vertices.length)
      return;
    const indices = geometry.getIndex();
    if (!indices)
      return;
    let cleanIndiArray = [];
    for (let i = 0; i < indices.count; i += 3) {
      const a = indices.getX(i);
      const b = indices.getX(i + 1);
      const c = indices.getX(i + 2);
      cleanIndiArray.push(a, b, c);
    }
    let colliderDesc = _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ColliderDesc.trimesh(vertices, new Uint32Array(cleanIndiArray));
    this.collider = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.createCollider(colliderDesc, this.body);
  }
  getVertices(geometry) {
    const position = geometry.attributes.position;
    const vertices = new Float32Array(position.count * 3);
    for (let i = 0; i < position.count; i++) {
      vertices[i * 3] = position.getX(i) * this.worldScale.x;
      vertices[i * 3 + 1] = position.getY(i) * this.worldScale.y;
      vertices[i * 3 + 2] = position.getZ(i) * this.worldScale.z;
    }
    return vertices;
  }
}
__name(RapierTrimesh, "RapierTrimesh");
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierTrimesh);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierBody.re.ts":
/*!************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierBody.re.ts ***!
  \************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierBody)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};




class RapierBody extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.type = 0;
    this.typeOptions = ["Dynamic", "Fixed", "KinematicPositionBased", "KinematicVelocityBased"];
    this.mass = 1;
    this._gravityScale = 1;
    this._angularDamping = 0;
    this._linearDamping = 0;
    this._xTranslation = true;
    this._yTranslation = true;
    this._zTranslation = true;
    this._xRotation = true;
    this._yRotation = true;
    this._zRotation = true;
    this.initialized = false;
    this.onCollisionStart = /* @__PURE__ */ __name(() => {
    }, "onCollisionStart");
    this.onCollisionEnd = /* @__PURE__ */ __name(() => {
    }, "onCollisionEnd");
    this.newPos = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3();
    this.newRot = new three__WEBPACK_IMPORTED_MODULE_1__.Quaternion();
    this.matrixA = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixB = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
    this.matrixC = new three__WEBPACK_IMPORTED_MODULE_1__.Matrix4();
  }
  get gravityScale() {
    return this._gravityScale;
  }
  set gravityScale(value) {
    this._gravityScale = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setGravityScale(value, true);
  }
  get angularDamping() {
    return this._angularDamping;
  }
  set angularDamping(value) {
    this._angularDamping = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setAngularDamping(value);
  }
  get linearDamping() {
    this.body;
    return this._linearDamping;
  }
  set linearDamping(value) {
    this._linearDamping = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setLinearDamping(value);
  }
  get xTranslation() {
    return this._xTranslation;
  }
  set xTranslation(value) {
    this._xTranslation = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setEnabledTranslations(value, this._yTranslation, this._zTranslation, true);
  }
  get yTranslation() {
    return this._yTranslation;
  }
  set yTranslation(value) {
    this._yTranslation = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setEnabledTranslations(this._xTranslation, value, this._zTranslation, true);
  }
  get zTranslation() {
    return this._zTranslation;
  }
  set zTranslation(value) {
    this._zTranslation = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setEnabledTranslations(this._xTranslation, this._yTranslation, value, true);
  }
  get xRotation() {
    return this._xRotation;
  }
  set xRotation(value) {
    this._xRotation = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setEnabledRotations(value, this._yRotation, this._zRotation, true);
  }
  get yRotation() {
    return this._yRotation;
  }
  set yRotation(value) {
    this._yRotation = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setEnabledRotations(this._xRotation, value, this._zRotation, true);
  }
  get zRotation() {
    return this._zRotation;
  }
  set zRotation(value) {
    this._zRotation = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && this.body && this.body.setEnabledRotations(this._xRotation, this._yRotation, value, true);
  }
  init() {
    let rigidBodyDesc = this.getType();
    this.object3d.getWorldPosition(this.newPos);
    this.object3d.getWorldQuaternion(this.newRot);
    rigidBodyDesc.setGravityScale(this._gravityScale).setTranslation(this.newPos.x, this.newPos.y, this.newPos.z).setRotation(this.newRot).setAngularDamping(this._angularDamping).setLinearDamping(this._linearDamping).enabledRotations(this._xRotation, this._yRotation, this._zRotation).enabledTranslations(this._xTranslation, this._yTranslation, this._zTranslation);
    rigidBodyDesc.mass = this.mass;
    this.body = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.createRigidBody(rigidBodyDesc);
    this.body.userData = { object3d: this.object3d.uuid };
    this.initialized = true;
  }
  getType() {
    if (Number(this.type) === 1)
      return _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_3__["default"].RigidBodyDesc.fixed();
    else if (Number(this.type) === 2)
      return _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_3__["default"].RigidBodyDesc.kinematicPositionBased();
    else if (Number(this.type) === 3)
      return _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_3__["default"].RigidBodyDesc.kinematicVelocityBased();
    else
      return _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_3__["default"].RigidBodyDesc.dynamic();
  }
  beforeUpdate() {
    if (!_Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].initialized)
      return;
    !this.initialized && this.init();
    this.type !== _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_3__["default"].RigidBodyType.Fixed && this.updatePhysics();
  }
  updatePhysics() {
    this.copyBodyPosition();
    this.copyBodyRotation();
  }
  copyBodyPosition() {
    const pos = this.body.translation();
    this.newPos.set(pos.x, pos.y, pos.z);
    this.object3d.parent?.worldToLocal(this.newPos);
    this.object3d.position.copy(this.newPos);
  }
  copyBodyRotation() {
    const rot = this.body.rotation();
    this.newRot.set(rot.x, rot.y, rot.z, rot.w);
    this.matrixA.makeRotationFromQuaternion(this.newRot);
    this.object3d.updateMatrixWorld();
    this.matrixB.copy(this.object3d.parent.matrixWorld).invert();
    this.matrixC.extractRotation(this.matrixB);
    this.matrixA.premultiply(this.matrixC);
    this.object3d.quaternion.setFromRotationMatrix(this.matrixA);
  }
}
__name(RapierBody, "RapierBody");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.select()
], RapierBody.prototype, "type", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierBody.prototype, "mass", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierBody.prototype, "gravityScale", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierBody.prototype, "angularDamping", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.num()
], RapierBody.prototype, "linearDamping", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierBody.prototype, "xTranslation", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierBody.prototype, "yTranslation", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierBody.prototype, "zTranslation", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierBody.prototype, "xRotation", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierBody.prototype, "yRotation", 1);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierBody.prototype, "zRotation", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierBody);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierConfig.re.ts":
/*!**************************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierConfig.re.ts ***!
  \**************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RapierConfig)
/* harmony export */ });
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rogue-engine */ "rogue-engine");
/* harmony import */ var rogue_engine__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(rogue_engine__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three */ "three");
/* harmony import */ var three__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(three__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Lib/RogueRapier */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/* harmony import */ var _RapierBody_re__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RapierBody.re */ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierBody.re.ts");
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};





class RapierConfig extends rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor() {
    super(...arguments);
    this.gravity = new three__WEBPACK_IMPORTED_MODULE_1__.Vector3(0, -9.81, 0);
    this._debug = false;
    this.lines = new three__WEBPACK_IMPORTED_MODULE_1__.LineSegments(new three__WEBPACK_IMPORTED_MODULE_1__.BufferGeometry(), new three__WEBPACK_IMPORTED_MODULE_1__.LineBasicMaterial({ color: new three__WEBPACK_IMPORTED_MODULE_1__.Color("#00FF00") }));
  }
  get debug() {
    return this._debug;
  }
  set debug(value) {
    this._debug = value;
    rogue_engine__WEBPACK_IMPORTED_MODULE_0__.Runtime.isRunning && value ? rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.add(this.lines) : rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.remove(this.lines);
  }
  awake() {
    this.lines.name = "Rapier Debug Lines";
    _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].init(() => {
      _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.gravity = this.gravity;
    });
  }
  start() {
    if (this.debug) {
      rogue_engine__WEBPACK_IMPORTED_MODULE_0__.App.currentScene.add(this.lines);
    }
  }
  beforeUpdate() {
    if (!_Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].initialized)
      return;
    if (this.debug) {
      let buffers = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.debugRender();
      this.lines.geometry.setAttribute("position", new three__WEBPACK_IMPORTED_MODULE_1__.BufferAttribute(buffers.vertices, 3));
      this.lines.geometry.setAttribute("color", new three__WEBPACK_IMPORTED_MODULE_1__.BufferAttribute(buffers.colors, 4));
    }
    _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.step(_Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].eventQueue);
    _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].eventQueue.drainCollisionEvents((handle1, handle2, started) => {
      const col1 = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.getCollider(handle1);
      const col2 = _Lib_RogueRapier__WEBPACK_IMPORTED_MODULE_2__["default"].world.getCollider(handle2);
      const body1 = col1.parent();
      const body2 = col2.parent();
      const components = rogue_engine__WEBPACK_IMPORTED_MODULE_0__.getComponents(_RapierBody_re__WEBPACK_IMPORTED_MODULE_3__["default"]);
      let bodyComp1;
      let bodyComp2;
      components.forEach((bodyComp) => {
        if (bodyComp.body.handle === body1?.handle) {
          bodyComp1 = bodyComp;
        } else if (bodyComp.body.handle === body2?.handle) {
          bodyComp2 = bodyComp;
        }
      });
      if (bodyComp1 && col1.activeEvents() === _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ActiveEvents.COLLISION_EVENTS) {
        const colInfo = { ownCollider: col1, otherCollider: col2, otherBody: bodyComp2 };
        started ? bodyComp1.onCollisionStart(colInfo) : bodyComp1.onCollisionEnd(colInfo);
      }
      if (bodyComp2 && col2.activeEvents() === _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_4__["default"].ActiveEvents.COLLISION_EVENTS) {
        const colInfo = { ownCollider: col1, otherCollider: col2, otherBody: bodyComp1 };
        started ? bodyComp2.onCollisionStart(colInfo) : bodyComp2.onCollisionEnd(colInfo);
      }
    });
  }
}
__name(RapierConfig, "RapierConfig");
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.vector3()
], RapierConfig.prototype, "gravity", 2);
__decorateClass([
  rogue_engine__WEBPACK_IMPORTED_MODULE_0__.props.checkbox()
], RapierConfig.prototype, "debug", 1);
rogue_engine__WEBPACK_IMPORTED_MODULE_0__.registerComponent(RapierConfig);


/***/ }),

/***/ "./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts":
/*!***************************************************************************!*\
  !*** ./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts ***!
  \***************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RogueRapier)
/* harmony export */ });
/* harmony import */ var _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @dimforge/rapier3d-compat */ "./node_modules/@dimforge/rapier3d-compat/rapier.es.js");
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

class RogueRapier {
  static init(onDone) {
    this.initialized = false;
    const done = this.doInit();
    done.then(() => onDone());
  }
  static async doInit() {
    await _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_0__["default"].init();
    this.world = new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_0__["default"].World({ x: 0, y: -9.81, z: 0 });
    this.eventQueue && this.eventQueue.clear();
    this.eventQueue = this.eventQueue || new _dimforge_rapier3d_compat__WEBPACK_IMPORTED_MODULE_0__["default"].EventQueue(true);
    this.initialized = true;
  }
}
__name(RogueRapier, "RogueRapier");
RogueRapier.initialized = false;


/***/ }),

/***/ "rogue-engine":
/*!******************************************************************************************************************!*\
  !*** external {"commonjs":"rogue-engine","commonjs2":"rogue-engine","amd":"rogue-engine","root":"rogue-engine"} ***!
  \******************************************************************************************************************/
/***/ ((module) => {

module.exports = __WEBPACK_EXTERNAL_MODULE_rogue_engine__;

/***/ }),

/***/ "three":
/*!**************************************************************************************!*\
  !*** external {"commonjs":"three","commonjs2":"three","amd":"three","root":"three"} ***!
  \**************************************************************************************/
/***/ ((module) => {

module.exports = __WEBPACK_EXTERNAL_MODULE_three__;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = __webpack_modules__;
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/chunk loaded */
/******/ 	(() => {
/******/ 		var deferred = [];
/******/ 		__webpack_require__.O = (result, chunkIds, fn, priority) => {
/******/ 			if(chunkIds) {
/******/ 				priority = priority || 0;
/******/ 				for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];
/******/ 				deferred[i] = [chunkIds, fn, priority];
/******/ 				return;
/******/ 			}
/******/ 			var notFulfilled = Infinity;
/******/ 			for (var i = 0; i < deferred.length; i++) {
/******/ 				var [chunkIds, fn, priority] = deferred[i];
/******/ 				var fulfilled = true;
/******/ 				for (var j = 0; j < chunkIds.length; j++) {
/******/ 					if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {
/******/ 						chunkIds.splice(j--, 1);
/******/ 					} else {
/******/ 						fulfilled = false;
/******/ 						if(priority < notFulfilled) notFulfilled = priority;
/******/ 					}
/******/ 				}
/******/ 				if(fulfilled) {
/******/ 					deferred.splice(i--, 1)
/******/ 					var r = fn();
/******/ 					if (r !== undefined) result = r;
/******/ 				}
/******/ 			}
/******/ 			return result;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/jsonp chunk loading */
/******/ 	(() => {
/******/ 		// no baseURI
/******/ 		
/******/ 		// object to store loaded and loading chunks
/******/ 		// undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ 		// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ 		var installedChunks = {
/******/ 			"rogue-engine-user-scripts": 0
/******/ 		};
/******/ 		
/******/ 		// no chunk on demand loading
/******/ 		
/******/ 		// no prefetching
/******/ 		
/******/ 		// no preloaded
/******/ 		
/******/ 		// no HMR
/******/ 		
/******/ 		// no HMR manifest
/******/ 		
/******/ 		__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);
/******/ 		
/******/ 		// install a JSONP callback for chunk loading
/******/ 		var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ 			var [chunkIds, moreModules, runtime] = data;
/******/ 			// add "moreModules" to the modules object,
/******/ 			// then flag all "chunkIds" as loaded and fire callback
/******/ 			var moduleId, chunkId, i = 0;
/******/ 			if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ 				for(moduleId in moreModules) {
/******/ 					if(__webpack_require__.o(moreModules, moduleId)) {
/******/ 						__webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ 					}
/******/ 				}
/******/ 				if(runtime) var result = runtime(__webpack_require__);
/******/ 			}
/******/ 			if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ 			for(;i < chunkIds.length; i++) {
/******/ 				chunkId = chunkIds[i];
/******/ 				if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ 					installedChunks[chunkId][0]();
/******/ 				}
/******/ 				installedChunks[chunkId] = 0;
/******/ 			}
/******/ 			return __webpack_require__.O(result);
/******/ 		}
/******/ 		
/******/ 		var chunkLoadingGlobal = self["webpackChunkroguetemplateproject"] = self["webpackChunkroguetemplateproject"] || [];
/******/ 		chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ 		chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	__webpack_require__("./Assets/Components/Animator.re.ts");
/******/ 	__webpack_require__("./Assets/Components/BallRaycastReceiver.re.ts");
/******/ 	__webpack_require__("./Assets/Components/CannonMovementController.re.ts");
/******/ 	__webpack_require__("./Assets/Components/FaceDirectionOfVelocityComponent.re.ts");
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	__webpack_require__("./Assets/Components/FloorCheckComponent.re.ts");
/******/ 	__webpack_require__("./Assets/Components/FloorRaycastReceiver.re.ts");
/******/ 	__webpack_require__("./Assets/Components/GameLogic.re.ts");
/******/ 	__webpack_require__("./Assets/Components/MovementController.re.ts");
/******/ 	__webpack_require__("./Assets/Components/RapierMovementController.re.ts");
/******/ 	__webpack_require__("./Assets/Components/RaycastReceiver.re.ts");
/******/ 	__webpack_require__("./Assets/Components/RaycastReporter.re.ts");
/******/ 	__webpack_require__("./Assets/Library/GetForwardVector.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonBody.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/CannonConfig.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonConstraint.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonDistanceConstraint.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonHingeConstraint.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonLockConstraint.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Constraints/CannonPointToPointConstraint.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Controllers/CannonSimpleCharacterController.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Controllers/CannonVehicleController.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/CannonContactMaterial.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/CannonMaterial.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Material/SetCannonMaterial.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonRaycastVehicle.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonSpring.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Objects/CannonWheel.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonBox.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonCylinder.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonShape.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonSphere.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Components/Shapes/CannonTrimesh.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/index.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/BeardScript/rogue-cannon/Lib/RogueCannon.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/EyeOfMidas/targeted-orbit-camera/TargetedOrbitCamera.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierBall.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCapsule.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCollider.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCone.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCuboid.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierCylinder.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/Colliders/RapierTrimesh.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierBody.re.ts");
/******/ 	__webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Components/RapierConfig.re.ts");
/******/ 	var __webpack_exports__ = __webpack_require__("./Assets/rogue_packages/RogueEngine/rogue-rapier/Lib/RogueRapier.ts");
/******/ 	__webpack_exports__ = __webpack_require__.O(__webpack_exports__);
/******/ 	
/******/ 	return __webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=rogue-engine-user-scripts.js.map