@hology/core 0.0.110 → 0.0.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -44,6 +44,7 @@ export declare class Trail extends THREE.Object3D {
44
44
  initializeMesh(): void;
45
45
  destroyMesh(): void;
46
46
  reset(): void;
47
+ setAllNodesToCurrentTargetPosition(): void;
47
48
  updateUniforms(): void;
48
49
  advance: () => void;
49
50
  advanceWithPositionAndOrientation(nextPosition: any, orientationTangent: any): void;
@@ -1 +1 @@
1
- {"version":3,"file":"trail-renderer.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/trail-renderer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAC,kBAAkB,EAAuP,MAAM,oBAAoB,CAAC;AAC5S,OAAO,EAAC,oBAAoB,EAAC,MAAM,gBAAgB,CAAC;AAiCpD,eAAO,MAAM,OAAO,uCAMlB,CAAA;AAEF,eAAO,MAAM,WAAW,uCAGtB,CAAA;AAEF,qBAAa,KAAM,SAAQ,KAAK,CAAC,QAAQ;IACvC,MAAM,EAAE,OAAO,CAAA;IACf,gBAAgB,EAAE,OAAO,CAAA;IACzB,SAAS,EAAE,OAAO,CAAA;IAClB,KAAK,EAAE,GAAG,CAAA;IACV,QAAQ,EAAE,KAAK,CAAC,cAAc,GAAG,IAAI,CAAA;IACrC,IAAI,EAAE,KAAK,CAAC,IAAI,GAAG,IAAI,CAAA;IACvB,WAAW,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAK;IACtC,cAAc,EAAE,KAAK,CAAC,OAAO,GAAG,IAAI,CAAA;IACpC,iBAAiB,EAAE,KAAK,CAAC,OAAO,GAAG,IAAI,CAAA;IACvC,kBAAkB,EAAE,KAAK,CAAC,OAAO,GAAG,IAAI,CAAA;IACxC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAK;IAC3B,aAAa,EAAE,MAAM,CAAA;IAC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AAe,WAEzB;IAED,MAAM,CAAC,wBAAwB,gBAA6B;IAC5D,MAAM,KAAK,uBAAuB,kBAEjC;IAED,MAAM,CAAC,gBAAgB,gBAA6B;IACpD,MAAM,KAAK,eAAe,kBAEzB;IAED,MAAM,KAAK,sBAAsB,WAEhC;IAED,MAAM,KAAK,gBAAgB,WAE1B;IAED,MAAM,KAAK,cAAc,WAExB;IAED,MAAM,KAAK,YAAY,WAEtB;IAED,MAAM,CAAC,MAAM;;;;;;;;;;MAsGZ;CACF"}
@@ -1,4 +1,4 @@
1
- import{timeUniforms as e}from"../../shader-nodes";import*as t from"three";import{NodeShaderMaterial as r,uniformBool as i,uniformFloat as a,uniformVec2 as n,mix as s,uniformVec4 as o,attributeFloat as h,attributeVec3 as c,select as l,float as d,textureSampler2d as u,attributes as m,uniforms as g,rgba as p,vec4 as y,varying as f,vec2 as x,normalize as v,cross as T,max as V}from"three-shader-graph";a("trailLength");const C=a("verticesPerNode"),N=a("minID"),P=a("maxID"),b=(a("dragTexture"),a("maxTrailLength")),D=n("textureTileFactor",new t.Vector2(1,1)),w=o("headColor",new t.Vector4),F=o("tailColor",new t.Vector4),I=i("taper",!1),U=(a("scale",1),h("nodeID")),A=h("nodeVertexID"),L=c("nodeCenter"),M=P.subtract(U).divide(P.subtract(N)),S=l(I,M,d(0)),B=f(d(1).subtract(M).multiplyVec4(w).add(M.multiplyVec4(F))),H=v(g.cameraPosition.subtract(L)),z=v(c("nodeTangent")),G=a("width",1),O=v(T(z,H)).multiplyScalar(A.subtract(d(.5))).multiplyScalar(G),j=y(d(1).subtract(S).multiplyVec3(O).add(V(S,d(1)).multiplyVec3(L)),1),E=y(d(1).subtract(S).multiplyVec3(m.position).add(S.multiplyVec3(L)),1),R=g.projectionMatrix.multiply(g.viewMatrix).multiplyVec(j),q=g.projectionMatrix.multiply(g.viewMatrix).multiplyVec(E);export const trailUV=f(x(M.multiply(D.x),A.divide(C).multiply(D.y).multiply(2)));export const trailDragUV=f(x(U.divide(b).multiply(D.x),A.divide(C).multiply(D.y).multiply(2)));export class Trail extends t.Object3D{constructor(e,r){super(),this.nodeCenters=[],this.nodeIDs=[],this.advance=function(){const e=new t.Matrix4;return function(){this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.advanceWithTransform(e),this.updateUniforms()}}(),this.advanceGeometry=function(e,t){const r=this.currentEnd+1>=this.length?0:this.currentEnd+1;if(t?this.updateNodePositionsFromTransformMatrix(r,t):this.updateNodePositionsFromOrientationTangent(r,e.position,e.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,r),this.currentLength>=this.length)){const e=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(e)}this.currentLength<this.length&&this.currentLength++,this.currentEnd++,this.currentEnd>=this.length&&(this.currentEnd=0),this.currentLength>=1&&(this.currentLength<this.length?this.geometry.setDrawRange(0,(this.currentLength-1)*this.FaceIndicesPerNode):this.geometry.setDrawRange(0,this.currentLength*this.FaceIndicesPerNode)),this.updateNodeID(this.currentEnd,this.currentNodeID),this.currentNodeID++},this.updateHead=function(){const e=new t.Matrix4;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}}(),this.updateNodePositionsFromOrientationTangent=function(){const e=new t.Quaternion,r=new t.Vector3,i=[];for(let e=0;e<Trail.MaxHeadVertices;e++){const e=new t.Vector3;i.push(e)}return function(t,a,n){const s=this.geometry.getAttribute("position");this.updateNodeCenter(t,a),r.copy(a),r.sub(Trail.LocalHeadOrigin),e.setFromUnitVectors(Trail.LocalOrientationTangent,n);for(let t=0;t<this.localHeadGeometry.length;t++){const a=i[t];a.copy(this.localHeadGeometry[t]),a.applyQuaternion(e),a.add(r)}for(let e=0;e<this.localHeadGeometry.length;e++){const r=(this.VerticesPerNode*t+e)*Trail.PositionComponentCount,a=i[e];s.array[r]=a.x,s.array[r+1]=a.y,s.array[r+2]=a.z}s.needsUpdate=!0}}(),this.updateNodePositionsFromTransformMatrix=function(){const e=new t.Matrix3,r=new t.Quaternion,i=new t.Vector3,a=new t.Vector3,n=new t.Vector3,s=new t.Vector3,o=new t.Box3,h=new t.Vector3,c=[];for(let e=0;e<Trail.MaxHeadVertices;e++){const e=new t.Vector3;c.push(e)}const l=new t.Vector3(1,0,0);return function(d,u){const m=this.geometry.getAttribute("position");i.set(0,0,0),i.applyMatrix4(u),this.updateNodeCenter(d,i);for(let e=0;e<this.localHeadGeometry.length;e++){c[e].copy(this.localHeadGeometry[e])}for(let e=0;e<this.localHeadGeometry.length;e++){c[e].applyMatrix4(u)}if(this.lastNodeCenter&&this.orientToMovement&&(function(e,t){const r=t.elements;e.set(r[0],r[1],r[2],r[4],r[5],r[6],r[8],r[9],r[10])}(e,u),n.set(0,0,-1),n.applyMatrix3(e),s.copy(this.currentNodeCenter),s.sub(this.lastNodeCenter),s.normalize(),s.lengthSq()<=1e-4&&this.lastOrientationDir&&s.copy(this.lastOrientationDir),s.lengthSq()>1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new t.Vector3),r.setFromUnitVectors(n,s),a.copy(this.currentNodeCenter);for(let e=0;e<this.localHeadGeometry.length;e++){const t=c[e];t.sub(a),t.applyQuaternion(r),t.add(a)}}this.lastNodeCenter&&this.currentNodeCenter&&this.billboard&&!this.currentNodeCenter.equals(this.lastNodeCenter)&&(l.copy(this.currentNodeCenter).sub(this.lastNodeCenter),l.normalize());const g=this.geometry.getAttribute("nodeTangent");for(let e=0;e<this.localHeadGeometry.length;e++){const t=(this.VerticesPerNode*d+e)*Trail.PositionComponentCount,r=c[e];this.billboard?(g.array[t]=l.x,g.array[t+1]=l.y,g.array[t+2]=l.z):(m.array[t]=r.x,m.array[t+1]=r.y,m.array[t+2]=r.z)}this.billboard?(this.mesh.frustumCulled=!1,g.needsUpdate=!0,g.updateRange={offset:d*this.VerticesPerNode*3,count:3*this.VerticesPerNode}):(m.needsUpdate=!0,m.addUpdateRange(d*this.VerticesPerNode*Trail.PositionComponentCount,this.VerticesPerNode*Trail.PositionComponentCount)),o.makeEmpty();for(let e=0;e<this.currentLength*this.VerticesPerNode;e++){const t=3*e;h.set(m.array[t],m.array[t+1],m.array[t+2]),o.expandByPoint(h)}this.mesh.visible=!o.isEmpty(),null==this.geometry.boundingBox&&(this.geometry.boundingBox=new t.Box3),this.geometry.boundingBox.copy(o),null==this.geometry.boundingSphere&&(this.geometry.boundingSphere=new t.Sphere),this.geometry.boundingBox.getBoundingSphere(this.geometry.boundingSphere)}}(),this.connectNodes=(()=>{const e={attribute:null,offset:0,count:-1};return(t,r)=>{const i=this.geometry.getIndex();for(let e=0;e<this.localHeadGeometry.length-1;e++){const a=this.VerticesPerNode*t+e,n=this.VerticesPerNode*r+e,s=(t*this.FacesPerNode+e*Trail.FacesPerQuad)*Trail.IndicesPerFace;i.array[s]=a,i.array[s+1]=n,i.array[s+2]=a+1,i.array[s+3]=n,i.array[s+4]=n+1,i.array[s+5]=a+1}return i.needsUpdate=!0,i.clearUpdateRanges(),e.attribute=i,e.offset=t*this.FacesPerNode*Trail.IndicesPerFace,e.count=this.FacesPerNode*Trail.IndicesPerFace,e}})(),this.disconnectNodes=(()=>{const e={attribute:null,offset:0,count:-1};return t=>{const r=this.geometry.getIndex();for(let e=0;e<this.localHeadGeometry.length-1;e++){const i=(t*this.FacesPerNode+e*Trail.FacesPerQuad)*Trail.IndicesPerFace;r.array[i]=0,r.array[i+1]=0,r.array[i+2]=0,r.array[i+3]=0,r.array[i+4]=0,r.array[i+5]=0}return r.needsUpdate=!0,r.clearUpdateRanges(),e.attribute=r,e.offset=t*this.FacesPerNode*Trail.IndicesPerFace,e.count=this.FacesPerNode*Trail.IndicesPerFace,e}})(),this.active=!1,this.orientToMovement=!1,r&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=[],this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=[],this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,r,i,a,n,s,o=!1){this.deactivate(),this.destroyMesh(),this.length=r>0?r+1:0,this.dragTexture=i?1:0,this.targetObject=s,this.billboard=o,this.initializeLocalHeadGeometry(a,n),null!=e.uniforms.width&&(e.uniforms.width.value=a),this.nodeIDs=[],this.nodeCenters=[];for(let e=0;e<this.length;e++)this.nodeIDs[e]=-1,this.nodeCenters[e]=new t.Vector3;this.material=e,this.initializeGeometry(),this.initializeMesh(),this.material.uniforms.dragTexture&&(this.material.uniforms.trailLength.value=0),this.material.uniforms.minID.value=0,this.material.uniforms.maxID.value=0,this.material.uniforms.dragTexture&&(this.material.uniforms.dragTexture.value=this.dragTexture),this.material.uniforms.maxTrailLength&&(this.material.uniforms.maxTrailLength.value=this.length),this.material.uniforms.verticesPerNode&&(this.material.uniforms.verticesPerNode.value=this.VerticesPerNode),this.material.uniforms.textureTileFactor&&(this.material.uniforms.textureTileFactor.value=new t.Vector2(1,1)),this.material.uniforms.scale&&(this.material.uniforms.scale.value=1),this.reset()}initializeLocalHeadGeometry(e,r){if(this.localHeadGeometry=[],r){this.VerticesPerNode=0;for(let e=0;e<r.length&&e<Trail.MaxHeadVertices;e++){const i=r[e];if(i&&i instanceof t.Vector3){const e=new t.Vector3;e.copy(i),this.localHeadGeometry.push(e),this.VerticesPerNode++}}}else{const r=(e||1)/2;this.localHeadGeometry.push(new t.Vector3(-r,0,0)),this.localHeadGeometry.push(new t.Vector3(r,0,0)),this.VerticesPerNode=2}this.FacesPerNode=2*(this.VerticesPerNode-1),this.FaceIndicesPerNode=3*this.FacesPerNode}initializeGeometry(){this.vertexCount=this.length*this.VerticesPerNode,this.faceCount=this.length*this.FacesPerNode;const e=new t.BufferGeometry,r=new Float32Array(this.vertexCount),i=new Float32Array(this.vertexCount*this.VerticesPerNode),a=new Float32Array(this.vertexCount*Trail.PositionComponentCount),n=new Float32Array(this.vertexCount*Trail.PositionComponentCount),s=new Float32Array(this.vertexCount*Trail.UVComponentCount),o=new Uint32Array(this.faceCount*Trail.IndicesPerFace),h=new Float32Array(3*this.vertexCount),c=new t.BufferAttribute(h,3);c.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeTangent",c);const l=new t.BufferAttribute(r,1);l.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeID",l);const d=new t.BufferAttribute(i,1);d.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeVertexID",d);const u=new t.BufferAttribute(n,Trail.PositionComponentCount);u.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeCenter",u);const m=new t.BufferAttribute(a,Trail.PositionComponentCount);m.setUsage(t.DynamicDrawUsage),e.setAttribute("position",m);const g=new t.BufferAttribute(s,Trail.UVComponentCount);g.setUsage(t.DynamicDrawUsage),e.setAttribute("uv",g);const p=new t.BufferAttribute(o,1);p.setUsage(t.DynamicDrawUsage),e.setIndex(p),this.geometry=e}zeroVertices(){const e=this.geometry.getAttribute("position");for(let t=0;t<this.vertexCount;t++){const r=3*t;e.array[r]=0,e.array[r+1]=0,e.array[r+2]=0}e.needsUpdate=!0}zeroIndices(){if(null==this.geometry)throw"Geometry not initialized";const e=this.geometry.getIndex();for(let t=0;t<this.faceCount;t++){const r=3*t;e.array[r]=0,e.array[r+1]=0,e.array[r+2]=0}e.needsUpdate=!0,e.clearUpdateRanges()}formInitialFaces(){this.zeroIndices();const e=this.geometry.getIndex();for(let e=0;e<this.length-1;e++)this.connectNodes(e,e+1);e.needsUpdate=!0,e.clearUpdateRanges()}initializeMesh(){if(null==this.geometry)throw"Geometry not initialized";this.mesh=new t.Mesh(this.geometry,this.material),this.mesh.matrixAutoUpdate=!1}destroyMesh(){this.mesh&&(this.scene.remove(this.mesh),this.mesh=null)}reset(){this.currentLength=0,this.currentEnd=-1,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.currentNodeID=0,this.formInitialFaces(),this.zeroVertices(),this.geometry.setDrawRange(0,0)}updateUniforms(){this.currentLength<this.length?this.material.uniforms.minID.value=0:this.material.uniforms.minID.value=this.currentNodeID-this.length,this.material.uniforms.maxID.value=this.currentNodeID,this.material.uniforms.trailLength&&(this.material.uniforms.trailLength.value=this.currentLength),this.material.uniforms.maxTrailLength&&(this.material.uniforms.maxTrailLength.value=this.length),this.material.uniforms.verticesPerNod&&(this.material.uniforms.verticesPerNode.value=this.VerticesPerNode)}advanceWithPositionAndOrientation(e,t){this.advanceGeometry({position:e,tangent:t},null)}advanceWithTransform(e){this.advanceGeometry(null,e)}currentTime(){return performance.now()/1e3}pause(){this.paused||(this.paused=!0,this.pauseAdvanceUpdateTimeDiff=this.currentTime()-this.lastAdvanceTime)}resume(){this.paused&&(this.paused=!1,this.lastAdvanceTime=this.currentTime()-this.pauseAdvanceUpdateTimeDiff)}update(){if(!this.paused){const e=this.currentTime();this.lastAdvanceTime||(this.lastAdvanceTime=e),e-this.lastAdvanceTime>this.advancePeriod?(this.advance(),this.lastAdvanceTime=e):this.updateHead()}}updateNodeID(e,t){this.nodeIDs[e]=t;const r=this.geometry.getAttribute("nodeID"),i=this.geometry.getAttribute("nodeVertexID");for(let a=0;a<this.VerticesPerNode;a++){const n=e*this.VerticesPerNode+a;r.array[n]=t,i.array[n]=a}r.needsUpdate=!0,i.needsUpdate=!0,r.addUpdateRange(e*this.VerticesPerNode,this.VerticesPerNode),i.addUpdateRange(e*this.VerticesPerNode,this.VerticesPerNode)}updateNodeCenter(e,t){this.lastNodeCenter=this.currentNodeCenter,this.currentNodeCenter=this.nodeCenters[e],this.currentNodeCenter.copy(t);const r=this.geometry.getAttribute("nodeCenter");for(let i=0;i<this.VerticesPerNode;i++){const a=3*(e*this.VerticesPerNode+i);r.array[a]=t.x,r.array[a+1]=t.y,r.array[a+2]=t.z}r.needsUpdate=!0,r.updateRanges=[{start:e*this.VerticesPerNode*Trail.PositionComponentCount,count:this.VerticesPerNode*Trail.PositionComponentCount}]}deactivate(){this.active&&(this.scene.remove(this.mesh),this.active=!1)}activate(){this.active||(this.scene.add(this.mesh),this.active=!0)}static getTrailShaderNodes(e){return{position:e?R:q,color:B,fraction:M}}static applyTrailShaderParameters(e){e.transparent=!0,e.alphaTest=.5,e.blending=t.CustomBlending,e.blendSrc=t.SrcAlphaFactor,e.blendDst=t.OneMinusSrcAlphaFactor,e.blendEquation=t.AddEquation,e.depthTest=!0,e.depthWrite=!1,e.side=t.DoubleSide}static createBaseMaterial(t,i,a,n=!1){let{position:o}=Trail.getTrailShaderNodes(n),h=s(w,F,M).rgba;if(null!=t){let r=trailUV;null!=i&&(r=r.add(x(e.elapsed.multiply(-i),0)));const n=u(t).sample(r);let s=h.a;switch(a??"red"){case"none":break;case"red":s=s.multiply(n.r);break;case"alpha":s=s.multiply(n.a)}h=p(h.rgb.multiply(n.rgb),s)}const c=new r({position:o,color:h});return Trail.applyTrailShaderParameters(c),c}static get MaxHeadVertices(){return 128}static get LocalOrientationTangent(){return Trail._LocalOrientationTangent}static get LocalHeadOrigin(){return Trail._LocalHeadOrigin}static get PositionComponentCount(){return 3}static get UVComponentCount(){return 2}static get IndicesPerFace(){return 3}static get FacesPerQuad(){return 2}}Trail._LocalOrientationTangent=new t.Vector3(1,0,0),Trail._LocalHeadOrigin=new t.Vector3(0,0,0),Trail.Shader={get BaseVertexVars(){return["attribute float nodeID;","attribute float nodeVertexID;","attribute vec3 nodeCenter;","uniform float minID;","uniform float maxID;","uniform float trailLength;","uniform float maxTrailLength;","uniform float verticesPerNode;","uniform vec2 textureTileFactor;","uniform bool taper;","uniform vec4 headColor;","uniform vec4 tailColor;","varying vec4 vColor;"].join("\n")},get TexturedVertexVars(){return[this.BaseVertexVars,"varying vec2 vUV;","uniform float dragTexture;"].join("\n")},BaseFragmentVars:["varying vec4 vColor;","uniform sampler2D trailTexture;"].join("\n"),get TexturedFragmentVars(){return[this.BaseFragmentVars,"varying vec2 vUV;"].join("\n")},get VertexShaderCore(){return["float fraction = (maxID - nodeID) / (maxID - minID);","float fractionSize = taper ? fraction : 0.0;","vColor = (1.0 - fraction) * headColor + fraction * tailColor;","vec4 realPosition = vec4((1.0 - fractionSize) * position.xyz + fractionSize * nodeCenter.xyz, 1.0); "].join("\n")},get BaseVertexShader(){return[this.BaseVertexVars,"void main() { ",this.VertexShaderCore,"gl_Position = projectionMatrix * viewMatrix * realPosition;","}"].join("\n")},get BaseFragmentShader(){return[this.BaseFragmentVars,"void main() { ","gl_FragColor = vColor;","}"].join("\n")},get TexturedVertexShader(){return[this.TexturedVertexVars,"void main() { ",this.VertexShaderCore,"float s = 0.0;","float t = 0.0;","if (dragTexture == 1.0) { "," s = fraction * textureTileFactor.s; "," t = (nodeVertexID / verticesPerNode) * textureTileFactor.t;","} else { "," s = nodeID / maxTrailLength * textureTileFactor.s;"," t = (nodeVertexID / verticesPerNode) * textureTileFactor.t;","}","vUV = vec2(s, t); ","gl_Position = projectionMatrix * viewMatrix * realPosition;","}"].join("\n")},get TexturedFragmentShader(){return[this.TexturedFragmentVars,"void main() { ","vec4 textureColor = texture2D(trailTexture, vUV);","gl_FragColor = vColor * textureColor;","}"].join("\n")}};/*
1
+ import{timeUniforms as e}from"../../shader-nodes";import*as t from"three";import{NodeShaderMaterial as r,uniformBool as i,uniformFloat as n,uniformVec2 as a,mix as s,uniformVec4 as o,attributeFloat as h,attributeVec3 as l,select as c,float as d,textureSampler2d as u,attributes as m,uniforms as g,rgba as y,vec4 as p,varying as f,vec2 as x,normalize as v,vec3 as T,cross as V,max as C,length as P}from"three-shader-graph";n("trailLength");const N=n("verticesPerNode"),b=n("minID"),D=n("maxID"),w=(n("dragTexture"),n("maxTrailLength")),F=a("textureTileFactor",new t.Vector2(1,1)),I=o("headColor",new t.Vector4),U=o("tailColor",new t.Vector4),A=i("taper",!1),L=(n("scale",1),h("nodeID")),O=h("nodeVertexID"),M=l("nodeCenter"),B=D.subtract(L).divide(D.subtract(b)),S=c(A,B,d(0)),z=f(d(1).subtract(B).multiplyVec4(I).add(B.multiplyVec4(U))),H=v(g.cameraPosition.subtract(M)),G=v(l("nodeTangent")),j=n("width",1),E=v(V(c(P(G).gt(d(.1)),G,T(1,0,0)),H)).multiplyScalar(O.subtract(d(.5))).multiplyScalar(j),R=p(d(1).subtract(S).multiplyVec3(E).add(C(S,d(1)).multiplyVec3(M)),1),W=p(d(1).subtract(S).multiplyVec3(m.position).add(S.multiplyVec3(M)),1),q=g.projectionMatrix.multiply(g.viewMatrix).multiplyVec(R),_=g.projectionMatrix.multiply(g.viewMatrix).multiplyVec(W);export const trailUV=f(x(B.multiply(F.x),O.divide(N).multiply(F.y).multiply(2)));export const trailDragUV=f(x(L.divide(w).multiply(F.x),O.divide(N).multiply(F.y).multiply(2)));export class Trail extends t.Object3D{constructor(e,r){super(),this.nodeCenters=[],this.nodeIDs=[],this.advance=function(){const e=new t.Matrix4;return function(){this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.advanceWithTransform(e),this.updateUniforms()}}(),this.advanceGeometry=function(e,t){const r=this.currentEnd+1>=this.length?0:this.currentEnd+1;if(t?this.updateNodePositionsFromTransformMatrix(r,t):this.updateNodePositionsFromOrientationTangent(r,e.position,e.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,r),this.currentLength>=this.length)){const e=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(e)}this.currentLength<this.length&&this.currentLength++,this.currentEnd++,this.currentEnd>=this.length&&(this.currentEnd=0),this.currentLength>=1?(this.currentLength<this.length?this.geometry.setDrawRange(0,(this.currentLength-1)*this.FaceIndicesPerNode):this.geometry.setDrawRange(0,this.currentLength*this.FaceIndicesPerNode),this.mesh&&(this.mesh.visible=!0)):(this.geometry.setDrawRange(0,0),this.mesh&&(this.mesh.visible=!1)),this.updateNodeID(this.currentEnd,this.currentNodeID),this.currentNodeID++},this.updateHead=function(){const e=new t.Matrix4;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}}(),this.updateNodePositionsFromOrientationTangent=function(){const e=new t.Quaternion,r=new t.Vector3,i=[];for(let e=0;e<Trail.MaxHeadVertices;e++){const e=new t.Vector3;i.push(e)}return function(t,n,a){const s=this.geometry.getAttribute("position");this.updateNodeCenter(t,n),r.copy(n),r.sub(Trail.LocalHeadOrigin),e.setFromUnitVectors(Trail.LocalOrientationTangent,a);for(let t=0;t<this.localHeadGeometry.length;t++){const n=i[t];n.copy(this.localHeadGeometry[t]),n.applyQuaternion(e),n.add(r)}for(let e=0;e<this.localHeadGeometry.length;e++){const r=(this.VerticesPerNode*t+e)*Trail.PositionComponentCount,n=i[e];s.array[r]=n.x,s.array[r+1]=n.y,s.array[r+2]=n.z}s.needsUpdate=!0}}(),this.updateNodePositionsFromTransformMatrix=function(){const e=new t.Matrix3,r=new t.Quaternion,i=new t.Vector3,n=new t.Vector3,a=new t.Vector3,s=new t.Vector3,o=new t.Box3,h=new t.Vector3,l=[];for(let e=0;e<Trail.MaxHeadVertices;e++){const e=new t.Vector3;l.push(e)}const c=new t.Vector3(1,0,0);return function(d,u){const m=this.geometry.getAttribute("position");i.set(0,0,0),i.applyMatrix4(u),this.updateNodeCenter(d,i);for(let e=0;e<this.localHeadGeometry.length;e++){l[e].copy(this.localHeadGeometry[e])}for(let e=0;e<this.localHeadGeometry.length;e++){l[e].applyMatrix4(u)}if(this.lastNodeCenter&&this.orientToMovement&&(function(e,t){const r=t.elements;e.set(r[0],r[1],r[2],r[4],r[5],r[6],r[8],r[9],r[10])}(e,u),a.set(0,0,-1),a.applyMatrix3(e),s.copy(this.currentNodeCenter),s.sub(this.lastNodeCenter),s.normalize(),s.lengthSq()<=1e-4&&this.lastOrientationDir&&s.copy(this.lastOrientationDir),s.lengthSq()>1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new t.Vector3),r.setFromUnitVectors(a,s),n.copy(this.currentNodeCenter);for(let e=0;e<this.localHeadGeometry.length;e++){const t=l[e];t.sub(n),t.applyQuaternion(r),t.add(n)}}this.billboard&&(this.lastNodeCenter&&this.currentNodeCenter&&!this.currentNodeCenter.equals(this.lastNodeCenter)?(c.copy(this.currentNodeCenter).sub(this.lastNodeCenter),c.normalize(),this.lastOrientationDir||(this.lastOrientationDir=new t.Vector3),this.lastOrientationDir.copy(c)):this.lastOrientationDir?c.copy(this.lastOrientationDir):(c.set(1,0,0),c.applyMatrix4(u),c.normalize(),this.lastOrientationDir||(this.lastOrientationDir=new t.Vector3),this.lastOrientationDir.copy(c)));const g=this.geometry.getAttribute("nodeTangent");for(let e=0;e<this.localHeadGeometry.length;e++){const t=(this.VerticesPerNode*d+e)*Trail.PositionComponentCount,r=l[e];this.billboard?(g.array[t]=c.x,g.array[t+1]=c.y,g.array[t+2]=c.z):(m.array[t]=r.x,m.array[t+1]=r.y,m.array[t+2]=r.z)}if(this.billboard?(this.mesh.frustumCulled=!1,g.needsUpdate=!0,g.addUpdateRange(d*this.VerticesPerNode*Trail.PositionComponentCount,this.VerticesPerNode*Trail.PositionComponentCount)):(m.needsUpdate=!0,m.addUpdateRange(d*this.VerticesPerNode*Trail.PositionComponentCount,this.VerticesPerNode*Trail.PositionComponentCount)),o.makeEmpty(),this.billboard)for(let e=0;e<this.currentLength;e++){const r=(this.currentEnd-e+this.length)%this.length,i=this.nodeCenters[r];if(i){const e=this.material.uniforms.width?.5*this.material.uniforms.width.value:.5;o.expandByPoint(i.clone().add(new t.Vector3(e,e,e))),o.expandByPoint(i.clone().sub(new t.Vector3(e,e,e)))}}else for(let e=0;e<this.currentLength*this.VerticesPerNode;e++){const t=3*e;h.set(m.array[t],m.array[t+1],m.array[t+2]),o.expandByPoint(h)}this.mesh.visible=!o.isEmpty(),null==this.geometry.boundingBox&&(this.geometry.boundingBox=new t.Box3),this.geometry.boundingBox.copy(o),null==this.geometry.boundingSphere&&(this.geometry.boundingSphere=new t.Sphere),this.geometry.boundingBox.getBoundingSphere(this.geometry.boundingSphere)}}(),this.connectNodes=(()=>{const e={attribute:null,offset:0,count:-1};return(t,r)=>{const i=this.geometry.getIndex();for(let e=0;e<this.localHeadGeometry.length-1;e++){const n=this.VerticesPerNode*t+e,a=this.VerticesPerNode*r+e,s=(t*this.FacesPerNode+e*Trail.FacesPerQuad)*Trail.IndicesPerFace;i.array[s]=n,i.array[s+1]=a,i.array[s+2]=n+1,i.array[s+3]=a,i.array[s+4]=a+1,i.array[s+5]=n+1}return i.needsUpdate=!0,i.clearUpdateRanges(),e.attribute=i,e.offset=t*this.FacesPerNode*Trail.IndicesPerFace,e.count=this.FacesPerNode*Trail.IndicesPerFace,e}})(),this.disconnectNodes=(()=>{const e={attribute:null,offset:0,count:-1};return t=>{const r=this.geometry.getIndex();for(let e=0;e<this.localHeadGeometry.length-1;e++){const i=(t*this.FacesPerNode+e*Trail.FacesPerQuad)*Trail.IndicesPerFace;r.array[i]=0,r.array[i+1]=0,r.array[i+2]=0,r.array[i+3]=0,r.array[i+4]=0,r.array[i+5]=0}return r.needsUpdate=!0,r.clearUpdateRanges(),e.attribute=r,e.offset=t*this.FacesPerNode*Trail.IndicesPerFace,e.count=this.FacesPerNode*Trail.IndicesPerFace,e}})(),this.active=!1,this.orientToMovement=!1,r&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=[],this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=[],this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,r,i,n,a,s,o=!1){this.deactivate(),this.destroyMesh(),this.length=r>0?r+1:0,this.dragTexture=i?1:0,this.targetObject=s,this.billboard=o,this.initializeLocalHeadGeometry(n,a),null!=e.uniforms.width&&(e.uniforms.width.value=n),this.nodeIDs=[],this.nodeCenters=[];for(let e=0;e<this.length;e++)this.nodeIDs[e]=-1,this.nodeCenters[e]=new t.Vector3;this.setAllNodesToCurrentTargetPosition(),this.material=e,this.initializeGeometry(),this.initializeMesh(),this.material.uniforms.dragTexture&&(this.material.uniforms.trailLength.value=0),this.material.uniforms.minID.value=0,this.material.uniforms.maxID.value=0,this.material.uniforms.dragTexture&&(this.material.uniforms.dragTexture.value=this.dragTexture),this.material.uniforms.maxTrailLength&&(this.material.uniforms.maxTrailLength.value=this.length),this.material.uniforms.verticesPerNode&&(this.material.uniforms.verticesPerNode.value=this.VerticesPerNode),this.material.uniforms.textureTileFactor&&(this.material.uniforms.textureTileFactor.value=new t.Vector2(1,1)),this.material.uniforms.scale&&(this.material.uniforms.scale.value=1),this.reset()}initializeLocalHeadGeometry(e,r){if(this.localHeadGeometry=[],r){this.VerticesPerNode=0;for(let e=0;e<r.length&&e<Trail.MaxHeadVertices;e++){const i=r[e];if(i&&i instanceof t.Vector3){const e=new t.Vector3;e.copy(i),this.localHeadGeometry.push(e),this.VerticesPerNode++}}}else{const r=(e||1)/2;this.localHeadGeometry.push(new t.Vector3(-r,0,0)),this.localHeadGeometry.push(new t.Vector3(r,0,0)),this.VerticesPerNode=2}this.FacesPerNode=2*(this.VerticesPerNode-1),this.FaceIndicesPerNode=3*this.FacesPerNode}initializeGeometry(){this.vertexCount=this.length*this.VerticesPerNode,this.faceCount=this.length*this.FacesPerNode;const e=new t.BufferGeometry,r=new Float32Array(this.vertexCount),i=new Float32Array(this.vertexCount*this.VerticesPerNode),n=new Float32Array(this.vertexCount*Trail.PositionComponentCount),a=new Float32Array(this.vertexCount*Trail.PositionComponentCount),s=new Float32Array(this.vertexCount*Trail.UVComponentCount),o=new Uint32Array(this.faceCount*Trail.IndicesPerFace),h=new Float32Array(3*this.vertexCount),l=new t.BufferAttribute(h,3);l.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeTangent",l);const c=new t.BufferAttribute(r,1);c.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeID",c);const d=new t.BufferAttribute(i,1);d.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeVertexID",d);const u=new t.BufferAttribute(a,Trail.PositionComponentCount);u.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeCenter",u);const m=new t.BufferAttribute(n,Trail.PositionComponentCount);m.setUsage(t.DynamicDrawUsage),e.setAttribute("position",m);const g=new t.BufferAttribute(s,Trail.UVComponentCount);g.setUsage(t.DynamicDrawUsage),e.setAttribute("uv",g);const y=new t.BufferAttribute(o,1);y.setUsage(t.DynamicDrawUsage),e.setIndex(y),this.geometry=e}zeroVertices(){const e=this.geometry.getAttribute("position");for(let t=0;t<this.vertexCount;t++){const r=3*t;e.array[r]=0,e.array[r+1]=0,e.array[r+2]=0}e.needsUpdate=!0}zeroIndices(){if(null==this.geometry)throw"Geometry not initialized";const e=this.geometry.getIndex();for(let t=0;t<this.faceCount;t++){const r=3*t;e.array[r]=0,e.array[r+1]=0,e.array[r+2]=0}e.needsUpdate=!0,e.clearUpdateRanges()}formInitialFaces(){this.zeroIndices();const e=this.geometry.getIndex();for(let e=0;e<this.length-1;e++)this.connectNodes(e,e+1);e.needsUpdate=!0,e.clearUpdateRanges()}initializeMesh(){if(null==this.geometry)throw"Geometry not initialized";this.mesh=new t.Mesh(this.geometry,this.material),this.mesh.matrixAutoUpdate=!1,this.mesh.visible=!1}destroyMesh(){this.mesh&&(this.scene.remove(this.mesh),this.mesh=null)}reset(){this.currentLength=0,this.currentEnd=-1,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.currentNodeID=0,this.formInitialFaces(),this.zeroVertices(),this.geometry.setDrawRange(0,0),this.setAllNodesToCurrentTargetPosition(),this.mesh&&(this.mesh.visible=!0)}setAllNodesToCurrentTargetPosition(){if(!this.targetObject)return;const e=new t.Vector3;this.targetObject.getWorldPosition(e);for(let t=0;t<this.length;t++)this.nodeCenters[t].copy(e);if(this.billboard&&this.geometry){const e=this.geometry.getAttribute("nodeTangent"),r=new t.Vector3(1,0,0);this.targetObject.matrixWorld&&(r.applyMatrix4(this.targetObject.matrixWorld),r.normalize());for(let t=0;t<this.vertexCount;t++){const i=3*t;e.array[i]=r.x,e.array[i+1]=r.y,e.array[i+2]=r.z}e.needsUpdate=!0}}updateUniforms(){this.currentLength<this.length?this.material.uniforms.minID.value=0:this.material.uniforms.minID.value=this.currentNodeID-this.length,this.material.uniforms.maxID.value=this.currentNodeID,this.material.uniforms.trailLength&&(this.material.uniforms.trailLength.value=this.currentLength),this.material.uniforms.maxTrailLength&&(this.material.uniforms.maxTrailLength.value=this.length),this.material.uniforms.verticesPerNode&&(this.material.uniforms.verticesPerNode.value=this.VerticesPerNode)}advanceWithPositionAndOrientation(e,t){this.advanceGeometry({position:e,tangent:t},null)}advanceWithTransform(e){this.advanceGeometry(null,e)}currentTime(){return performance.now()/1e3}pause(){this.paused||(this.paused=!0,this.pauseAdvanceUpdateTimeDiff=this.currentTime()-this.lastAdvanceTime)}resume(){this.paused&&(this.paused=!1,this.lastAdvanceTime=this.currentTime()-this.pauseAdvanceUpdateTimeDiff)}update(){if(!this.paused){const e=this.currentTime();this.lastAdvanceTime||(this.lastAdvanceTime=e),e-this.lastAdvanceTime>this.advancePeriod?(this.advance(),this.lastAdvanceTime=e):this.updateHead()}}updateNodeID(e,t){this.nodeIDs[e]=t;const r=this.geometry.getAttribute("nodeID"),i=this.geometry.getAttribute("nodeVertexID");for(let n=0;n<this.VerticesPerNode;n++){const a=e*this.VerticesPerNode+n;r.array[a]=t,i.array[a]=n}r.needsUpdate=!0,i.needsUpdate=!0,r.addUpdateRange(e*this.VerticesPerNode,this.VerticesPerNode),i.addUpdateRange(e*this.VerticesPerNode,this.VerticesPerNode)}updateNodeCenter(e,t){this.lastNodeCenter=this.currentNodeCenter,this.currentNodeCenter=this.nodeCenters[e],this.currentNodeCenter.copy(t);const r=this.geometry.getAttribute("nodeCenter");for(let i=0;i<this.VerticesPerNode;i++){const n=3*(e*this.VerticesPerNode+i);r.array[n]=t.x,r.array[n+1]=t.y,r.array[n+2]=t.z}r.needsUpdate=!0,r.updateRanges=[{start:e*this.VerticesPerNode*Trail.PositionComponentCount,count:this.VerticesPerNode*Trail.PositionComponentCount}]}deactivate(){this.active&&(this.scene.remove(this.mesh),this.active=!1)}activate(){this.active||(this.scene.add(this.mesh),this.active=!0)}static getTrailShaderNodes(e){return{position:e?q:_,color:z,fraction:B}}static applyTrailShaderParameters(e){e.transparent=!0,e.alphaTest=.5,e.blending=t.CustomBlending,e.blendSrc=t.SrcAlphaFactor,e.blendDst=t.OneMinusSrcAlphaFactor,e.blendEquation=t.AddEquation,e.depthTest=!0,e.depthWrite=!1,e.side=t.DoubleSide}static createBaseMaterial(t,i,n,a=!1){let{position:o}=Trail.getTrailShaderNodes(a),h=s(I,U,B).rgba;if(null!=t){let r=trailUV;null!=i&&(r=r.add(x(e.elapsed.multiply(-i),0)));const a=u(t).sample(r);let s=h.a;switch(n??"red"){case"none":break;case"red":s=s.multiply(a.r);break;case"alpha":s=s.multiply(a.a)}h=y(h.rgb.multiply(a.rgb),s)}const l=new r({position:o,color:h});return Trail.applyTrailShaderParameters(l),l}static get MaxHeadVertices(){return 128}static get LocalOrientationTangent(){return Trail._LocalOrientationTangent}static get LocalHeadOrigin(){return Trail._LocalHeadOrigin}static get PositionComponentCount(){return 3}static get UVComponentCount(){return 2}static get IndicesPerFace(){return 3}static get FacesPerQuad(){return 2}}Trail._LocalOrientationTangent=new t.Vector3(1,0,0),Trail._LocalHeadOrigin=new t.Vector3(0,0,0),Trail.Shader={get BaseVertexVars(){return["attribute float nodeID;","attribute float nodeVertexID;","attribute vec3 nodeCenter;","uniform float minID;","uniform float maxID;","uniform float trailLength;","uniform float maxTrailLength;","uniform float verticesPerNode;","uniform vec2 textureTileFactor;","uniform bool taper;","uniform vec4 headColor;","uniform vec4 tailColor;","varying vec4 vColor;"].join("\n")},get TexturedVertexVars(){return[this.BaseVertexVars,"varying vec2 vUV;","uniform float dragTexture;"].join("\n")},BaseFragmentVars:["varying vec4 vColor;","uniform sampler2D trailTexture;"].join("\n"),get TexturedFragmentVars(){return[this.BaseFragmentVars,"varying vec2 vUV;"].join("\n")},get VertexShaderCore(){return["float fraction = (maxID - nodeID) / (maxID - minID);","float fractionSize = taper ? fraction : 0.0;","vColor = (1.0 - fraction) * headColor + fraction * tailColor;","vec4 realPosition = vec4((1.0 - fractionSize) * position.xyz + fractionSize * nodeCenter.xyz, 1.0); "].join("\n")},get BaseVertexShader(){return[this.BaseVertexVars,"void main() { ",this.VertexShaderCore,"gl_Position = projectionMatrix * viewMatrix * realPosition;","}"].join("\n")},get BaseFragmentShader(){return[this.BaseFragmentVars,"void main() { ","gl_FragColor = vColor;","}"].join("\n")},get TexturedVertexShader(){return[this.TexturedVertexVars,"void main() { ",this.VertexShaderCore,"float s = 0.0;","float t = 0.0;","if (dragTexture == 1.0) { "," s = fraction * textureTileFactor.s; "," t = (nodeVertexID / verticesPerNode) * textureTileFactor.t;","} else { "," s = nodeID / maxTrailLength * textureTileFactor.s;"," t = (nodeVertexID / verticesPerNode) * textureTileFactor.t;","}","vUV = vec2(s, t); ","gl_Position = projectionMatrix * viewMatrix * realPosition;","}"].join("\n")},get TexturedFragmentShader(){return[this.TexturedFragmentVars,"void main() { ","vec4 textureColor = texture2D(trailTexture, vUV);","gl_FragColor = vColor * textureColor;","}"].join("\n")}};/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1 +1 @@
1
- {"version":3,"file":"vfx-renderers.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/vfx-renderers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAQ,QAAQ,EAA4B,MAAM,gBAAgB,CAAA;AACvG,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,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EAAU,IAAI,EAAE,cAAc;IAGxF,OAAO;IAIP,cAAc;IAUd,OAAO,CAAC,MAAM,CAA0B;IAExC,OAAO,CAAC,YAAY;IAWpB,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,GAAG;QAAC,IAAI,CAAC,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAC;IAsElF,gBAAgB,CAAC,QAAQ,KAAA;IA0CzB,cAAc,CAAC,QAAQ,KAAA;CAiBxB;AAgDD;;;;;GAKG;AACH,iBAAS,2BAA2B,CAAC,IAAI,EAAE,iBAAiB,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAqExF;AAED,OAAO,EAAE,2BAA2B,EAAE,CAAA"}
@@ -1,4 +1,4 @@
1
- import{CustomRenderer as e,MeshRenderer as t,PUID as r}from"@hology/nebula";import*as a from"three";import{InstancedBufferAttribute as o,Object3D as i}from"three";import{NodeShaderMaterial as n}from"three-shader-graph";import{StretchedSprite as s}from"./stretched-sprite.js";import{Trail as l}from"./trail-renderer.js";import{SpriteNodeShaderMaterial as c}from"../../shader/sprite-shader";var d;!function(e){e[e.mesh=0]="mesh",e[e.instanced=1]="instanced",e[e.sprite=2]="sprite",e[e.stretchedBillboard=3]="stretchedBillboard",e[e.trail=4]="trail"}(d||(d={}));export class MultiRenderer extends e{constructor(e,t,r,a){super(),this.worldContainer=e,this.localContainer=t,this.three=r,this.view=a,this.localRenderers=[],this.worldRenderers=[]}onSystemUpdate(){for(const e of this.worldRenderers)e?.onSystemUpdate();for(const e of this.localRenderers)e?.onSystemUpdate()}onParticleCreated(e){e.target=null,this.getRenderer(e)?.onParticleCreated(e)}onParticleUpdate(e){this.getRenderer(e)?.onParticleUpdate(e)}onParticleDead(e){this.getRenderer(e)?.onParticleDead(e),e._renderer=null}getRenderer(e){if(e._renderer)return e._renderer;const t=(null!=e?.parent?e?.parent._space:null)??"world",r="world"===t?this.worldContainer:this.localContainer,o="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==o[d.trail]&&(o[d.trail]=new TrailRenderer(r,this.three)),e._renderer=o[d.trail]):e.body instanceof s?(null==o[d.stretchedBillboard]&&(o[d.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=o[d.stretchedBillboard]):e.body instanceof a.Sprite||e.body instanceof a.Mesh&&"sprite"===e.body.name?(null==o[d.sprite]&&(o[d.sprite]=new CombinedRenderer(r,this.three)),e._renderer=o[d.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof n?(null==o[d.instanced]&&(o[d.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=o[d.instanced]):e.body instanceof a.Object3D?(null==o[d.mesh]&&(o[d.mesh]=new CombinedRenderer(r,this.three)),e._renderer=o[d.mesh]):void 0}dispose(){this.localRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()})),this.worldRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()}))}}export class TrailRenderer extends t{constructor(){super(...arguments),this.trails=[]}dispose(){}onSystemUpdate(){for(const e of this.trails)e.update()}onParticleCreated(e){const t=e.body,r=new l(this.container,!1),o=new i;this.container.add(o);const n=l.createBaseMaterial(t.texture,t.scrollSpeed,t.opacityChannel,t.billboard??!1);n.uniforms.taper.value=t.taper??!1;const s=new a.Color(t.color??0).multiplyScalar(t.intensity),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensityEnd??t.intensity??1);n.uniforms.headColor&&n.uniforms.tailColor&&(n.uniforms.headColor.value=new a.Vector4(s.r,s.g,s.b,t.opacityStart??1),n.uniforms.tailColor.value=new a.Vector4(c.r,c.g,c.b,t.opacityEnd??1)),t.bloom&&(n.userData.hasBloom=!0),r.initialize(n,Math.round(t.length??10),!1,t.width,null,o,t.billboard??!1);const d=e.rotation;o.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=o}onParticleUpdate(e){const t=e.target;t.position.copy(e.position);const r=e.body;let a=x;e.old&&e.old.position?a.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize():a.copy(e.velocity).normalize();const o=w;o.setFromUnitVectors(a,y),t.rotation.set(0,0,0),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.applyQuaternion(o);const i=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=i){const t=this.trails[i];if(e.useAlpha&&t.material.uniforms.headColor&&t.material.uniforms.tailColor){t.material.uniforms.headColor.value.setW(r.opacityStart*e.alpha);t.material.uniforms.tailColor.value.setW(r.opacityEnd*e.alpha)}}}onParticleDead(e){const t=e.target,r=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=r){const e=this.trails[r];e.removeFromParent(),e.mesh.removeFromParent(),e.targetObject.removeFromParent(),t.removeFromParent(),this.trails.splice(r,1)}}}export class CombinedRenderer extends t{dispose(){}scale(e){const t=e.transform.initialScale;e.target instanceof a.Sprite?null!=t?e.target.scale.set(t.x*e.scale*e.radius,t.y*e.scale*e.radius,1):e.target.scale.set(e.scale*e.radius,e.scale*e.radius,1):null!=t?e.target.scale.set(t.x*e.scale,t.y*e.scale,t.z*e.scale):super.scale(e)}rotate(e){e.target.material.rotation=e.rotation.z}onParticleCreated(e){e.target||(e.target=this._targetPool.get(e.body),(e.useAlpha||e.useColor)&&(e.target instanceof a.Mesh||e.target instanceof a.Sprite&&e.target.material instanceof a.Material)&&(e.target.material.__puid=r.id(e.body.material),e.target.material=this._materialPool.get(e.target.material))),e.target&&e.target instanceof i&&(e.target.position.set(e.position.x,e.position.y,e.position.z),this.container.add(e.target))}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:o,rotation:n}=e;if(t){if(t.position.copy(e.position),this.isThreeSprite(e)||(t instanceof a.Mesh&&t.material instanceof c?e.target.material.rotation=e.rotation.z:t.rotation.set(n.x,n.y,n.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof i){const r=m.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(u);a.applyAxisAngle(p,Math.PI/-2),h.setFromUnitVectors(a,r),t.quaternion.copy(h)}t.material instanceof a.Material&&(r&&(t.material instanceof c&&null!=t.material.uniforms.opacity&&(t.material.uniforms.opacity.value=e.alpha,t.material.uniformsNeedUpdate=!0),t.material.opacity=e.alpha,t.material.transparent=!0),o&&(null!=t.material.color?t.material.color.copy(e.color):t.material instanceof a.ShaderMaterial&&null!=t.material.uniforms.color&&(t.material.uniforms.color.value=e.color,t.material.uniformsNeedUpdate=!0)))}}onParticleDead(e){e.target&&(e.target.material&&(e.useAlpha||e.useColor)&&this._materialPool.expire(e.target.material),this._targetPool.expire(e.target),this.container.remove(e.target),e.target=null)}}export class StretchedSpriteInstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.geometry.dispose()))}onSystemUpdate(){for(const e of this.meshes){const t=e.mesh.geometry.getAttribute("offset"),r=e.mesh.geometry.getAttribute("size"),o=e.mesh.geometry.getAttribute("velocity"),i=e.mesh.geometry.getAttribute("rotation"),n=e.mesh.geometry.getAttribute("color");let s=0;for(const l of e.particles){if(null==l||l.dead)continue;if(l.useColor||l.color instanceof a.Color){const e=C.copy(l.color).getRGB(M);n.setXYZW(s,e.r,e.g,e.b,1),n.needsUpdate=!0}l.useAlpha&&(n.setW(s,l.alpha),n.needsUpdate=!0),"number"==typeof l.rotation?i.setX(s,l.rotation):i.setX(s,l.rotation.x);const e=l.position;if(t.setXYZ(s,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(s,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;o.setXYZW(s,m.x*c,m.y*c,m.z*c,d),s++}s>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*s),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*s),r.needsUpdate=!0,n.clearUpdateRanges(),n.addUpdateRange(0,4*s),n.needsUpdate=!0,o.clearUpdateRanges(),o.addUpdateRange(0,4*s),o.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,s),i.needsUpdate=!0)}}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof s&&null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(null==r){const i=this.calcMaxCount(e),n=new a.InstancedBufferGeometry;n.setIndex(t.geometry.getIndex()),n.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&n.setAttribute("normal",t.geometry.getAttribute("normal")),n.setAttribute("uv",t.geometry.getAttribute("uv"));const s=new o(new Float32Array(3*i),3);s.setUsage(a.DynamicDrawUsage),n.setAttribute("offset",s);const l=new o(new Float32Array(4*i),4);if(l.setUsage(a.DynamicDrawUsage),n.setAttribute("color",l),t.material instanceof c){const e=new a.Color(t.material.color);for(let t=0;t<l.count;t++)l.setXYZW(t,e.r,e.g,e.b,1)}const d=new o(new Float32Array(3*i),3);d.setUsage(a.DynamicDrawUsage),n.setAttribute("size",d);const m=new o(new Float32Array(4*i),4);m.setUsage(a.DynamicDrawUsage),n.setAttribute("velocity",m);const u=new o(new Float32Array(4*i),1);u.setUsage(a.DynamicDrawUsage),n.setAttribute("rotation",u),r={mesh:new a.Mesh(n,t.material),indices:new Float32Array(i),particles:[]},this.meshes.push(r),this.container.add(r.mesh)}let i=r.indices.findIndex((e=>0===e));i<0&&(i=function(e){let t=e[0],r=0;for(let a=1;a<e.length;a++)e[a]<t&&(t=e[a],r=a);return r}(r.indices)),r.indices[i]=performance.now(),e.target=i,r.particles[i]=e}}onParticleUpdate(e){}onParticleDead(e){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(r){const t=r.mesh.geometry.getAttribute("size");t.setXYZ(e.target,0,0,0),t.needsUpdate=!0,r.particles[e.target]=null,r.indices[e.target]=0}e.target=null}}const m=new a.Vector3,u=new a.Vector3,h=new a.Quaternion,p=new a.Vector3(1,0,0);export class InstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.dispose()))}onSystemUpdate(){for(const e of this.meshes);}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof a.Sprite)return;const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r){const o=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,o),indices:new Array(o).fill(null),particles:[]},r.mesh.setColorAt(0,C.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="";const i=new Float32Array(3*o);b.makeScale(0,0,0);for(let e=0;e<o;e++)i[3*e+0]=1,i[3*e+1]=1,r.mesh.setMatrixAt(e,b);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(i,3)),this.meshes.push(r),this.container.add(r.mesh)}let o=r.indices.findIndex((e=>null==e));if(o<0&&(o=r.indices.indexOf(Math.min(...r.indices))),r.indices[o]=performance.now(),e.target=o,r.particles[o]=e,"number"==typeof e.target){e.transform.initialScale;const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));f(e,r.mesh),e.useAlpha&&(r.mesh.material.transparent=!0)}}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:a,rotation:o}=e;if(null==t)return;const i=e.body,n=this.meshes.find((e=>e.mesh.geometry.uuid===i.geometry.uuid&&e.mesh.material.uuid===i.material.uuid));if(null==n)return;n.mesh.frustumCulled=!1,f(e,n.mesh),a&&(n.mesh.setColorAt(e.target,C.copy(e.color)),n.mesh.instanceColor.needsUpdate=!0);const s=n.mesh.geometry.getAttribute("particleData");r&&s.setX(e.target,e.alpha),s.setY(e.target,e.energy),s.needsUpdate=!0}onParticleDead(e){if(null!=e.target){const t=e.body,r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r)return;r.indices[e.target]=null,e.scale=0,f(e,r.mesh),r.mesh.instanceMatrix.needsUpdate=!0,e.target=null}}}const g=new i;function f(e,t){if(x.set(e.position.x,e.position.y,e.position.z),e.transform&&e.transform.orientAlongVelocity){const r=m.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize();t.getMatrixAt(e.target,g.matrix);const a=g.getWorldDirection(A);a.applyAxisAngle(p,Math.PI/-2),w.setFromUnitVectors(a,r)}else U.set(e.rotation.x,e.rotation.y,e.rotation.z),w.setFromEuler(U);const r=e.transform.initialScale;null!=r?A.set(r.x*e.scale,r.y*e.scale,r.z*e.scale):A.set(e.scale,e.scale,e.scale),b.compose(x,w,A),t.setMatrixAt(e.target,b),t.instanceMatrix.needsUpdate=!0}const y=new a.Vector3(0,0,-1),b=new a.Matrix4,w=new a.Quaternion,x=new a.Vector3,A=new a.Vector3,U=new a.Euler,C=new a.Color(0),M={r:0,g:0,b:0};function P(e,t){const r=e.mesh,o=r.count,i=[],n=r.geometry.getAttribute("particleData"),s=new a.Vector3;for(let l=0;l<o;l++){const o=new a.Matrix4,c=new a.Color;r.getMatrixAt(l,o),r.getColorAt(l,c);const d=n.getX(l);s.setFromMatrixPosition(o);const m=s.distanceTo(t.position);i.push({index:l,distance:m,matrix:o,particle:e.particles[l],color:c,pdx:d})}i.sort(((e,t)=>t.distance-e.distance));for(let e=0;e<o;e++){const t=i[e].matrix;null==i[e].particle&&t.makeScale(0,0,0),r.setMatrixAt(e,t),r.setColorAt(e,i[e].color),n.setX(e,i[e].pdx)}r.instanceMatrix.needsUpdate=!0}export{P as sortInstancedMeshByDistance};/*
1
+ import{CustomRenderer as e,MeshRenderer as t,PUID as r}from"@hology/nebula";import*as a from"three";import{InstancedBufferAttribute as o,Object3D as i}from"three";import{NodeShaderMaterial as n}from"three-shader-graph";import{StretchedSprite as s}from"./stretched-sprite.js";import{Trail as l}from"./trail-renderer.js";import{SpriteNodeShaderMaterial as c}from"../../shader/sprite-shader";var d;!function(e){e[e.mesh=0]="mesh",e[e.instanced=1]="instanced",e[e.sprite=2]="sprite",e[e.stretchedBillboard=3]="stretchedBillboard",e[e.trail=4]="trail"}(d||(d={}));export class MultiRenderer extends e{constructor(e,t,r,a){super(),this.worldContainer=e,this.localContainer=t,this.three=r,this.view=a,this.localRenderers=[],this.worldRenderers=[]}onSystemUpdate(){for(const e of this.worldRenderers)e?.onSystemUpdate();for(const e of this.localRenderers)e?.onSystemUpdate()}onParticleCreated(e){e.target=null,this.getRenderer(e)?.onParticleCreated(e)}onParticleUpdate(e){this.getRenderer(e)?.onParticleUpdate(e)}onParticleDead(e){this.getRenderer(e)?.onParticleDead(e),e._renderer=null}getRenderer(e){if(e._renderer)return e._renderer;const t=(null!=e?.parent?e?.parent._space:null)??"world",r="world"===t?this.worldContainer:this.localContainer,o="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==o[d.trail]&&(o[d.trail]=new TrailRenderer(r,this.three)),e._renderer=o[d.trail]):e.body instanceof s?(null==o[d.stretchedBillboard]&&(o[d.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=o[d.stretchedBillboard]):e.body instanceof a.Sprite||e.body instanceof a.Mesh&&"sprite"===e.body.name?(null==o[d.sprite]&&(o[d.sprite]=new CombinedRenderer(r,this.three)),e._renderer=o[d.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof n?(null==o[d.instanced]&&(o[d.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=o[d.instanced]):e.body instanceof a.Object3D?(null==o[d.mesh]&&(o[d.mesh]=new CombinedRenderer(r,this.three)),e._renderer=o[d.mesh]):void 0}dispose(){this.localRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()})),this.worldRenderers.forEach((e=>{e instanceof InstancedRenderer&&e.dispose()}))}}export class TrailRenderer extends t{constructor(){super(...arguments),this.trails=[]}dispose(){}onSystemUpdate(){for(const e of this.trails)e.update()}onParticleCreated(e){const t=e.body,r=new l(this.container,!1),o=new i;this.container.add(o),o.updateMatrixWorld(),o.updateWorldMatrix(!0,!0);const n=l.createBaseMaterial(t.texture,t.scrollSpeed,t.opacityChannel,t.billboard??!1);n.uniforms.taper.value=t.taper??!1;const s=new a.Color(t.color??0).multiplyScalar(t.intensity),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensityEnd??t.intensity??1);n.uniforms.headColor&&n.uniforms.tailColor&&(n.uniforms.headColor.value=new a.Vector4(s.r,s.g,s.b,t.opacityStart??1),n.uniforms.tailColor.value=new a.Vector4(c.r,c.g,c.b,t.opacityEnd??1)),t.bloom&&(n.userData.hasBloom=!0),r.initialize(n,Math.round(t.length??10),!1,t.width,null,o,t.billboard??!1);const d=e.rotation;o.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=o}onParticleUpdate(e){const t=e.target;t.position.copy(e.position);const r=e.body;let a=x;e.old&&e.old.position?a.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize():a.copy(e.velocity).normalize();const o=w;o.setFromUnitVectors(a,y),t.rotation.set(0,0,0),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.applyQuaternion(o);const i=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=i){const t=this.trails[i];if(e.useAlpha&&t.material.uniforms.headColor&&t.material.uniforms.tailColor){t.material.uniforms.headColor.value.setW(r.opacityStart*e.alpha);t.material.uniforms.tailColor.value.setW(r.opacityEnd*e.alpha)}}}onParticleDead(e){const t=e.target,r=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=r){const e=this.trails[r];e.removeFromParent(),e.mesh.removeFromParent(),e.targetObject.removeFromParent(),t.removeFromParent(),this.trails.splice(r,1)}}}export class CombinedRenderer extends t{dispose(){}scale(e){const t=e.transform.initialScale;e.target instanceof a.Sprite?null!=t?e.target.scale.set(t.x*e.scale*e.radius,t.y*e.scale*e.radius,1):e.target.scale.set(e.scale*e.radius,e.scale*e.radius,1):null!=t?e.target.scale.set(t.x*e.scale,t.y*e.scale,t.z*e.scale):super.scale(e)}rotate(e){e.target.material.rotation=e.rotation.z}onParticleCreated(e){e.target||(e.target=this._targetPool.get(e.body),(e.useAlpha||e.useColor)&&(e.target instanceof a.Mesh||e.target instanceof a.Sprite&&e.target.material instanceof a.Material)&&(e.target.material.__puid=r.id(e.body.material),e.target.material=this._materialPool.get(e.target.material))),e.target&&e.target instanceof i&&(e.target.position.set(e.position.x,e.position.y,e.position.z),this.container.add(e.target))}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:o,rotation:n}=e;if(t){if(t.position.copy(e.position),this.isThreeSprite(e)||(t instanceof a.Mesh&&t.material instanceof c?e.target.material.rotation=e.rotation.z:t.rotation.set(n.x,n.y,n.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof i){const r=m.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(u);a.applyAxisAngle(p,Math.PI/-2),h.setFromUnitVectors(a,r),t.quaternion.copy(h)}t.material instanceof a.Material&&(r&&(t.material instanceof c&&null!=t.material.uniforms.opacity&&(t.material.uniforms.opacity.value=e.alpha,t.material.uniformsNeedUpdate=!0),t.material.opacity=e.alpha,t.material.transparent=!0),o&&(null!=t.material.color?t.material.color.copy(e.color):t.material instanceof a.ShaderMaterial&&null!=t.material.uniforms.color&&(t.material.uniforms.color.value=e.color,t.material.uniformsNeedUpdate=!0)))}}onParticleDead(e){e.target&&(e.target.material&&(e.useAlpha||e.useColor)&&this._materialPool.expire(e.target.material),this._targetPool.expire(e.target),this.container.remove(e.target),e.target=null)}}export class StretchedSpriteInstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.geometry.dispose()))}onSystemUpdate(){for(const e of this.meshes){const t=e.mesh.geometry.getAttribute("offset"),r=e.mesh.geometry.getAttribute("size"),o=e.mesh.geometry.getAttribute("velocity"),i=e.mesh.geometry.getAttribute("rotation"),n=e.mesh.geometry.getAttribute("color");let s=0;for(const l of e.particles){if(null==l||l.dead)continue;if(l.useColor||l.color instanceof a.Color){const e=C.copy(l.color).getRGB(M);n.setXYZW(s,e.r,e.g,e.b,1),n.needsUpdate=!0}l.useAlpha&&(n.setW(s,l.alpha),n.needsUpdate=!0),"number"==typeof l.rotation?i.setX(s,l.rotation):i.setX(s,l.rotation.x);const e=l.position;if(t.setXYZ(s,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(s,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;o.setXYZW(s,m.x*c,m.y*c,m.z*c,d),s++}s>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*s),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*s),r.needsUpdate=!0,n.clearUpdateRanges(),n.addUpdateRange(0,4*s),n.needsUpdate=!0,o.clearUpdateRanges(),o.addUpdateRange(0,4*s),o.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,s),i.needsUpdate=!0)}}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof s&&null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(null==r){const i=this.calcMaxCount(e),n=new a.InstancedBufferGeometry;n.setIndex(t.geometry.getIndex()),n.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&n.setAttribute("normal",t.geometry.getAttribute("normal")),n.setAttribute("uv",t.geometry.getAttribute("uv"));const s=new o(new Float32Array(3*i),3);s.setUsage(a.DynamicDrawUsage),n.setAttribute("offset",s);const l=new o(new Float32Array(4*i),4);if(l.setUsage(a.DynamicDrawUsage),n.setAttribute("color",l),t.material instanceof c){const e=new a.Color(t.material.color);for(let t=0;t<l.count;t++)l.setXYZW(t,e.r,e.g,e.b,1)}const d=new o(new Float32Array(3*i),3);d.setUsage(a.DynamicDrawUsage),n.setAttribute("size",d);const m=new o(new Float32Array(4*i),4);m.setUsage(a.DynamicDrawUsage),n.setAttribute("velocity",m);const u=new o(new Float32Array(4*i),1);u.setUsage(a.DynamicDrawUsage),n.setAttribute("rotation",u),r={mesh:new a.Mesh(n,t.material),indices:new Float32Array(i),particles:[]},this.meshes.push(r),this.container.add(r.mesh)}let i=r.indices.findIndex((e=>0===e));i<0&&(i=function(e){let t=e[0],r=0;for(let a=1;a<e.length;a++)e[a]<t&&(t=e[a],r=a);return r}(r.indices)),r.indices[i]=performance.now(),e.target=i,r.particles[i]=e}}onParticleUpdate(e){}onParticleDead(e){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(r){const t=r.mesh.geometry.getAttribute("size");t.setXYZ(e.target,0,0,0),t.needsUpdate=!0,r.particles[e.target]=null,r.indices[e.target]=0}e.target=null}}const m=new a.Vector3,u=new a.Vector3,h=new a.Quaternion,p=new a.Vector3(1,0,0);export class InstancedRenderer extends t{constructor(e,t,r){super(e,t),this.view=r,this.meshes=[]}dispose(){this.meshes.forEach((e=>e.mesh.dispose()))}onSystemUpdate(){for(const e of this.meshes);}calcMaxCount(e){if(null==e)return 1;const t=e.parent.rate;return Math.min(t.numPan.b*Math.ceil(e.life/Math.min(Math.max(t.timePan.a,.01),1)),1e5)*this.calcMaxCount(e.parent.parentParticle)}onParticleCreated(e){if(e.body instanceof a.Sprite)return;const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r){const o=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,o),indices:new Array(o).fill(null),particles:[]},r.mesh.setColorAt(0,C.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="";const i=new Float32Array(3*o);b.makeScale(0,0,0);for(let e=0;e<o;e++)i[3*e+0]=1,i[3*e+1]=1,r.mesh.setMatrixAt(e,b);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(i,3)),this.meshes.push(r),this.container.add(r.mesh)}let o=r.indices.findIndex((e=>null==e));if(o<0&&(o=r.indices.indexOf(Math.min(...r.indices))),r.indices[o]=performance.now(),e.target=o,r.particles[o]=e,"number"==typeof e.target){e.transform.initialScale;const t=e.body;let r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));f(e,r.mesh),e.useAlpha&&(r.mesh.material.transparent=!0)}}onParticleUpdate(e){const{target:t,useAlpha:r,useColor:a,rotation:o}=e;if(null==t)return;const i=e.body,n=this.meshes.find((e=>e.mesh.geometry.uuid===i.geometry.uuid&&e.mesh.material.uuid===i.material.uuid));if(null==n)return;n.mesh.frustumCulled=!1,f(e,n.mesh),a&&(n.mesh.setColorAt(e.target,C.copy(e.color)),n.mesh.instanceColor.needsUpdate=!0);const s=n.mesh.geometry.getAttribute("particleData");r&&s.setX(e.target,e.alpha),s.setY(e.target,e.energy),s.needsUpdate=!0}onParticleDead(e){if(null!=e.target){const t=e.body,r=this.meshes.find((e=>e.mesh.geometry.uuid===t.geometry.uuid&&e.mesh.material.uuid===t.material.uuid));if(null==r)return;r.indices[e.target]=null,e.scale=0,f(e,r.mesh),r.mesh.instanceMatrix.needsUpdate=!0,e.target=null}}}const g=new i;function f(e,t){if(x.set(e.position.x,e.position.y,e.position.z),e.transform&&e.transform.orientAlongVelocity){const r=m.set(e.position.x-e.old.position.x,e.position.y-e.old.position.y,e.position.z-e.old.position.z).normalize();t.getMatrixAt(e.target,g.matrix);const a=g.getWorldDirection(A);a.applyAxisAngle(p,Math.PI/-2),w.setFromUnitVectors(a,r)}else U.set(e.rotation.x,e.rotation.y,e.rotation.z),w.setFromEuler(U);const r=e.transform.initialScale;null!=r?A.set(r.x*e.scale,r.y*e.scale,r.z*e.scale):A.set(e.scale,e.scale,e.scale),b.compose(x,w,A),t.setMatrixAt(e.target,b),t.instanceMatrix.needsUpdate=!0}const y=new a.Vector3(0,0,-1),b=new a.Matrix4,w=new a.Quaternion,x=new a.Vector3,A=new a.Vector3,U=new a.Euler,C=new a.Color(0),M={r:0,g:0,b:0};function P(e,t){const r=e.mesh,o=r.count,i=[],n=r.geometry.getAttribute("particleData"),s=new a.Vector3;for(let l=0;l<o;l++){const o=new a.Matrix4,c=new a.Color;r.getMatrixAt(l,o),r.getColorAt(l,c);const d=n.getX(l);s.setFromMatrixPosition(o);const m=s.distanceTo(t.position);i.push({index:l,distance:m,matrix:o,particle:e.particles[l],color:c,pdx:d})}i.sort(((e,t)=>t.distance-e.distance));for(let e=0;e<o;e++){const t=i[e].matrix;null==i[e].particle&&t.makeScale(0,0,0),r.setMatrixAt(e,t),r.setColorAt(e,i[e].color),n.setX(e,i[e].pdx)}r.instanceMatrix.needsUpdate=!0}export{P as sortInstancedMeshByDistance};/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -32,7 +32,7 @@ export declare abstract class BaseActor {
32
32
  onLateUpdate(deltaTime: number): void;
33
33
  constructor();
34
34
  attach<T extends ActorComponent>(type: Constructable<T>, props?: ComponentAttachProps<T>): T;
35
- getComponent<T extends ActorComponent>(type: Constructable<T>): T;
35
+ getComponent<T extends ActorComponent>(type: Constructable<T>): T | undefined;
36
36
  }
37
37
  export declare function _setupActorUpdateEventHandlers(): void;
38
38
  //# sourceMappingURL=actor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"actor.d.ts","sourceRoot":"","sources":["../../../src/gameplay/actors/actor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAa,MAAM,MAAM,CAAA;AACzC,OAAO,EAAE,QAAQ,EAAS,MAAM,OAAO,CAAA;AACvC,OAAkB,EAAE,aAAa,EAAW,MAAM,QAAQ,CAAA;AAC1D,OAAO,EAAE,cAAc,EAAU,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AAO7E,wBAAgB,KAAK,KAEF,sBAAiB,UAMnC;AAED,MAAM,MAAM,OAAO,GAAG,MAAM,CAAA;AAE5B;;GAEG;AACH,8BAAsB,SAAS;IAC7B,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAY;IAIzB,eAAe,UAAQ;IAE9B,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAc;IACvC,QAAQ,CAAC,QAAQ,gBAAsB;IACvC,IACI,QAAQ,4BAEX;IACD,IACI,UAAU,+BAEb;IACD,IACI,QAAQ,0BAEX;IACD,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,GAAC,IAAI;IAC5B,WAAW,IAAI,IAAI;IACnB,SAAS,IAAI,IAAI;IACjB;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IACjC;;;;OAIG;IACH,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;;IAYrC,MAAM,CAAC,CAAC,SAAS,cAAc,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAAG,CAAC;IAiC5F,YAAY,CAAC,CAAC,SAAS,cAAc,EAAE,IAAI,EAAE,aAAa,CAAC,CAA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QACH,OAAO,EAAE,OAAO,CAAA;KACjB,CAAC;IACF,SAAS,CAAC,EAAE,OAAO,CAAC;QAClB,eAAe,EAAE,MAAM,CAAC;QACxB,aAAa,EAAE,MAAM,CAAC;QACtB,OAAO,EAAE;YACP,OAAO,CAAC,EAAE,OAAO,CAAA;YACjB,UAAU,CAAC,EAAE,OAAO,CAAA;SACrB,CAAA;KACF,CAAC,CAAA;CACH,CAAA;AAED,wBAAgB,YAAY,CAAC,MAAM,EACjC,SAAS,EAAE,SAAS,CAAC,MAAM,CAAC,EAC5B,MAAM,EAAE,kBAAkB,GACzB,aAAa,CAAC,MAAM,CAAC,CAmJvB;AAGD,8BAAsB,YAAY;IAChC,OAAO,IAAI,IAAI,GAAC,OAAO,CAAC,IAAI,CAAC;IAC7B,UAAU,IAAI,IAAI,GAAC,OAAO,CAAC,IAAI,CAAC;CACjC;AAID,wBAAgB,iBAAiB,SAEhC;AAED;;;;;;GAMG;AAEH,0BAAkB,mBAAmB;IACnC,UAAU,IAAI;IACd,OAAO,IAAI;IACX,OAAO,KAAK;CACb;AAED,qBAAa,aAAa,CAAC,MAAM,GAAG,OAAO;IAYvC,OAAO,CAAC,iBAAiB;IAXpB,MAAM,EAAE,mBAAmB,CAAiC;IAC5D,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,UAAU,UAAQ;IAClB,eAAe,EAAE,UAAU,CAAC,IAAI,CAAC,CAAsB;IAC9D,OAAO,CAAC,SAAS,CAA2B;IAC5C;;OAEG;IACH,SAAgB,KAAK,mBAA8D;gBAGzE,iBAAiB,EAAE,iBAAiB;IAE9C,QAAQ,IAAI,KAAK;IAIjB,UAAU,CAAC,CAAC,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC;IAI/C;;OAEG;IACH,QAAQ;CAyBT"}
@@ -1,4 +1,4 @@
1
- import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as n}from"./actors/factory.js";import{World as s}from"./services/world.js";import{SceneMaterializer as r}from"../scene/materializer.js";import{ViewController as o}from"./services/render.js";import{RenderingView as i}from"../rendering.js";import{PhysicsSystem as a}from"./services/physics/physics-system.js";import{MeshComponent as c}from"./actors/builtin/components/mesh-component.js";import{activeContainerInstance as m}from"./actors/internal/container-map.js";import{InputService as d}from"./input/index.js";import{RuntimeAssetsService as l}from"../scene/runtime-asset-service.js";import{AssetResourceLoader as p}from"../scene/asset-resource-loader.js";import{AssetLoader as h}from"./services/asset-loader.js";import{polyfillClient as u}from"./polyfill.js";import{Subject as f}from"rxjs";import{PointerEvents as w}from"./services/pointer-events.js";import{RuntimeBundledBackendService as g}from"../scene/runtime-bundled-backend-service.js";import{Scene as j}from"three";import{ShaderProvider as v}from"./services/shader-provider.js";import{SceneDataService as S}from"../scene/scene-data-service.js";export function initiateGame(d,f){if(u(),0!=f.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(o);const y=e.of("default"),I=new HologyRuntime(y),x=new n(y,{inEditor:!1});var b;e.set(n,x),b=f.element,Object.assign(b.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"});const D=new i(f.element,{enableXR:!0===f.xr?.enabled,maxPixelRatio:f.rendering?.maxPixelRatio});D.renderer.shadowMap.enabled=f.rendering?.shadows?.enabled??!0,D.renderer.shadowMap.autoUpdate=f.rendering?.shadows?.autoUpdate??!0,null!=f?.rendering?.resolutionScale&&(D.resolutionScale=f.rendering.resolutionScale),e.set(i,D);const R=new o(D);e.set(o,R);const G=new g,z=new l(G),H=new p;H.setDataDir(f.dataDir),H.initKtx2(D.renderer);const O=Object.entries(f.shaders).map((([e,t])=>({name:e,type:t}))),P=Object.entries(f.actors).map((([e,t])=>({name:e,type:t}))),W=new v(O);e.set(v,W);const A=new h(H,z,O);e.set(h,A);const M=new j,N=new r(M,new S,z,H,D,O,P,x);e.set(r,N);const U=e.get(s);return e.set(s,U),U.materializer=N,(async()=>{const n=e.get(a);if(n.scene=U.scene,await n.start(),I.isShutdown)return;if(await G.preloadData(),I.isShutdown)return;U.scene=M;const{scene:s,actors:r}=await t(D,f.sceneName,f.dataDir,f.shaders,f.actors,x,G,z,H);U.scene=s;for(const e of M.children)U.scene.add(e);if(I.isShutdown)return void D.stop();e.import([c]);for(const e of r)U.addActor(e);n.addFromScene(s),D.loop((e=>{})),I.status=5,m.value=y,y.remove(d),y.set({id:d,type:d});const o=y.get(d);m.value=null,I.gameInstance=o,y.get(w).start(),o instanceof GameInstance&&o.onStart(),I._resolver(!0)})(),I}export class GameInstance{onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(e){this.containerInstance=e,this.status=0,this.isShutdown=!1,this.shutdownStarted=new f,this.ready=new Promise((e=>{this._resolver=e}))}getWorld(){return this.containerInstance.get(s)}getService(e){return this.containerInstance.get(e)}shutdown(){this.isShutdown=!0,this.shutdownStarted.next(),this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(d).stop();const e=this.containerInstance.get(i);e?.stop();for(const e of this.getWorld().actors)this.getWorld().removeActor(e);this.containerInstance.get(a).stop(),this.containerInstance.get(r).dispose(),this.containerInstance.get(w).stop(),this.containerInstance.reset()}}/*
1
+ import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as n}from"./actors/factory.js";import{World as s}from"./services/world.js";import{SceneMaterializer as r}from"../scene/materializer.js";import{ViewController as o}from"./services/render.js";import{RenderingView as i}from"../rendering.js";import{PhysicsSystem as a}from"./services/physics/physics-system.js";import{MeshComponent as c}from"./actors/builtin/components/mesh-component.js";import{activeContainerInstance as m}from"./actors/internal/container-map.js";import{InputService as d}from"./input/index.js";import{RuntimeAssetsService as l}from"../scene/runtime-asset-service.js";import{AssetResourceLoader as p}from"../scene/asset-resource-loader.js";import{AssetLoader as h}from"./services/asset-loader.js";import{polyfillClient as u}from"./polyfill.js";import{Subject as f}from"rxjs";import{PointerEvents as w}from"./services/pointer-events.js";import{RuntimeBundledBackendService as g}from"../scene/runtime-bundled-backend-service.js";import{Scene as j}from"three";import{ShaderProvider as v}from"./services/shader-provider.js";import{SceneDataService as S}from"../scene/scene-data-service.js";export function initiateGame(d,f){if(u(),0!=f.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(o);const y=e.of("default"),I=new HologyRuntime(y),x=new n(y,{inEditor:!1});var b;e.set(n,x),b=f.element,Object.assign(b.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"});const D=new i(f.element,{enableXR:!0===f.xr?.enabled,maxPixelRatio:f.rendering?.maxPixelRatio});D.renderer.shadowMap.enabled=f.rendering?.shadows?.enabled??!0,D.renderer.shadowMap.autoUpdate=f.rendering?.shadows?.autoUpdate??!0,null!=f?.rendering?.resolutionScale&&(D.resolutionScale=f.rendering.resolutionScale),e.set(i,D);const R=new o(D);e.set(o,R);const G=new g,z=new l(G),H=new p;H.setDataDir(f.dataDir),H.initKtx2(D.renderer);const O=Object.entries(f.shaders).map((([e,t])=>({name:e,type:t}))),P=Object.entries(f.actors).map((([e,t])=>({name:e,type:t}))),W=new v(O);e.set(v,W);const A=new h(H,z,O);e.set(h,A);const M=new j,N=new r(M,new S,z,H,D,O,P,x);e.set(r,N);const U=e.get(s);return e.set(s,U),U.materializer=N,(async()=>{const n=e.get(a);if(await n.start(),I.isShutdown)return;if(await G.preloadData(),I.isShutdown)return;U.scene=M;const{scene:s,actors:r}=await t(D,f.sceneName,f.dataDir,f.shaders,f.actors,x,G,z,H);U.scene=s,n.scene=U.scene;for(const e of M.children)U.scene.add(e);if(I.isShutdown)return void D.stop();e.import([c]);for(const e of r)U.addActor(e);n.addFromScene(s),D.loop((e=>{})),I.status=5,m.value=y,y.remove(d),y.set({id:d,type:d});const o=y.get(d);m.value=null,I.gameInstance=o,y.get(w).start(),o instanceof GameInstance&&o.onStart(),I._resolver(!0)})(),I}export class GameInstance{onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(e){this.containerInstance=e,this.status=0,this.isShutdown=!1,this.shutdownStarted=new f,this.ready=new Promise((e=>{this._resolver=e}))}getWorld(){return this.containerInstance.get(s)}getService(e){return this.containerInstance.get(e)}shutdown(){this.isShutdown=!0,this.shutdownStarted.next(),this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(d).stop();const e=this.containerInstance.get(i);e?.stop();for(const e of this.getWorld().actors)this.getWorld().removeActor(e);this.containerInstance.get(a).stop(),this.containerInstance.get(r).dispose(),this.containerInstance.get(w).stop(),this.containerInstance.reset()}}/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -186,14 +186,6 @@ export declare abstract class AbstractPhysicsSystem {
186
186
  * Updates the transform of an actor's physics body to match its visual representation
187
187
  */
188
188
  abstract updateActorTransform(actor: BaseActor): void;
189
- /**
190
- * Gets the contact points between an actor and other objects in a specific direction
191
- */
192
- abstract getActorContacts(actor: BaseActor, direction: Vector3): {
193
- ri: Vector3;
194
- rj: Vector3;
195
- ni: Vector3;
196
- }[];
197
189
  /**
198
190
  * Stops the physics simulation and cleans up resources
199
191
  */
@@ -1 +1 @@
1
- {"version":3,"file":"abstract-physics-system.d.ts","sourceRoot":"","sources":["../../../../src/gameplay/services/physics/abstract-physics-system.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAA;AAC1C,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAClD,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAA;AAEnD,MAAM,MAAM,mBAAmB,GAAG;IAChC,SAAS,EAAE,O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,EACP,KAAK,EAAE,CAAC,GACP,UAAU,CAAC,CAAC,CAAC;IAEhB;;OAEG;aACa,oBAAoB,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EAC3E,IAAI,EAAE,CAAC,EACP,KAAK,EAAE,CAAC,GACP,UAAU,CAAC,CAAC,CAAC;IAEhB;;OAEG;aACa,wBAAwB,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EAC/E,IAAI,EAAE,CAAC,EACP,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,GACzB,UAAU,CAAC,CAAC,CAAC;IAEhB;;OAEG;aACa,oBAAoB,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAE5D;;OAEG;aACa,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,GAAG;QACtE,EAAE,EAAE,OAAO,CAAC;QACZ,EAAE,EAAE,OAAO,CAAC;QACZ,EAAE,EAAE,OAAO,CAAA;KACZ,EAAE;IAEH;;OAEG;aACa,IAAI,IAAI,IAAI;CAC7B"}
1
+ {"version":3,"file":"abstract-physics-system.d.ts","sourceRoot":"","sources":["../../../../src/gameplay/services/physics/abstract-physics-system.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAA;AAC1C,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAClD,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAA;AAEnD,MAAM,MAAM,mBAAmB,GAAG;IAChC,SAAS,EAAE,OAAO,CAAA;IAClB,IAAI,EAAE,MAAM,CAAA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,CAAC,CAAC;IAEhB;;OAEG;aACa,oBAAoB,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EAC3E,IAAI,EAAE,CAAC,EACP,KAAK,EAAE,CAAC,GACP,UAAU,CAAC,CAAC,CAAC;IAEhB;;OAEG;aACa,wBAAwB,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EAC/E,IAAI,EAAE,CAAC,EACP,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,GACzB,UAAU,CAAC,CAAC,CAAC;IAEhB;;OAEG;aACa,oBAAoB,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAE5D;;OAEG;aACa,IAAI,IAAI,IAAI;CAC7B"}
@@ -1,13 +1,31 @@
1
1
  import * as RAPIER from "@dimforge/rapier3d-compat";
2
2
  import { Observable, Subject } from "rxjs";
3
3
  import * as THREE from "three";
4
- import { ColorRepresentation, Object3D, Vector3 } from "three";
4
+ import { ColorRepresentation, Object3D, Quaternion, Vector3 } from "three";
5
5
  import { CollisionShape } from '../../../index.js';
6
6
  import { AbstractType } from '../../../utils/type.js';
7
7
  import { BaseActor } from '../../actors/actor.js';
8
8
  import { ViewController } from '../render.js';
9
9
  import { AbstractPhysicsSystem, ActorPhysicsOptions } from './abstract-physics-system.js';
10
10
  export { Component, ActorComponent, type ComponentOptions, attach, Attach } from '../../actors/component.js';
11
+ /**
12
+ * Pairwise filtering using bit masks.
13
+ *
14
+ * This filtering method is based on two 16-bit values:
15
+ * - The interaction groups (the 16 left-most bits of `self.0`).
16
+ * - The interaction mask (the 16 right-most bits of `self.0`).
17
+ *
18
+ * An interaction is allowed between two filters `a` and `b` two conditions
19
+ * are met simultaneously:
20
+ * - The interaction groups of `a` has at least one bit set to `1` in common with the interaction mask of `b`.
21
+ * - The interaction groups of `b` has at least one bit set to `1` in common with the interaction mask of `a`.
22
+ * In other words, interactions are allowed between two filter iff. the following condition is met:
23
+ *
24
+ * ```
25
+ * ((a >> 16) & b) != 0 && ((b >> 16) & a) != 0
26
+ * ```
27
+ */
28
+ export type InteractionGroups = number;
11
29
  export declare class RayTestResult {
12
30
  actor?: BaseActor;
13
31
  hasHit: boolean;
@@ -18,10 +36,25 @@ export declare class RayTestResult {
18
36
  interface RayTestOptions {
19
37
  debugColor?: ColorRepresentation;
20
38
  debugLifetime?: number;
21
- collisionFilter?: number;
39
+ collisionFilter?: InteractionGroups;
22
40
  excludeActor?: BaseActor;
23
41
  excludeTriggers?: boolean;
24
42
  }
43
+ export declare class ShapeCastResult {
44
+ static shared: ShapeCastResult;
45
+ actor?: BaseActor;
46
+ hasHit: boolean;
47
+ distance: number;
48
+ /**
49
+ * The world-space contact point at the point of impact.
50
+ */
51
+ hitPoint: Vector3;
52
+ /**
53
+ * The world-space normal of the collider hit at the point of impact.
54
+ */
55
+ normal: Vector3;
56
+ reset(): void;
57
+ }
25
58
  export declare enum PhysicsBodyType {
26
59
  dynamic = 1,
27
60
  static = 2,
@@ -52,6 +85,8 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
52
85
  constructor(viewController: ViewController);
53
86
  private shapeCacheBox;
54
87
  private shapeCacheBall;
88
+ private getBallShape;
89
+ private getBoxShape;
55
90
  /**
56
91
  * Check if there is any objects in the physics world currently that
57
92
  * intersects with this box.
@@ -215,6 +250,40 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
215
250
  * @param factor - The damping factor to apply
216
251
  */
217
252
  setAngularDamping(actor: BaseActor, factor: number): void;
253
+ /**
254
+ * Set the position of the actor's phsyics body. This acts as a teleport
255
+ * and should be used with caution. For kinematic and dynamic bodies,
256
+ * you normally want to control their transform with velocities or forces
257
+ * as opposed to updating their position directly. However, if you have locked
258
+ * translations or rotations, then you may have good reason to do it.
259
+ * @param actor The actor's whose physical position to update
260
+ * @param position The new position in world space
261
+ */
262
+ setPosition(actor: BaseActor, position: Vector3): void;
263
+ /**
264
+ * Retrieve the position of an actor's physics body.
265
+ * This is normally synchronized to the actor's position automatically after the physics simulation.
266
+ * @param actor The actor whose physical rotation to get
267
+ * @param target A target vector to write the result into to avoid creating new objects
268
+ */
269
+ getPosition(actor: BaseActor, target?: Vector3): void;
270
+ /**
271
+ * Set the rotation of the actor's phsyics body. This acts as a teleport
272
+ * and should be used with caution. For kinematic and dynamic bodies,
273
+ * you normally want to control their transform with velocities or forces
274
+ * as opposed to updating their position directly. However, if you have locked
275
+ * translations or rotations, then you may have good reason to do it.
276
+ * @param actor The actor's whose physical rotation to update
277
+ * @param position The new rotation in world space
278
+ */
279
+ setRotation(actor: BaseActor, rotation: Quaternion): void;
280
+ /**
281
+ * Retrieve the rotation of an actor's physics body.
282
+ * This is normally synchronized to the actor's rotation automatically after the physics simulation.
283
+ * @param actor The actor whose physical rotation to get
284
+ * @param target A target quaternion to write the result into to avoid creating new objects
285
+ */
286
+ getRotation(actor: BaseActor, target?: Quaternion): void;
218
287
  /**
219
288
  * Locks or unlocks the ability of this rigid-body to translate.
220
289
  *
@@ -405,6 +474,7 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
405
474
  /**
406
475
  * Updates the transform of an actor's physics body to match its visual representation.
407
476
  * @param actor - The actor to update
477
+ * @deprecated The transform is now automatically being updated for all actors
408
478
  */
409
479
  updateActorTransform(actor: BaseActor): void;
410
480
  /**
@@ -413,16 +483,34 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
413
483
  */
414
484
  private setupWorld;
415
485
  /**
416
- * Gets the contact points between an actor and other objects in a specific direction.
417
- * @param actor - The actor to check contacts for
418
- * @param direction - The direction to check in
419
- * @returns Array of contact points with position and normal information
420
- */
421
- getActorContacts(actor: BaseActor, direction: Vector3): {
422
- ri: Vector3;
423
- rj: Vector3;
424
- ni: Vector3;
425
- }[];
486
+ * Performs a sphere cast (swept sphere collision test) in the physics world.
487
+ * This method checks if a sphere, starting at a given position and with a given radius,
488
+ * would intersect with any colliders in the physics world when moved along the given direction
489
+ * up to the specified distance.
490
+ *
491
+ * @param position - The starting position of the sphere (THREE.Vector3)
492
+ * @param radius - The radius of the sphere
493
+ * @param direction - The direction vector along which to cast the sphere (THREE.Vector3)
494
+ * @param distance - The maximum distance to cast the sphere
495
+ * @param result - Optional. A ShapeCastResult object to store the result. If not provided, a shared instance is used.
496
+ * @param collisionFilter - Optional. An interaction group filter to restrict which objects are considered for collision.
497
+ * @returns The ShapeCastResult containing hit information if a collision occurred, or indicating no hit otherwise.
498
+ */
499
+ sphereCast(position: Vector3, radius: number, direction: Vector3, distance: number, result?: ShapeCastResult, collisionFilter?: InteractionGroups): ShapeCastResult;
500
+ /**
501
+ * Performs a shape cast (swept collision test) for the given actor in a specified direction and distance.
502
+ * This method checks if the actor's collider(s) would intersect with any other colliders in the physics world
503
+ * when moved along the given direction up to the specified distance. The result contains information about
504
+ * the first hit, including contact points, normals, and the hit actor.
505
+ *
506
+ * @param actor - The actor whose shape will be cast through the world.
507
+ * @param direction - The direction vector along which to cast the shape.
508
+ * @param distance - The maximum distance to cast the shape.
509
+ * @param result - Optional. A ShapeCastResult object to store the result. If not provided, a shared instance is used.
510
+ * @param collisionFilter - Optional. An interaction group filter to restrict which objects are considered for collision.
511
+ * @returns The ShapeCastResult containing hit information if a collision occurred, or indicating no hit otherwise.
512
+ */
513
+ castActorShape(actor: BaseActor, direction: Vector3, distance: number, result?: ShapeCastResult, collisionFilter?: InteractionGroups): ShapeCastResult;
426
514
  /**
427
515
  * Stops the physics simulation and cleans up resources.
428
516
  */
@@ -1 +1 @@
1
- {"version":3,"file":"physics-system.d.ts","sourceRoot":"","sources":["../../../../src/gameplay/services/physics/physics-system.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,2BAA2B,CAAA;AAEnD,OAAO,EAAgE,UAAU,EAAE,OAAO,EAA2B,MAAM,MAAM,CAAA;AACjI,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAGL,mBAAmB,EAE6C,QAAQ,EAIxE,OAAO,EACR,MAAM,OAAO,CAAA;AAGd,OAAO,E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E,KAAK,CAAC,eAAe,GAAG,KAAK,CAAC,0BAA0B,GAC7D,YAAY,CAcd"}
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as e}from"tslib";import*as s from"@dimforge/rapier3d-compat";import{QueryFilterFlags as i}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as c,takeUntil as l}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as y,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as x,Scene as B,Vector3 as v}from"three";import{Service as b}from"typedi";import{AssetMeshInstance as C}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as A,CapsuleCollisionShape as D,CollisionShapeSource as M,ConeCollisionShape as z,ConvexPolyhedronCollisionShape as S,CylinderCollisionShape as R,PhysicalShapeMesh as T,PlaneCollisionShape as E,SphereCollisionShape as F,TrimeshCollisionShape as W}from"../../../index.js";import{LandscapeGroup as j}from"../../../scene/landscape/landscape.js";import{ViewController as V}from"../render.js";import{World as _}from"../world.js";import*as I from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as P}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as k}from"./abstract-physics-system.js";import{ActorComponent as L,Component as O}from"../../../gameplay/actors/component.js";import{inject as N}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new v,this.hitNormal=new v}}export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const G=new v,q=new v,Q=new w;let U=class extends k{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(t){super(),this.viewController=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new c,this.beforeStep=new c,this.afterStep=new c,this.shouldRenderDebug=!1,this.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new v,this._raytestDirection=new v,this.controlledActors=new Set,this.ready=this.setup()}hasBoxIntersection(t){const e=t.getCenter(G),i=t.getSize(q),o=i.x+1e6*i.y+1e12*i.z;if(!this.shapeCacheBox.has(o)){const t=new s.Cuboid(i.x/2,i.y/2,i.z/2);this.shapeCacheBox.set(o,t)}const n=this.shapeCacheBox.get(o);return null!=this.world.intersectionWithShape(e,Q,n)}hasSphereIntersection(t){const e=t.radius;if(!this.shapeCacheBox.has(e)){const i=new s.Ball(t.radius);this.shapeCacheBall.set(e,i)}const i=this.shapeCacheBall.get(e);return null!=this.world.intersectionWithShape(t.center,Q,i)}createDebugMesh(){return new g(new y,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.ready}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene.add(this.debugMesh));const t=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(t.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await et(),this.eventQueue=new s.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;var s,i;null!=e&&(e.parent instanceof B&&(it(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&(s=e.quaternion,i=t.rotation(),s.x=i.x,s.y=i.y,s.z=i.z,s.w=i.w),e.updateMatrix(),e.updateWorldMatrix(!1,!1)))})),this.afterStep.next(t)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((t,e,s)=>{this.collisionEvents.next({handle1:t,handle2:e,started:s}),this.collisionEvents.next({handle1:e,handle2:t,started:s})}))}rayTestFromCamera(t,e,s){this._raycaster.setFromCamera(tt,this.viewController.getCamera());const i=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(i);return this.rayTest(i,o,e,s)}rayTest(t,e,s,i){null==s&&(s=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),s;st(lt.origin,t),st(lt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(lt,r,!1,void 0,void 0,void 0,null!=i?.excludeActor?this.actorBodies.get(i.excludeActor.id):void 0,i?.excludeTriggers?t=>!t.isSensor():void 0);if(s.hasHit=null!=a,s.hasHit){const e=lt.pointAt(a.timeOfImpact);s._internal=a,it(s.hitNormal,a.normal),it(s.hitPoint,e),s.distance=nt.subVectors(s.hitPoint,t).length();const i=this.world.bodies.getAll().find((t=>function(t,e){for(let s=0,i=t.numColliders();s<i;s++){const i=t.collider(s);if(e(i))return i}}(t,(t=>t===a.collider))));s.actor=null!=i?this.bodyActors.get(i):null}if(this.showDebug){const e=new h(n,t,r,i?.debugColor??255);this.scene.add(e),setTimeout((()=>this.scene.remove(e)),i?.debugLifetime??200)}return s}setGravity(t,e,s){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=s}getGravity(){return Y.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())ot(t,(t=>t.setActiveEvents(s.ActiveEvents.COLLISION_EVENTS)))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof T&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof C&&!1!==t.userData?.src?.collisionDetection)if(t.children[0]&&t.children[0].instanceMatrix)this.createForInstancedMesh(t.children[0],t.collisionShapes);else{const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else t instanceof j?this.addLandscapeGroup(t):(t instanceof p||t instanceof B)&&t.children.forEach((t=>this.addRecursively(t)))}createForInstancedMesh(t,e){const s=new m,i=e.filter((t=>null!=t)).map((t=>t.source===M.rendered?t.withOffset(ht):t));for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),s.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(s);this.createStaticBody(o,i)}}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,s,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,s,i.EXCLUDE_SENSORS,o,at);const a=e.computedMovement();return it(rt,a),rt}setNextKinematicTranslation(t,e){const s=this.actorBodies.get(t.id),i=s.translation();i.x+=e.x,i.y+=e.y,i.z+=e.z,s?.setNextKinematicTranslation(i)}setAngularVelocity(t,e){const s=this.actorBodies.get(t.id);Z.x=e.x,Z.y=e.y,Z.z=e.z,s?.setAngvel(Z,!0)}setLinearVelocity(t,e){const s=this.actorBodies.get(t.id);Z.x=e.x,Z.y=e.y,Z.z=e.z,s?.setLinvel(Z,!0)}getLinearVelocity(t,e=new v){const s=this.actorBodies.get(t.id).linvel();return e.x=s.x,e.y=s.y,e.z=s.z,e}getAngularVelocity(t,e=new v){const s=this.actorBodies.get(t.id).angvel();return e.x=s.x,e.y=s.y,e.z=s.z,e}setLinearDamping(t,e){const s=this.actorBodies.get(t.id);s?.setLinearDamping(e)}setAngularDamping(t,e){const s=this.actorBodies.get(t.id);s?.setAngularDamping(e)}lockTranslations(t,e){const s=this.actorBodies.get(t.id);s?.lockTranslations(e,!1)}lockRotations(t,e){const s=this.actorBodies.get(t.id);s?.lockRotations(e,!1)}setEnabledTranslations(t,e,s,i){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,s,i,!1)}setEnabledRotations(t,e,s,i){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,s,i,!1)}addLandscapeGroup(t){const e=t.userData.src,i=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new v);if(e.landscape.holes&&e.landscape.holes.some((t=>t.m===n.name&&0!==t.w[0]))){const t=n.geometry.clone(),i=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=i.x,a[t+1]*=i.y,a[t+2]*=i.z;const c=t.index;for(let t=0;t<c.count;t+=3){const e=r.getX(c.getX(t)),s=r.getX(c.getY(t)),i=r.getX(c.getZ(t));(e>.5||s>.5||i>.5)&&(c.setX(t,0),c.setY(t,0),c.setZ(t,0))}const l=s.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(s.RigidBodyDesc.fixed()),e=new s.Vector3(0,0,0);st(e,o),t.setTranslation(e,!1),this.world.createCollider(l,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const c=i.find((t=>t.x===n.x&&t.y==n.y));if(null!=c)for(const e of c.points){if(null==a[e.i%t])continue;const s=t-1-Math.floor(e.i/t);s in a[e.i%t]?a[e.i%t][s]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:s,heightMap:c})}const l=e.landscape.options.density,d=a.flatMap((t=>t.reverse())),h=s.ColliderDesc.heightfield(l,l,new Float32Array(d),new s.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(s.RigidBodyDesc.fixed()),e=new s.Vector3(0,0,0);st(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const s=this.actorBodies.get(t.id);s?.setEnabled(e)}addActor(t,e,i={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const o=t.object;let n;switch(i.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=s.RigidBodyDesc.dynamic(),n.mass=i.mass??1;break;case PhysicsBodyType.kinematic:n=s.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=s.RigidBodyDesc.kinematicVelocityBased();break;default:n=i.isTrigger?s.RigidBodyDesc.kinematicVelocityBased():s.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==i.continousCollisionDetection);for(const t of e)this.addShape(r,t,o);ot(r,(t=>{null!=i.isTrigger&&(t.setSensor(i.isTrigger),t.setActiveCollisionTypes(s.ActiveCollisionTypes.ALL),t.setActiveEvents(s.ActiveEvents.COLLISION_EVENTS)),null!=i.friction&&t.setFriction(i.friction),null!=i.density&&t.setDensity(i.density),null!=i.mass&&t.setMass(i.mass),null!=i.restitution&&t.setRestitution(i.restitution)})),K(r,o),!0===i.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t)}applyTorque(t,e){const s=this.actorBodies.get(t.id);Z.x=e.x,Z.y=e.y,Z.z=e.z,s?.addTorque(Z,!0)}applyTorqueImpulse(t,e){const s=this.actorBodies.get(t.id);Z.x=e.x,Z.y=e.y,Z.z=e.z,s?.applyTorqueImpulse(Z,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const s=this.actorBodies.get(t.id);Z.x=e.x,Z.y=e.y,Z.z=e.z,s?.addForce(Z,!0)}applyImpulse(t,e){const s=this.actorBodies.get(t.id);Z.x=e.x,Z.y=e.y,Z.z=e.z,s?.applyImpulse(Z,!0)}applyLocalForce(t,e,s){const i=this.actorBodies.get(t.id);st(Z,e),null==s?i?.addForce(Z,!0):(st(J,s),i?.addForceAtPoint(Z,J,!0))}applyLocalImpulse(t,e,s){const i=this.actorBodies.get(t.id);st(Z,e),null==s?i.applyImpulse(Z,!0):(st(J,s),i.applyImpulseAtPoint(Z,J,!0))}applyRadiusImpulse(t,e,i){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==s.RigidBodyType.Dynamic)return;const n=$;it(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(i);Z.x=a.x,Z.y=a.y,Z.z=a.z,o.applyImpulse(Z,!0)}))}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){if(null==t)return;const e=new Set;t.traverse((t=>{e.add(t.uuid)}));for(const[t,s]of this.staticBodies.entries())!e.has(t.uuid)&&this.world.getRigidBody(s.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(s))}removeSceneObject(t){if(t instanceof j){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,s){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((({started:t})=>t===s)),a((({handle1:t,handle2:e,started:s})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:s}))),r((({a1:s,a2:i})=>null!=s&&null!=i&&s.id===t.id&&e(s,i))),a((({a2:t})=>t)))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>t.started)),r((({handle1:e})=>{const s=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=s&&s.id===t.id})),a((t=>t.handle2)))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>!t.started)),r((({handle1:e})=>{const s=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=s&&s.id===t.id})),a((t=>t.handle2)))}onHasContactChanged(t){const e=new Set,s=new o(!1);return this.onBeginContact(t).subscribe((t=>{e.add(t),s.next(e.size>0)})),this.onEndContact(t).subscribe((t=>{e.delete(t),s.next(e.size>0)})),s.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>s instanceof e),!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>s instanceof e),!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>e.id===s.id),!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>e.id===s.id),!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e?K(e,t.object):console.warn("Actor has not been added to physics world",t)}setupWorld(){const t=new s.World({x:0,y:-9.81,z:0});this.world=t}getActorContacts(t,e){const i=this.actorBodies.get(t.id);if(i&&i.numColliders()>0){const o=i.collider(0);let n=o.shape,r=o.translation(),a=o.rotation(),c=e,l=.3;const d=this.world.castShape(r,a,c,n,.1,l,!0,null,null,null,this.actorBodies.get(t.id),(t=>t.shape.type!=s.ShapeType.HeightField));if(null!=d){const t=new v,e=new v,s=new v;return it(t,d.witness2),it(e,d.witness1),it(s,d.normal1),s.negate(),[{ri:t,rj:e,ni:s}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world?.bodies.forEach((t=>this.world.removeRigidBody(t))),this.world?.free(),this.fixedupdateSub?.unsubscribe()}createStaticBody(t,e,i){const o=i?.type===PhysicsBodyType.dynamic?s.RigidBodyDesc.dynamic():s.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const s of e){if(null==s){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,s,t);null!=i?.friction&&o.setFriction(i.friction),null!=i?.density&&o.setDensity(i.density),null!=i?.mass&&o.setMass(i.mass/e.length),null!=i?.restitution&&o.setRestitution(i.restitution)}return K(n,t),n.userData=t.uuid,n}addShape(t,e,i){const o=i.getWorldScale(ct),n=this.createShape(e,o);null!=e.collisionGroup&&n.setCollisionGroups(e.collisionGroup),n.friction=e.friction??.1,null!=e.restitution&&(n.restitution=e.restitution),null!=e.density&&(n.density=e.density,n.massPropsMode=s.MassPropsMode.Density),null!=e.mass&&(n.mass=e.mass,n.massPropsMode=s.MassPropsMode.Mass);const r=e.offset.clone().multiply(o);st(n.translation,r);const a=(new w).setFromEuler(e.rotation);var c,l;e instanceof S&&e.mesh instanceof d.Mesh&&a.multiply(e.mesh.getWorldQuaternion(X)),c=n.rotation,l=a,c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w;return this.world.createCollider(n,t)}createShape(t,e){if(t instanceof A)return s.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof D){return s.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof W){const i=null!=t.geometry.getIndex()?t.geometry:I.mergeVertices(t.geometry),o=extractFloat32Array(i.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return s.ColliderDesc.trimesh(o,new Uint32Array(i.getIndex().array))}if(t instanceof S){let i;t.mesh instanceof d.Mesh?i=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?i=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(i.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=P(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return s.ColliderDesc.convexHull(n)}if(t instanceof F){const i=2*e.x-e.y-e.z;return Math.abs(i)>.01?this.createShape(new S(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new v(1,1,1)):s.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof R?s.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof z?s.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof E?s.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),s.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new s.CharacterCollision}};U=t([b(),e("design:paramtypes",[V])],U);export{U as PhysicsSystem};const H=new v,X=new d.Quaternion;function K(t,e){const i=e.getWorldPosition(H),o=e.getWorldQuaternion(X);t.setTranslation(new s.Vector3(i.x,i.y,i.z),!1),t.setRotation(new s.Quaternion(o.x,o.y,o.z,o.w),!1)}const Y=new v,Z=new s.Vector3(0,0,0),J=new s.Vector3(0,0,0),$=new v,tt=new d.Vector2,et=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function st(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function it(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function ot(t,e){for(let s=0,i=t.numColliders();s<i;s++){e(t.collider(s))}}const nt=new v,rt=new v,at=t=>!t.isSensor(),ct=new v;const lt=new s.Ray(new s.Vector3(0,0,0),new s.Vector3(0,1,0));let dt=class extends L{constructor(){super(...arguments),this._active=!0,this.physics=N(U),this.world=N(_)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};dt=t([O()],dt);export function extractFloat32Array(t){const e=t.itemSize,s=t.count,i=new Float32Array(s*e);for(let o=0;o<s;o++)for(let s=0;s<e;s++)i[o*e+s]=t.getComponent(o,s);return i}const ht=new v;/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import*as s from"@dimforge/rapier3d-compat";import{QueryFilterFlags as i}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as c,takeUntil as l}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as u,BufferGeometry as p,Group as y,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as x,Scene as B,Vector3 as v}from"three";import{Service as b}from"typedi";import{AssetMeshInstance as C}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as A,CapsuleCollisionShape as S,CollisionShapeSource as z,ConeCollisionShape as D,ConvexPolyhedronCollisionShape as R,CylinderCollisionShape as M,PhysicalShapeMesh as T,PlaneCollisionShape as E,SphereCollisionShape as P,TrimeshCollisionShape as _}from"../../../index.js";import{LandscapeGroup as F}from"../../../scene/landscape/landscape.js";import{ViewController as W}from"../render.js";import{World as j}from"../world.js";import*as I from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as V}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as k}from"./abstract-physics-system.js";import{ActorComponent as L,Component as O}from"../../../gameplay/actors/component.js";import{inject as N}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new v,this.hitNormal=new v}}export class ShapeCastResult{constructor(){this.hasHit=!1,this.hitPoint=new v,this.normal=new v}reset(){this.actor=void 0,this.hasHit=!1,this.distance=0,this.hitPoint.set(0,0,0),this.normal.set(0,0,0)}}ShapeCastResult.shared=new ShapeCastResult;export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const G=new v,H=new v,q=new w,Q=new w,U=(new w,[]);let X=class extends k{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(t){super(),this.viewController=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new c,this.beforeStep=new c,this.afterStep=new c,this.shouldRenderDebug=!1,this.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new v,this._raytestDirection=new v,this.controlledActors=new Set,this.ready=this.setup()}getBallShape(t){let e=this.shapeCacheBall.get(t);return null==e&&(e=new s.Ball(t),this.shapeCacheBall.set(t,e)),e}getBoxShape(t,e,i){const o=t+1e6*e+1e12*i;let n=this.shapeCacheBox.get(o);return null==n&&(n=new s.Cuboid(t,e,i),this.shapeCacheBox.set(o,n)),n}hasBoxIntersection(t){const e=t.getCenter(G),s=t.getSize(H),i=this.getBoxShape(s.x/2,s.y/2,s.z/2);return null!=this.world.intersectionWithShape(e,q,i)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,q,e)}createDebugMesh(){return new g(new p,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.ready}renderDebug(){if(null==this.scene)return;null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene?.add(this.debugMesh));const t=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(t.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await nt(),this.eventQueue=new s.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;null!=e&&e.parent instanceof B&&(ct(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&lt(e.quaternion,t.rotation()),e.updateMatrix(),e.updateWorldMatrix(!1,!1))})),this.afterStep.next(t)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((t,e,s)=>{this.collisionEvents.next({handle1:t,handle2:e,started:s}),this.collisionEvents.next({handle1:e,handle2:t,started:s})}))}rayTestFromCamera(t,e,s){this._raycaster.setFromCamera(st,this.viewController.getCamera());const i=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(i);return this.rayTest(i,o,e,s)}rayTest(t,e,s,i){null==s&&(s=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),s;rt(gt.origin,t),rt(gt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(gt,r,!1,void 0,i.collisionFilter,void 0,null!=i?.excludeActor?this.actorBodies.get(i.excludeActor.id):void 0,i?.excludeTriggers?t=>!t.isSensor():void 0);if(s.hasHit=null!=a,s.hasHit){const e=gt.pointAt(a.timeOfImpact);s._internal=a,ct(s.hitNormal,a.normal),ct(s.hitPoint,e),s.distance=ht.subVectors(s.hitPoint,t).length();const i=this.world.bodies.getAll().find((t=>function(t,e){for(let s=0,i=t.numColliders();s<i;s++){const i=t.collider(s);if(e(i))return i}}(t,(t=>t===a.collider))));s.actor=null!=i?this.bodyActors.get(i):null}if(this.showDebug){let e;U.length>0?(e=U.pop(),e.setDirection(n),e.position.copy(t),e.setLength(r,.2,.1),e.setColor(i?.debugColor??255)):e=new h(n,t,r,i?.debugColor??255),this.scene?.add(e),setTimeout((()=>{this.scene?.remove(e),U.push(e)}),i?.debugLifetime??200)}return s}setGravity(t,e,s){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=s}getGravity(){return J.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())dt(t,(t=>t.setActiveEvents(s.ActiveEvents.COLLISION_EVENTS)))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof T&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof C&&!1!==t.userData?.src?.collisionDetection)if(t.children[0]&&t.children[0].instanceMatrix)this.createForInstancedMesh(t.children[0],t.collisionShapes);else{const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else t instanceof F?this.addLandscapeGroup(t):(t instanceof y||t instanceof B)&&t.children.forEach((t=>this.addRecursively(t)))}createForInstancedMesh(t,e){const s=new m,i=e.filter((t=>null!=t)).map((t=>t.source===z.rendered?t.withOffset(ft):t));for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),s.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(s);this.createStaticBody(o,i)}}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,s,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,s,i.EXCLUDE_SENSORS,o,pt);const a=e.computedMovement();return ct(ut,a),ut}setNextKinematicTranslation(t,e){const s=this.actorBodies.get(t.id),i=s.translation();i.x+=e.x,i.y+=e.y,i.z+=e.z,s?.setNextKinematicTranslation(i)}setAngularVelocity(t,e){const s=this.actorBodies.get(t.id);$.x=e.x,$.y=e.y,$.z=e.z,s?.setAngvel($,!0)}setLinearVelocity(t,e){const s=this.actorBodies.get(t.id);$.x=e.x,$.y=e.y,$.z=e.z,s?.setLinvel($,!0)}getLinearVelocity(t,e=new v){const s=this.actorBodies.get(t.id).linvel();return e.x=s.x,e.y=s.y,e.z=s.z,e}getAngularVelocity(t,e=new v){const s=this.actorBodies.get(t.id).angvel();return e.x=s.x,e.y=s.y,e.z=s.z,e}setLinearDamping(t,e){const s=this.actorBodies.get(t.id);s?.setLinearDamping(e)}setAngularDamping(t,e){const s=this.actorBodies.get(t.id);s?.setAngularDamping(e)}setPosition(t,e){const s=this.actorBodies.get(t.id);s?.setTranslation(it(e),!1)}getPosition(t,e=new v){const s=this.actorBodies.get(t.id);s&&ct(e,s.translation())}setRotation(t,e){const s=this.actorBodies.get(t.id);s?.setTranslation(ot(e),!1)}getRotation(t,e=new w){const s=this.actorBodies.get(t.id);s&&lt(e,s.rotation())}lockTranslations(t,e){const s=this.actorBodies.get(t.id);s?.lockTranslations(e,!1)}lockRotations(t,e){const s=this.actorBodies.get(t.id);s?.lockRotations(e,!1)}setEnabledTranslations(t,e,s,i){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,s,i,!1)}setEnabledRotations(t,e,s,i){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,s,i,!1)}addLandscapeGroup(t){const e=t.userData.src,i=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new v);if(e.landscape.holes&&e.landscape.holes.some((t=>t.m===n.name&&0!==t.w[0]))){const t=n.geometry.clone(),i=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=i.x,a[t+1]*=i.y,a[t+2]*=i.z;const c=t.index;for(let t=0;t<c.count;t+=3){const e=r.getX(c.getX(t)),s=r.getX(c.getY(t)),i=r.getX(c.getZ(t));(e>.5||s>.5||i>.5)&&(c.setX(t,0),c.setY(t,0),c.setZ(t,0))}const l=s.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(s.RigidBodyDesc.fixed()),e=new s.Vector3(0,0,0);rt(e,o),t.setTranslation(e,!1),this.world.createCollider(l,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const c=i.find((t=>t.x===n.x&&t.y==n.y));if(null!=c)for(const e of c.points){if(null==a[e.i%t])continue;const s=t-1-Math.floor(e.i/t);s in a[e.i%t]?a[e.i%t][s]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:s,heightMap:c})}const l=e.landscape.options.density,d=a.flatMap((t=>t.reverse())),h=s.ColliderDesc.heightfield(l,l,new Float32Array(d),new s.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(s.RigidBodyDesc.fixed()),e=new s.Vector3(0,0,0);rt(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const s=this.actorBodies.get(t.id);s?.setEnabled(e)}addActor(t,e,i={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const o=t.object;let n;switch(i.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=s.RigidBodyDesc.dynamic(),n.mass=i.mass??1;break;case PhysicsBodyType.kinematic:n=s.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=s.RigidBodyDesc.kinematicVelocityBased();break;default:n=i.isTrigger?s.RigidBodyDesc.kinematicVelocityBased():s.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==i.continousCollisionDetection);for(const t of e)this.addShape(r,t,o);dt(r,(t=>{null!=i.isTrigger&&(t.setSensor(i.isTrigger),t.setActiveCollisionTypes(s.ActiveCollisionTypes.ALL),t.setActiveEvents(s.ActiveEvents.COLLISION_EVENTS)),null!=i.friction&&t.setFriction(i.friction),null!=i.density&&t.setDensity(i.density),null!=i.mass&&t.setMass(i.mass),null!=i.restitution&&t.setRestitution(i.restitution)})),Z(r,o),!0===i.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t)}applyTorque(t,e){const s=this.actorBodies.get(t.id);$.x=e.x,$.y=e.y,$.z=e.z,s?.addTorque($,!0)}applyTorqueImpulse(t,e){const s=this.actorBodies.get(t.id);$.x=e.x,$.y=e.y,$.z=e.z,s?.applyTorqueImpulse($,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const s=this.actorBodies.get(t.id);$.x=e.x,$.y=e.y,$.z=e.z,s?.addForce($,!0)}applyImpulse(t,e){const s=this.actorBodies.get(t.id);$.x=e.x,$.y=e.y,$.z=e.z,s?.applyImpulse($,!0)}applyLocalForce(t,e,s){const i=this.actorBodies.get(t.id);rt($,e),null==s?i?.addForce($,!0):(rt(tt,s),i?.addForceAtPoint($,tt,!0))}applyLocalImpulse(t,e,s){const i=this.actorBodies.get(t.id);rt($,e),null==s?i.applyImpulse($,!0):(rt(tt,s),i.applyImpulseAtPoint($,tt,!0))}applyRadiusImpulse(t,e,i){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==s.RigidBodyType.Dynamic)return;const n=et;ct(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(i);$.x=a.x,$.y=a.y,$.z=a.z,o.applyImpulse($,!0)}))}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){if(null==t)return;const e=new Set;t.traverse((t=>{e.add(t.uuid)}));for(const[t,s]of this.staticBodies.entries())!e.has(t.uuid)&&this.world.getRigidBody(s.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(s))}removeSceneObject(t){if(t instanceof F){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,s){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((({started:t})=>t===s)),a((({handle1:t,handle2:e,started:s})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:s}))),r((({a1:s,a2:i})=>null!=s&&null!=i&&s.id===t.id&&e(s,i))),a((({a2:t})=>t)))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>t.started)),r((({handle1:e})=>{const s=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=s&&s.id===t.id})),a((t=>t.handle2)))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(l(t.disposed),r((t=>!t.started)),r((({handle1:e})=>{const s=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=s&&s.id===t.id})),a((t=>t.handle2)))}onHasContactChanged(t){const e=new Set,s=new o(!1);return this.onBeginContact(t).subscribe((t=>{e.add(t),s.next(e.size>0)})),this.onEndContact(t).subscribe((t=>{e.delete(t),s.next(e.size>0)})),s.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>s instanceof e),!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>s instanceof e),!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>e.id===s.id),!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,((t,s)=>e.id===s.id),!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e?Z(e,t.object):console.warn("Actor has not been added to physics world",t)}setupWorld(){const t=new s.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,s,i,o=ShapeCastResult.shared,n=void 0){o.reset();const r=this.getBallShape(e);this.shapeCacheBall.get;const a={x:t.x,y:t.y,z:t.z},c={x:s.x,y:s.y,z:s.z},l=this.world.castShape(a,{x:0,y:0,z:0,w:1},c,r,.01,i,!0,null,n,null,void 0,void 0);if(null!=l){ct(o.hitPoint,l.witness1),o.normal.set(l.normal1.x,l.normal1.y,l.normal1.z),o.distance=l.time_of_impact,o.hasHit=!0;const t=l.collider.parent();if(t){const e=this.bodyActors.get(t);e&&(o.actor=e)}}return o}castActorShape(t,e,s,i=ShapeCastResult.shared,o=void 0){i.reset();const n=this.actorBodies.get(t.id);if(n&&n.numColliders()>0){for(let t=0;t<n.numColliders();t++){const r=n.collider(t);let a=r.shape,c=r.translation(),l=r.rotation(),d=e,h=s;const u=this.world.castShape(c,l,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=u){u.collider;const t=r;return ct(i.hitPoint,u.witness1),wt(t.rotation(),u.normal1,i.normal,Q),i.distance=u.time_of_impact,i.actor=this.bodyActors.get(u.collider.parent()),i.hasHit=!0,i}}return i}return console.warn("Actor is not added to the physics system"),i}stop(){this.world?.bodies.forEach((t=>this.world.removeRigidBody(t))),this.world?.free(),this.fixedupdateSub?.unsubscribe(),U.length=0}createStaticBody(t,e,i){const o=i?.type===PhysicsBodyType.dynamic?s.RigidBodyDesc.dynamic():s.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const s of e){if(null==s){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,s,t);null!=i?.friction&&o.setFriction(i.friction),null!=i?.density&&o.setDensity(i.density),null!=i?.mass&&o.setMass(i.mass/e.length),null!=i?.restitution&&o.setRestitution(i.restitution)}return Z(n,t),n.userData=t.uuid,n}addShape(t,e,i){const o=i.getWorldScale(yt),n=this.createShape(e,o);null!=e.collisionGroup&&n.setCollisionGroups(e.collisionGroup),n.friction=e.friction??.1,null!=e.restitution&&(n.restitution=e.restitution),null!=e.density&&(n.density=e.density,n.massPropsMode=s.MassPropsMode.Density),null!=e.mass&&(n.mass=e.mass,n.massPropsMode=s.MassPropsMode.Mass);const r=e.offset.clone().multiply(o);rt(n.translation,r);const a=(new w).setFromEuler(e.rotation);e instanceof R&&e.mesh instanceof d.Mesh&&a.multiply(e.mesh.getWorldQuaternion(Y)),at(n.rotation,a);return this.world.createCollider(n,t)}createShape(t,e){if(t instanceof A)return s.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof S){return s.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof _){const i=null!=t.geometry.getIndex()?t.geometry:I.mergeVertices(t.geometry),o=extractFloat32Array(i.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return s.ColliderDesc.trimesh(o,new Uint32Array(i.getIndex().array))}if(t instanceof R){let i;t.mesh instanceof d.Mesh?i=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?i=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(i.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=V(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return s.ColliderDesc.convexHull(n)}if(t instanceof P){const i=2*e.x-e.y-e.z;return Math.abs(i)>.01?this.createShape(new R(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new v(1,1,1)):s.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof M?s.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof D?s.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof E?s.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),s.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new s.CharacterCollision}};X=t([b(),e("design:paramtypes",[W])],X);export{X as PhysicsSystem};const K=new v,Y=new d.Quaternion;function Z(t,e){const s=e.getWorldPosition(K),i=e.getWorldQuaternion(Y);t.setTranslation(it(s),!1),t.setRotation(ot(i),!1)}const J=new v,$=new s.Vector3(0,0,0),tt=new s.Vector3(0,0,0),et=new v,st=new d.Vector2;function it(t){return rt($,t),$}function ot(t){return at(Q,t),Q}const nt=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function rt(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function at(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ct(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function lt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function dt(t,e){for(let s=0,i=t.numColliders();s<i;s++){e(t.collider(s))}}const ht=new v,ut=new v,pt=t=>!t.isSensor(),yt=new v;const gt=new s.Ray(new s.Vector3(0,0,0),new s.Vector3(0,1,0));let mt=class extends L{constructor(){super(...arguments),this._active=!0,this.physics=N(X),this.world=N(j)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};mt=t([O()],mt);export function extractFloat32Array(t){const e=t.itemSize,s=t.count,i=new Float32Array(s*e);for(let o=0;o<s;o++)for(let s=0;s<e;s++)i[o*e+s]=t.getComponent(o,s);return i}const ft=new v;function wt(t,e,s,i){return i.set(t.x,t.y,t.z,t.w),s.set(e.x,e.y,e.z),s.applyQuaternion(i),s}/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */