@hology/core 0.0.101 → 0.0.102

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.
Files changed (32) hide show
  1. package/dist/effects/vfx/trail-renderer.d.ts +2 -1
  2. package/dist/effects/vfx/trail-renderer.d.ts.map +1 -1
  3. package/dist/effects/vfx/trail-renderer.js +1 -1
  4. package/dist/effects/vfx/vfx-actor.d.ts.map +1 -1
  5. package/dist/effects/vfx/vfx-actor.js +1 -1
  6. package/dist/effects/vfx/vfx-asset.d.ts +7 -3
  7. package/dist/effects/vfx/vfx-asset.d.ts.map +1 -1
  8. package/dist/effects/vfx/vfx-asset.js +1 -1
  9. package/dist/effects/vfx/vfx-materializer.d.ts.map +1 -1
  10. package/dist/effects/vfx/vfx-materializer.js +1 -1
  11. package/dist/effects/vfx/vfx-renderers.d.ts +2 -1
  12. package/dist/effects/vfx/vfx-renderers.d.ts.map +1 -1
  13. package/dist/effects/vfx/vfx-renderers.js +1 -1
  14. package/dist/gameplay/initiate.d.ts.map +1 -1
  15. package/dist/gameplay/initiate.js +1 -1
  16. package/dist/gameplay/services/physics/physics-system.d.ts +1 -3
  17. package/dist/gameplay/services/physics/physics-system.d.ts.map +1 -1
  18. package/dist/gameplay/services/physics/physics-system.js +1 -1
  19. package/dist/gameplay/services/world.d.ts +3 -1
  20. package/dist/gameplay/services/world.d.ts.map +1 -1
  21. package/dist/gameplay/services/world.js +1 -1
  22. package/dist/rendering.js +1 -1
  23. package/dist/scene/asset-resource-loader.d.ts +1 -1
  24. package/dist/scene/asset-resource-loader.d.ts.map +1 -1
  25. package/dist/scene/asset-resource-loader.js +1 -1
  26. package/dist/scene/materializer.d.ts.map +1 -1
  27. package/dist/scene/materializer.js +1 -1
  28. package/dist/shader-nodes/index.d.ts +1 -1
  29. package/dist/shader-nodes/index.d.ts.map +1 -1
  30. package/dist/shader-nodes/index.js +1 -1
  31. package/package.json +2 -2
  32. package/tsconfig.tsbuildinfo +1 -1
@@ -1,5 +1,6 @@
1
1
  import * as THREE from "three";
2
2
  import { NodeShaderMaterial } from "three-shader-graph";
3
+ import { OutputTextureSetting } from '../../gameplay';
3
4
  export declare const trailUV: import("three-shader-graph").Vec2Node;
4
5
  export declare const trailDragUV: import("three-shader-graph").Vec2Node;
5
6
  export declare class Trail extends THREE.Object3D {
@@ -74,7 +75,7 @@ export declare class Trail extends THREE.Object3D {
74
75
  fraction: import("three-shader-graph").FloatDivNode;
75
76
  };
76
77
  static applyTrailShaderParameters(nodeShader: THREE.ShaderMaterial): void;
77
- static createBaseMaterial(texture?: THREE.Texture, scrollSpeed?: number): NodeShaderMaterial;
78
+ static createBaseMaterial(texture?: THREE.Texture, scrollSpeed?: number, opacityChannel?: OutputTextureSetting['opacityChannel']): NodeShaderMaterial;
78
79
  static get MaxHeadVertices(): number;
79
80
  static _LocalOrientationTangent: THREE.Vector3;
80
81
  static get LocalOrientationTangent(): THREE.Vector3;
@@ -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,EAAE,kBAAkB,EAAkL,MAAM,oBAAoB,CAAA;AAyBvO,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,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,iBA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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 n,uniformVec2 as a,mix as s,min as o,uniformVec4 as h,attributeFloat as c,attributeVec3 as l,select as d,float as u,textureSampler2d as m,attributes as g,uniforms as p,rgba as y,vec4 as f,varying as x,vec2 as v}from"three-shader-graph";n("trailLength");const T=n("verticesPerNode"),V=n("minID"),P=n("maxID"),C=(n("dragTexture"),n("maxTrailLength")),N=a("textureTileFactor",new t.Vector2(1,1)),D=h("headColor",new t.Vector4),F=h("tailColor",new t.Vector4),I=i("taper",!1),w=(n("scale",1),c("nodeID")),b=c("nodeVertexID"),U=l("nodeCenter"),A=P.subtract(w).divide(P.subtract(V)),L=d(I,A,u(0)),M=x(u(1).subtract(A).multiplyVec4(D).add(A.multiplyVec4(F))),H=f(u(1).subtract(L).multiplyVec3(g.position).add(L.multiplyVec3(U)),1),S=p.projectionMatrix.multiply(p.viewMatrix).multiplyVec(H);export const trailUV=x(v(A.multiply(N.x),b.divide(T).multiply(N.y).multiply(2)));export const trailDragUV=x(v(w.divide(C).multiply(N.x),b.divide(T).multiply(N.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,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,c=[];for(let e=0;e<Trail.MaxHeadVertices;e++){const e=new t.Vector3;c.push(e)}return function(l,d){const u=this.geometry.getAttribute("position");i.set(0,0,0),i.applyMatrix4(d),this.updateNodeCenter(l,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(d)}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,d),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=c[e];t.sub(n),t.applyQuaternion(r),t.add(n)}}for(let e=0;e<this.localHeadGeometry.length;e++){const t=(this.VerticesPerNode*l+e)*Trail.PositionComponentCount,r=c[e];u.array[t]=r.x,u.array[t+1]=r.y,u.array[t+2]=r.z}u.needsUpdate=!0,u.addUpdateRange(l*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(u.array[t],u.array[t+1],u.array[t+2]),o.expandByPoint(h)}this.geometry.boundingBox=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){this.deactivate(),this.destroyMesh(),this.length=r>0?r+1:0,this.dragTexture=i?1:0,this.targetObject=s,this.initializeLocalHeadGeometry(n,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),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 t.BufferAttribute(r,1);h.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeID",h);const c=new t.BufferAttribute(i,1);c.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeVertexID",c);const l=new t.BufferAttribute(a,Trail.PositionComponentCount);l.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeCenter",l);const d=new t.BufferAttribute(n,Trail.PositionComponentCount);d.setUsage(t.DynamicDrawUsage),e.setAttribute("position",d);const u=new t.BufferAttribute(s,Trail.UVComponentCount);u.setUsage(t.DynamicDrawUsage),e.setAttribute("uv",u);const m=new t.BufferAttribute(o,1);m.setUsage(t.DynamicDrawUsage),e.setIndex(m),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 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(){return{position:S,color:M,fraction:A}}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){let{position:n}=Trail.getTrailShaderNodes(),a=s(D,F,A).rgba;if(null!=t){let r=trailUV;null!=i&&(r=r.add(v(e.elapsed.multiply(-i),0)));const n=m(t).sample(r);a=a.multiply(n),a=y(a.rgb,o(n.x,n.a).multiply(a.a))}const h=new r({position:n,color:a});return Trail.applyTrailShaderParameters(h),h}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 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}from"three-shader-graph";a("trailLength");const v=a("verticesPerNode"),T=a("minID"),V=a("maxID"),P=(a("dragTexture"),a("maxTrailLength")),C=n("textureTileFactor",new t.Vector2(1,1)),N=o("headColor",new t.Vector4),D=o("tailColor",new t.Vector4),F=i("taper",!1),w=(a("scale",1),h("nodeID")),I=h("nodeVertexID"),b=c("nodeCenter"),U=V.subtract(w).divide(V.subtract(T)),A=l(F,U,d(0)),L=f(d(1).subtract(U).multiplyVec4(N).add(U.multiplyVec4(D))),M=y(d(1).subtract(A).multiplyVec3(m.position).add(A.multiplyVec3(b)),1),H=g.projectionMatrix.multiply(g.viewMatrix).multiplyVec(M);export const trailUV=f(x(U.multiply(C.x),I.divide(v).multiply(C.y).multiply(2)));export const trailDragUV=f(x(w.divide(P).multiply(C.x),I.divide(v).multiply(C.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)}return function(l,d){const u=this.geometry.getAttribute("position");i.set(0,0,0),i.applyMatrix4(d),this.updateNodeCenter(l,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(d)}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,d),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)}}for(let e=0;e<this.localHeadGeometry.length;e++){const t=(this.VerticesPerNode*l+e)*Trail.PositionComponentCount,r=c[e];u.array[t]=r.x,u.array[t+1]=r.y,u.array[t+2]=r.z}u.needsUpdate=!0,u.addUpdateRange(l*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(u.array[t],u.array[t+1],u.array[t+2]),o.expandByPoint(h)}this.geometry.boundingBox=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){this.deactivate(),this.destroyMesh(),this.length=r>0?r+1:0,this.dragTexture=i?1:0,this.targetObject=s,this.initializeLocalHeadGeometry(a,n),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 t.BufferAttribute(r,1);h.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeID",h);const c=new t.BufferAttribute(i,1);c.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeVertexID",c);const l=new t.BufferAttribute(n,Trail.PositionComponentCount);l.setUsage(t.DynamicDrawUsage),e.setAttribute("nodeCenter",l);const d=new t.BufferAttribute(a,Trail.PositionComponentCount);d.setUsage(t.DynamicDrawUsage),e.setAttribute("position",d);const u=new t.BufferAttribute(s,Trail.UVComponentCount);u.setUsage(t.DynamicDrawUsage),e.setAttribute("uv",u);const m=new t.BufferAttribute(o,1);m.setUsage(t.DynamicDrawUsage),e.setIndex(m),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(){return{position:H,color:L,fraction:U}}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){let{position:n}=Trail.getTrailShaderNodes(),o=s(N,D,U).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=o.a;switch(a??"red"){case"none":break;case"red":s=s.multiply(n.r);break;case"alpha":s=s.multiply(n.a)}o=p(o.rgb.multiply(n.rgb),s)}const h=new r({position:n,color:o});return Trail.applyTrailShaderParameters(h),h}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-actor.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/vfx-actor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAS,SAAS,EAAE,MAAM,gCAAgC,CAAA;AAKjE,OAAO,EAAE,KAAK,EAAqB,MAAM,sBAAsB,CAAA;AAM/D,qBACa,QAAS,SAAQ,SAAS;IAErC;;OAEG;IACI,SAAS,SAAI;IACb,MAAM,UAAQ;IAErB,OAAO,CAAC,MAAM,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;IASJ,KAAK;IAIL,IAAI;IAiBJ,OAAO;IAeP,OAAO,CAAC,SAAS,CAAsB;IACvC,OAAO,CAAC,SAAS,CAAyB;IAC1C,OAAO,CAAC,SAAS,CAAoB;IAErC,OAAO,CAAC,GAAG,CAAK;IAEhB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IA2BjC;;;;;;;;;;OAUG;IAEH,gBAAgB;IAIhB,SAAS,IAAI,IAAI;CAelB"}
@@ -1,4 +1,4 @@
1
- import{__decorate as s}from"tslib";import*as t from"three";import{Rate as e}from"@hology/nebula";import{Actor as i,BaseActor as r}from"../../gameplay/actors/actor.js";import{inject as o}from"../../gameplay/inject.js";import{AssetLoader as a}from"../../gameplay/services/asset-loader.js";import{ViewController as h}from"../../gameplay/services/render.js";import{World as m}from"../../gameplay/services/world.js";import{DelayRate as d}from"./rates.js";import{materializeVfx as l}from"./vfx-materializer.js";import{PhysicsSystem as n}from"../../gameplay/index.js";import{ShaderProvider as p}from"../../gameplay/services/shader-provider.js";let c=class extends r{constructor(){super(...arguments),this.timescale=1,this.paused=!1,this.assetLoader=o(a),this.world=o(m),this.view=o(h),this.physics=o(n),this.shaderProvider=o(p),this._worldPos=new t.Vector3,this._worldRot=new t.Quaternion,this._worldEul=new t.Euler,this.max=0}async fromAsset(s){if("vfx"!==s.type)throw"Asset must be a VFX asset but is "+s.type;null!=this.system&&(this.system.destroy(),this.system.emitters.forEach((s=>s.reset()))),this.sourceAsset=s,this.disposeSystem&&this.disposeSystem(),this.world.scene.add(this.object);const{system:t,dispose:e,container:i}=await l(this.sourceAsset,this.object,{getAsset:s=>this.assetLoader.getAsset(s),getMaterial:s=>this.assetLoader.getMaterialByAssetId(s),getTexture:s=>this.assetLoader.getTextureByAssetId(s),getMesh:s=>this.assetLoader.getModelByAssetId(s).then((s=>s.scene))},this.view,this.physics,this.shaderProvider);this.system=t,this.disposeSystem=e,this.particleSystemContainer=i}play(){this.paused=!1;this.system.emitters.every((s=>s.dead))&&this.restart()}pause(){this.paused=!0}stop(){this.system.emitters.forEach((s=>{const t=s.rate;t instanceof e&&(t.nextTime=1/0)}))}restart(){for(const s of this.system.emitters){const t=s.rate;t instanceof d?t.restart():t.nextTime=0,s.removeAllParticles()}}onUpdate(s){this.paused||(this.object.getWorldPosition(this._worldPos),this.object.getWorldQuaternion(this._worldRot),this._worldEul.setFromQuaternion(this._worldRot),this.system?.emitters.forEach((s=>{"world"===s._space&&(s.setPosition(this._worldPos),s.setRotation(this._worldEul))})),this.system?.update(s*this.timescale))}getParticleCount(){return this.system?.getCount()??0}onEndPlay(){this.stop(),null!=this.disposeSystem&&this.disposeSystem()}};c=s([i()],c);export{c as VfxActor};/*
1
+ import{__decorate as s}from"tslib";import*as t from"three";import{Rate as e}from"@hology/nebula";import{Actor as i,BaseActor as r}from"../../gameplay/actors/actor.js";import{inject as o}from"../../gameplay/inject.js";import{AssetLoader as a}from"../../gameplay/services/asset-loader.js";import{ViewController as h}from"../../gameplay/services/render.js";import{World as m}from"../../gameplay/services/world.js";import{DelayRate as l}from"./rates.js";import{materializeVfx as d}from"./vfx-materializer.js";import{PhysicsSystem as n}from"../../gameplay/index.js";import{ShaderProvider as p}from"../../gameplay/services/shader-provider.js";let y=class extends r{constructor(){super(...arguments),this.timescale=1,this.paused=!1,this.assetLoader=o(a),this.world=o(m),this.view=o(h),this.physics=o(n),this.shaderProvider=o(p),this._worldPos=new t.Vector3,this._worldRot=new t.Quaternion,this._worldEul=new t.Euler,this.max=0}async fromAsset(s){if("vfx"!==s.type)throw"Asset must be a VFX asset but is "+s.type;null!=this.system&&(this.system.destroy(),this.system.emitters.forEach((s=>s.reset()))),this.sourceAsset=s,this.disposeSystem&&this.disposeSystem(),this.world.scene.add(this.object);const{system:t,dispose:e,container:i}=await d(this.sourceAsset,this.object,{getAsset:s=>this.assetLoader.getAsset(s),getMaterial:s=>this.assetLoader.getMaterialByAssetId(s),getTexture:s=>this.assetLoader.getTextureByAssetId(s),getMesh:s=>this.assetLoader.getModelByAssetId(s).then((s=>s.scene))},this.view,this.physics,this.shaderProvider);this.system=t,this.disposeSystem=e,this.particleSystemContainer=i}play(){this.paused=!1;this.system.emitters.every((s=>s.dead))&&this.restart()}pause(){this.paused=!0}stop(){this.system.emitters.forEach((s=>{const t=s.rate;t instanceof e&&(t.nextTime=1/0)}))}restart(){if(null!=this.system&&null!=this.system.emitters)for(const s of this.system.emitters){const t=s.rate;t instanceof l?t.restart():t.nextTime=0,s.removeAllParticles()}}onUpdate(s){this.paused||(this.object.getWorldPosition(this._worldPos),this.object.getWorldQuaternion(this._worldRot),this._worldEul.setFromQuaternion(this._worldRot),this.system?.emitters.forEach((s=>{"world"===s._space&&(s.setPosition(this._worldPos),s.setRotation(this._worldEul))})),this.system?.update(s*this.timescale))}getParticleCount(){return this.system?.getCount()??0}onEndPlay(){this.stop(),null!=this.disposeSystem&&this.disposeSystem()}};y=s([i()],y);export{y as VfxActor};/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -45,6 +45,9 @@ export type OutputCustomShader = {
45
45
  shader: string;
46
46
  shaderParams: Record<string, CustomParamValue>;
47
47
  };
48
+ export type OutputTextureSetting = {
49
+ opacityChannel?: 'alpha' | 'red' | 'none';
50
+ };
48
51
  export type CommonOutput = {
49
52
  space: 'world' | 'local';
50
53
  };
@@ -57,7 +60,7 @@ export type SpriteOutput = {
57
60
  softness: number;
58
61
  flipbook?: FlipbookSettings;
59
62
  bloom: boolean;
60
- } & CommonOutput & Partial<OutputCustomShader>;
63
+ } & CommonOutput & Partial<OutputCustomShader> & OutputTextureSetting;
61
64
  export type StretchedSpriteOutput = {
62
65
  type: 'stretchedSprite';
63
66
  texture: string;
@@ -67,7 +70,7 @@ export type StretchedSpriteOutput = {
67
70
  scale: number;
68
71
  softness: number;
69
72
  bloom: boolean;
70
- } & CommonOutput & Partial<OutputCustomShader>;
73
+ } & CommonOutput & Partial<OutputCustomShader> & OutputTextureSetting;
71
74
  export type MeshOutput = {
72
75
  type: 'mesh';
73
76
  assetId: AssetId;
@@ -87,7 +90,7 @@ export type TrailOutput = {
87
90
  bloom: boolean;
88
91
  scrollSpeed?: number;
89
92
  width?: number;
90
- } & CommonOutput & Partial<OutputCustomShader>;
93
+ } & CommonOutput & Partial<OutputCustomShader> & OutputTextureSetting;
91
94
  export type ShapeOutput = {
92
95
  type: 'shape';
93
96
  shape: LibraryShapeType;
@@ -145,6 +148,7 @@ export declare function EmitterDataConstructor(): {
145
148
  output: {
146
149
  type: "sprite";
147
150
  texture: any;
151
+ opacityChannel: "alpha";
148
152
  color: string;
149
153
  blendingMode: "normal";
150
154
  space: "world";
@@ -1 +1 @@
1
- {"version":3,"file":"vfx-asset.d.ts","sourceRoot":"","sources":["../../../src/effects/vfx/vfx-asset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAAE,uBAAuB,EAAE,wBAAwB,EAA0B,MAAM,eAAe,CAAC;AAM1G,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,MAAM,CAAA;IAEZ,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AACD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,YAAY,CAAA;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AACD,MAAM,MAAM,QAAQ,GAAG,YAAY,GAAC,kBAAkB,CAAA;AAEtD,MAAM,MAAM,eAAe,GAAG;IAC5B,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,wBAAwB,CAAA;IAC9B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAA;CACzC,C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C,CAAC,MAAM,CAAC,CAAA;AAE/E,MAAM,MAAM,YAAY,GAAG;IACzB;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,QAAQ,EAAE,WAAW,EAAE,CAAA;CAExB,CAAA;AAGD,wBAAgB,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyCrC"}
@@ -1,4 +1,4 @@
1
- import{SerializedParamType as t}from"../../scene/model.js";import*as e from"three";import{randomString as i}from"../../utils/math.js";export const BlendingModes=["additive","subtractive","multiply","normal"];export const ThreeBlendingMode={normal:e.NormalBlending,additive:e.AdditiveBlending,subtractive:e.SubtractiveBlending,multiply:e.MultiplyBlending};export const FlipbookModes=["clamp","loop"];export const ParticleChildSpawnEvents=["collision","start"];export function EmitterDataConstructor(){return{id:i(),name:"Emitter",rate:{type:"continuous",count:1,time:.5,delay:0},position:[0,0,0],rotation:[0,0,0],initializers:[{id:i(),type:"lifetime",params:{duration:{type:t.Number,value:1}}}],behaviours:[],children:[],output:{type:"sprite",texture:null,color:"#ffffff",blendingMode:"normal",space:"world",softness:0,intensity:1,bloom:!1}}}/*
1
+ import{SerializedParamType as t}from"../../scene/model.js";import*as e from"three";import{randomString as i}from"../../utils/math.js";export const BlendingModes=["additive","subtractive","multiply","normal"];export const ThreeBlendingMode={normal:e.NormalBlending,additive:e.AdditiveBlending,subtractive:e.SubtractiveBlending,multiply:e.MultiplyBlending};export const FlipbookModes=["clamp","loop"];export const ParticleChildSpawnEvents=["collision","start"];export function EmitterDataConstructor(){return{id:i(),name:"Emitter",rate:{type:"continuous",count:1,time:.5,delay:0},position:[0,0,0],rotation:[0,0,0],initializers:[{id:i(),type:"lifetime",params:{duration:{type:t.Number,value:1}}}],behaviours:[],children:[],output:{type:"sprite",texture:null,opacityChannel:"alpha",color:"#ffffff",blendingMode:"normal",space:"world",softness:0,intensity:1,bloom:!1}}}/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
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Emitter as n,Rate as s}from"@hology/nebula";import*as a from"three";import{Object3D as o}from"three";import{AttributeVec3Node as r,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as m,UniformFloatNode as u,UniformVec3Node as p,Vec3ExpressionNode as h,Vec4Node as d,attributeFloat as f,attributeVec3 as y,attributeVec4 as g,attributes as w,float as v,glslFunction as x,lambertMaterial as A,log as b,pow as E,rgb as M,rgba as P,saturate as I,standardMaterial as T,textureSampler2d as B,transformed as R,uniformFloat as S,uniforms as j,varying as C,varyingAttributes as k,varyingVec3 as z,varyingVec4 as V}from"three-shader-graph";import{prepareClassParameters as D,prepareShapeParameters as F}from"../../scene/materializer.js";import{SerializedParamType as Q}from"../../scene/model.js";import{ShapeLibrary as U}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as W,linearEyeDepth as L}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as q,particleTimeUniformName as H,particleUniforms as G,particleVelcoityUniformName as J}from"../../shader-nodes/particle.js";import{sampleFlipbook as O}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as N}from"./initializsers.js";import{DelayRate as K,OnceRate as X}from"./rates.js";import{StretchedSprite as Y}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as _,VfxInitializserLibrary as $}from"./vfx-defs.js";import{MultiRenderer as ee}from"./vfx-renderers.js";import{WorldCollisionBehaviour as te}from"./vfx-collision-behaviour.js";import{SpriteNodeShaderMaterial as ie}from"../../shader/sprite-shader.js";export async function materializeVfx(t,i,n,s,r,l){let c=i;for(;null!=c.parent;)c=c.parent;const m=new o;m.name="particle system local",i.add(m);const u=new o;u.name="particle system world",c.add(u);const p=new ee(u,m,a,s),h=new e;return(await Promise.all(t.vfx.emitters.map((async e=>{const t=await ne(e,n,h,r,l);return t.setParentRecursive(h),t.emit()})))).forEach((e=>h.addEmitter(e))),h.addRenderer(p).emit({onEnd:()=>{}}),{container:u,system:h,dispose:()=>{u.removeFromParent(),m.removeFromParent(),p.dispose()}}}async function ne(e,t,n,m,z){const D=function(e){let t;switch(e.rate.type){case"continuous":t=new K(e.rate.delay??0,e.rate.count,e.rate.time);break;case"once":t=new X(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new s(0,1/0)}return t}(e);let q;switch(e.output.type){case"sprite":q=new i(await async function(e,t,i){let n=null;n=null!=e.shader?await ae(e,t,i):await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):se,n=B(i);let s=n.sample(k.uv);e.flipbook?.enabled&&(s=O(n,w.uv,e.flipbook.columns,e.flipbook.rows,G.time,e.flipbook.fps,e.flipbook.mode));const o=new u("rotation",0),r=new p("color").rgb,l=S("opacity",1),c=L.subtract(W).divide(L);let m=s.x.multiply(l);if("number"==typeof e.softness&&e.softness>0){const t=E(c,v(e.softness));m=m.multiply(t)}const h=x(d,{position:R.position,modelViewMatrix:j.modelViewMatrix,rotation:o},"\n vec2 center = vec2(0.5, 0.5);\n vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n // Using scale form instance matrix instead of modelMatrix\n vec2 scale;\n scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\n // This times 2 on scale seem to make it appear like when using regular sprites. \n // Not sure if this is correct though.\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * (scale);\n\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\n mvPosition.xy += rotatedPosition;\n return projectionMatrix * mvPosition;\n ");var f=new ie({color:P(r.multiplyScalar(e.intensity??1),m).multiply(s),transparent:!0,position:h,uniforms:{color:{value:new a.Color(e.color)}}});null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??a.NormalBlending,f}(e,t);const s=new a.Mesh(new a.PlaneGeometry(1,1),n);return s.name="sprite",s}(e.output,t,z));break;case"stretchedSprite":q=new i(await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):se,n=B(i).sample(k.uv),s=V(new l("color")),o=s.rgb;let r=s.w;if("number"==typeof e.softness&&e.softness>0){const t=L.subtract(W).divide(b(L)),i=E(t,v(e.softness));r=I(r.multiply(i))}const c=x(d,{position:w.position,offset:y("offset"),modelViewMatrix:j.modelViewMatrix,velocity:g("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var m=new ie({color:P(o.multiplyScalar(e.intensity??1),r).multiply(n),transparent:!0,position:c,uniforms:{color:{value:new a.Color(e.color)}}});null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);m.blending=Z[e.blendingMode]??a.NormalBlending;const u=new Y(new a.PlaneGeometry(1,1),m);return u.scaleFactor=e.scale,u}(e.output,t));break;case"shape":q=new i(await async function(e,t,i){if(null==e.shape)return console.log("Shape is null"),new o;const n=U[e.shape];if(null==n)return console.error(`No shape with type ${e.shape}`),new o;const s=F(e.params??{}),l=n.geometry(s);let m=null;m=null!=e.shader?await ae(e,t,i):null!=e.material?function(e){const t=C(new h("instanceColor")).rgb;let i,n=C(new r("particleData")).x;if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshBasicMaterial){let s=t.multiply(M(e.color));null!=e.map&&(s=s.multiply(B(e.map).sample(k.uv).rgb)),null!=e.alphaMap&&(n=n.multiply(B(e.alphaMap).sample(k.uv).r)),e instanceof a.MeshStandardMaterial?i=new c({color:T({color:s,emissive:M(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshLambertMaterial?i=new c({color:A({color:s}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshBasicMaterial&&(i=new c({color:s.rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}))}null!=i&&(!0===e.userData?.hasBloom&&null!=i&&(i.userData.hasBloom=!0),i.side=e.side,i.transparent=e.transparent);return i??e}(await t.getMaterial(e.material)):function(){const e=C(new h("instanceColor")).rgb,t=C(new r("particleData")).x;return new c({color:A({color:e}).rgb.rgba(t),transparent:!0})}();null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);return new a.Mesh(l,m)}(e.output,t,z));break;case"mesh":q=new i(await async function(e,t,i){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new o;const n=await t.getMesh(e.assetId),s=await t.getAsset(e.assetId);if(null!=e.shader){const s=await ae(e,t,i);null!=s&&!0===e.bloom&&(s.userData.hasBloom=!0),n.traverse((e=>{e instanceof a.Mesh&&(e.material=s)}))}else{const e=[];if(null!=s.materialAssignments)for(const i of s.materialAssignments)n.traverse((n=>{n instanceof a.Mesh&&n.material instanceof a.Material&&n.material.color instanceof a.Color&&(n.material.name!=i.name&&null!=i.name||"#"+n.material.color.getHexString()!==i.color||e.push(t.getMaterial(i.materialId).then((e=>n.material=e))))}));await Promise.all(e)}const r=[];if(n.traverse((e=>{e instanceof a.Mesh&&r.push(e)})),1===r.length){const e=r[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return n}(e.output,t,z));break;case"trail":q=new i({type:"trail",taper:e.output.taper,headGeometry:null,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width});break;default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const H=new re;H.parent=n,H.setRate(D),H._space=e.output.space;const J=await Promise.all(e.initializers.filter((e=>null!=$[e.type])).map((async e=>{const t=$[e.type],i=await F(e.params??{});return t.build(i)})));J.push(q,new N),H.addInitializers(J);const ee=await Promise.all(e.behaviours.filter((e=>null!=_[e.type])).map((async e=>{const t=_[e.type];for(const[i,n]of Object.entries(e.params))t.parameters&&null!=t.parameters[i]&&"curve"===t.parameters[i].type&&n.type!==Q.Curve&&(n.type=Q.Curve);const i=await F(e.params??{});return t.build(i)})).sort(((e,t)=>e instanceof te?1:0)));ee.push(new oe);for(const e of ee)e instanceof te&&(e.physics=m);H.addBehaviours(ee);for(const i of e.children){const e=await ne(i,t,n,m,z),s=new EmitterPool((()=>{const t=e.clone();return t.onExpired=()=>{const e=H.childEmitters.findIndex((e=>e.id===t.id));-1!=e&&H.childEmitters.splice(e,1),s.release(t)},t})),a=H.eventDispatcher,o=new Map;H.bindEmitterEvent=!0,a.addEventListener("PARTICLE_DEAD",(e=>{const t=o.get(e.id);if(null!=t){const e=H.childEmitters.findIndex((e=>e.id===t.id));null!=e&&(t.stopEmit(),H.childEmitters.splice(e,1))}}));let r="PARTICLE_CREATED";if("spawnEvent"in i)switch(i.spawnEvent){case"collision":r="PARTICLE_COLLISION";break;case"start":r="PARTICLE_CREATED"}a.addEventListener(r,(e=>{const t=s.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),H.childEmitters.push(t),o.set(e.id,t),t.parentParticle=e,t.system=H.system,t.emit()}))}return H}const se=(new a.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function ae(e,t,i){const n=i.get(e.shader);if(null==n)return console.error("No shader exists with name "+e.shader),new a.Material;const s=new n.type,o=await D(e.shaderParams,n.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0);return Object.assign(s,o),s.build()}class oe extends t{initialize(e){e.body instanceof a.Object3D&&e.body.traverse((e=>{if(e instanceof a.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[q]||null!=t.uniforms[H]||t.uniforms[J])}}))}mutate(e,t,i){this.energize(e,t),e.target instanceof o&&e.target.traverse((t=>{if(t instanceof a.Mesh){const i=t.material;i instanceof c&&(null!=i.uniforms[q]&&(i.uniforms[q].value=this.energy),null!=i.uniforms[H]&&(i.uniforms[H].value=e.age),null!=i.uniforms[J]&&(i.uniforms[J].value=e.velocity))}}))}}class re extends n{constructor(){super(...arguments),this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}update(e){if(!this.isEmitting&&0===this.particles.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle?t.position.copy(t.parentParticle.position):t.setPosition(this.position),t.update(e)}clone(){const e=new re;return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach((t=>t.setParentRecursive(e)))}}export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
1
+ import e,{Behaviour as t,Body as i,Emitter as n,Rate as s}from"@hology/nebula";import*as a from"three";import{Object3D as o}from"three";import{AttributeVec3Node as r,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as m,UniformFloatNode as u,UniformVec3Node as p,Vec3ExpressionNode as h,Vec4Node as d,attributeFloat as f,attributeVec3 as y,attributeVec4 as g,attributes as w,float as v,glslFunction as b,lambertMaterial as x,log as A,pow as E,rgb as M,rgba as P,saturate as T,standardMaterial as I,textureSampler2d as C,transformed as B,uniformFloat as R,uniforms as k,varying as S,varyingAttributes as j,varyingVec3 as z,varyingVec4 as V}from"three-shader-graph";import{prepareClassParameters as D,prepareShapeParameters as F}from"../../scene/materializer.js";import{SerializedParamType as Q}from"../../scene/model.js";import{ShapeLibrary as U}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as W,linearEyeDepth as L}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as q,particleTimeUniformName as H,particleUniforms as G,particleVelcoityUniformName as J}from"../../shader-nodes/particle.js";import{sampleFlipbook as O}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as N}from"./initializsers.js";import{DelayRate as K,OnceRate as X}from"./rates.js";import{StretchedSprite as Y}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as _,VfxInitializserLibrary as $}from"./vfx-defs.js";import{MultiRenderer as ee}from"./vfx-renderers.js";import{WorldCollisionBehaviour as te}from"./vfx-collision-behaviour.js";import{SpriteNodeShaderMaterial as ie}from"../../shader/sprite-shader.js";export async function materializeVfx(t,i,n,s,r,l){let c=i;for(;null!=c.parent;)c=c.parent;const m=new o;m.name="particle system local",i.add(m);const u=new o;u.name="particle system world",c.add(u);const p=new ee(u,m,a,s),h=new e;return(await Promise.all(t.vfx.emitters.map((async e=>{const t=await ne(e,n,h,r,l);return t.setParentRecursive(h),t.emit()})))).forEach((e=>h.addEmitter(e))),h.addRenderer(p).emit({onEnd:()=>{}}),{container:u,system:h,dispose:()=>{u.removeFromParent(),m.removeFromParent(),p.dispose()}}}async function ne(e,t,n,m,z){const D=function(e){let t;switch(e.rate.type){case"continuous":t=new K(e.rate.delay??0,e.rate.count,e.rate.time);break;case"once":t=new X(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new s(0,1/0)}return t}(e);let q;switch(e.output.type){case"sprite":q=new i(await async function(e,t,i){let n=null;n=null!=e.shader?await ae(e,t,i):await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):se,n=C(i);let s=n.sample(j.uv);e.flipbook?.enabled&&(s=O(n,w.uv,e.flipbook.columns,e.flipbook.rows,G.time,e.flipbook.fps,e.flipbook.mode));const o=new u("rotation",0),r=new p("color").rgb,l=R("opacity",1),c=L.subtract(W).divide(L);let m=l;switch(e.opacityChannel??"red"){case"none":break;case"red":m=m.multiply(s.r);break;case"alpha":m=m.multiply(s.a)}if("number"==typeof e.softness&&e.softness>0){const t=E(c,v(e.softness));m=m.multiply(t)}const h=b(d,{position:B.position,modelViewMatrix:k.modelViewMatrix,rotation:o},"\n vec2 center = vec2(0.5, 0.5);\n vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n // Using scale form instance matrix instead of modelMatrix\n vec2 scale;\n scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\n // This times 2 on scale seem to make it appear like when using regular sprites. \n // Not sure if this is correct though.\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * (scale);\n\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\n mvPosition.xy += rotatedPosition;\n return projectionMatrix * mvPosition;\n ");var f=new ie({color:P(r.multiply(s.rgb).multiplyScalar(e.intensity??1),m),transparent:!0,position:h,uniforms:{color:{value:new a.Color(e.color)}}});null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??a.NormalBlending,f}(e,t);const s=new a.Mesh(new a.PlaneGeometry(1,1),n);return s.name="sprite",s}(e.output,t,z));break;case"stretchedSprite":q=new i(await async function(e,t){const i=null!=e.texture?await t.getTexture(e.texture):se,n=C(i).sample(j.uv),s=V(new l("color")),o=s.rgb.multiply(n.rgb);let r=s.w;switch(e.opacityChannel??"red"){case"none":break;case"red":r=r.multiply(n.r);break;case"alpha":r=r.multiply(n.a)}if("number"==typeof e.softness&&e.softness>0){const t=L.subtract(W).divide(A(L)),i=E(t,v(e.softness));r=T(r.multiply(i))}const c=b(d,{position:w.position,offset:y("offset"),modelViewMatrix:k.modelViewMatrix,velocity:g("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var m=new ie({color:P(o.multiplyScalar(e.intensity??1),r),alphaTest:.1,transparent:!0,position:c,uniforms:{color:{value:new a.Color(e.color)}}});null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);m.blending=Z[e.blendingMode]??a.NormalBlending;const u=new Y(new a.PlaneGeometry(1,1),m);return u.scaleFactor=e.scale,u}(e.output,t));break;case"shape":q=new i(await async function(e,t,i){if(null==e.shape)return console.log("Shape is null"),new o;const n=U[e.shape];if(null==n)return console.error(`No shape with type ${e.shape}`),new o;const s=F(e.params??{}),l=n.geometry(s);let m=null;m=null!=e.shader?await ae(e,t,i):null!=e.material?function(e){const t=S(new h("instanceColor")).rgb;let i,n=S(new r("particleData")).x;if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshBasicMaterial){let s=t.multiply(M(e.color));null!=e.map&&(s=s.multiply(C(e.map).sample(j.uv).rgb)),null!=e.alphaMap&&(n=n.multiply(C(e.alphaMap).sample(j.uv).r)),e instanceof a.MeshStandardMaterial?i=new c({color:I({color:s,emissive:M(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshLambertMaterial?i=new c({color:x({color:s}).rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}):e instanceof a.MeshBasicMaterial&&(i=new c({color:s.rgb.rgba(n),transparent:e.transparent,alphaTest:e.alphaTest}))}null!=i&&(!0===e.userData?.hasBloom&&null!=i&&(i.userData.hasBloom=!0),i.side=e.side,i.transparent=e.transparent);return i??e}(await t.getMaterial(e.material)):function(){const e=S(new h("instanceColor")).rgb,t=S(new r("particleData")).x;return new c({color:x({color:e}).rgb.rgba(t),transparent:!0})}();null!=m&&!0===e.bloom&&(m.userData.hasBloom=!0);return new a.Mesh(l,m)}(e.output,t,z));break;case"mesh":q=new i(await async function(e,t,i){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new o;const n=await t.getMesh(e.assetId),s=await t.getAsset(e.assetId);if(null!=e.shader){const s=await ae(e,t,i);null!=s&&!0===e.bloom&&(s.userData.hasBloom=!0),n.traverse((e=>{e instanceof a.Mesh&&(e.material=s)}))}else{const e=[];if(null!=s.materialAssignments)for(const i of s.materialAssignments)n.traverse((n=>{n instanceof a.Mesh&&n.material instanceof a.Material&&n.material.color instanceof a.Color&&(n.material.name!=i.name&&null!=i.name||"#"+n.material.color.getHexString()!==i.color||e.push(t.getMaterial(i.materialId).then((e=>n.material=e))))}));await Promise.all(e)}const r=[];if(n.traverse((e=>{e instanceof a.Mesh&&r.push(e)})),1===r.length){const e=r[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return n}(e.output,t,z));break;case"trail":q=new i({type:"trail",taper:e.output.taper,headGeometry:null,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,opacityChannel:e.output.opacityChannel,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width});break;default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const H=new re;H.parent=n,H.setRate(D),H._space=e.output.space;const J=await Promise.all(e.initializers.filter((e=>null!=$[e.type])).map((async e=>{const t=$[e.type],i=await F(e.params??{});return t.build(i)})));J.push(q,new N),H.addInitializers(J);const ee=await Promise.all(e.behaviours.filter((e=>null!=_[e.type])).map((async e=>{const t=_[e.type];for(const[i,n]of Object.entries(e.params))t.parameters&&null!=t.parameters[i]&&"curve"===t.parameters[i].type&&n.type!==Q.Curve&&(n.type=Q.Curve);const i=await F(e.params??{});return t.build(i)})).sort(((e,t)=>e instanceof te?1:0)));ee.push(new oe);for(const e of ee)e instanceof te&&(e.physics=m);H.addBehaviours(ee);for(const i of e.children){const e=await ne(i,t,n,m,z),s=new EmitterPool((()=>{const t=e.clone();return t.onExpired=()=>{const e=H.childEmitters.findIndex((e=>e.id===t.id));-1!=e&&H.childEmitters.splice(e,1),s.release(t)},t})),a=H.eventDispatcher,o=new Map;H.bindEmitterEvent=!0,a.addEventListener("PARTICLE_DEAD",(e=>{const t=o.get(e.id);if(null!=t){const e=H.childEmitters.findIndex((e=>e.id===t.id));null!=e&&(t.stopEmit(),H.childEmitters.splice(e,1))}}));let r="PARTICLE_CREATED";if("spawnEvent"in i)switch(i.spawnEvent){case"collision":r="PARTICLE_COLLISION";break;case"start":r="PARTICLE_CREATED"}a.addEventListener(r,(e=>{const t=s.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),H.childEmitters.push(t),o.set(e.id,t),t.parentParticle=e,t.system=H.system,t.emit()}))}return H}const se=(new a.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function ae(e,t,i){const n=i.get(e.shader);if(null==n)return console.error("No shader exists with name "+e.shader),new a.Material;const s=new n.type,o=await D(e.shaderParams,n.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0);return Object.assign(s,o),s.build()}class oe extends t{initialize(e){e.body instanceof a.Object3D&&e.body.traverse((e=>{if(e instanceof a.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[q]||null!=t.uniforms[H]||t.uniforms[J])}}))}mutate(e,t,i){this.energize(e,t),e.target instanceof o&&e.target.traverse((t=>{if(t instanceof a.Mesh){const i=t.material;i instanceof c&&(null!=i.uniforms[q]&&(i.uniforms[q].value=this.energy),null!=i.uniforms[H]&&(i.uniforms[H].value=e.age),null!=i.uniforms[J]&&(i.uniforms[J].value=e.velocity))}}))}}class re extends n{constructor(){super(...arguments),this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}update(e){if(!this.isEmitting&&0===this.particles.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle?t.position.copy(t.parentParticle.position):t.setPosition(this.position),t.update(e)}clone(){const e=new re;return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach((t=>t.setParentRecursive(e)))}}export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,7 +1,7 @@
1
1
  import { CustomRenderer, MeshRenderer, Particle } from '@hology/nebula';
2
2
  import * as THREE from 'three';
3
3
  import { Object3D } from 'three';
4
- import { ViewController } from '../../gameplay';
4
+ import { OutputTextureSetting, ViewController } from '../../gameplay';
5
5
  export declare class MultiRenderer extends CustomRenderer {
6
6
  private worldContainer;
7
7
  private localContainer;
@@ -25,6 +25,7 @@ export type TrailTemplate = {
25
25
  material?: THREE.ShaderMaterial;
26
26
  dragTexture?: boolean;
27
27
  texture: THREE.Texture;
28
+ opacityChannel?: OutputTextureSetting['opacityChannel'];
28
29
  taper: boolean;
29
30
  color: string;
30
31
  colorEnd: string;
@@ -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,OAAO,EAA2B,QAAQ,EAAc,MAAM,OAAO,CAAC;AAEtE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAU/C,qBAAa,aAAc,SAAQ,cAAc;IAInC,OAAO,CAAC,cAAc;IAAY,OAAO,CAAC,cAAc;IAAY,OAAO,CAAC,KAAK;IAAgB,OAAO,CAAC,IAAI;IAHzH,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAAK;gBAEP,cAAc,EAAE,QAAQ,EAAU,cAAc,EAAE,QAAQ,EA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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 i,Object3D as o}from"three";import{NodeShaderMaterial as s}from"three-shader-graph";import{StretchedSprite as n}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){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,i="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==i[d.trail]&&(i[d.trail]=new TrailRenderer(r,this.three)),e._renderer=i[d.trail]):e.body instanceof n?(null==i[d.stretchedBillboard]&&(i[d.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=i[d.stretchedBillboard]):e.body instanceof a.Sprite||e.body instanceof a.Mesh&&"sprite"===e.body.name?(null==i[d.sprite]&&(i[d.sprite]=new CombinedRenderer(r,this.three)),e._renderer=i[d.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof s?(null==i[d.instanced]&&(i[d.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=i[d.instanced]):e.body instanceof a.Object3D?(null==i[d.mesh]&&(i[d.mesh]=new CombinedRenderer(r,this.three)),e._renderer=i[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,!0),i=new o,s=l.createBaseMaterial(t.texture,t.scrollSpeed);s.uniforms.taper.value=t.taper??!1;const n=new a.Color(t.color??0).multiplyScalar(t.intensity),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensityEnd??t.intensity??1);s.uniforms.headColor&&s.uniforms.tailColor&&(s.uniforms.headColor.value=new a.Vector4(n.r,n.g,n.b,t.opacityStart??1),s.uniforms.tailColor.value=new a.Vector4(c.r,c.g,c.b,t.opacityEnd??1)),t.bloom&&(s.userData.hasBloom=!0),r.initialize(s,Math.round(t.length??10),!1,t.width,null,i);const d=e.rotation;i.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=i}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 i=w;i.setFromUnitVectors(a,y),t.rotation.set(0,0,0),t.applyQuaternion(i);const o=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=o){const t=this.trails[o];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(),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 o&&(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:i,rotation:s}=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(s.x,s.y,s.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof o){const r=m.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(h);a.applyAxisAngle(p,Math.PI/-2),u.setFromUnitVectors(a,r),t.quaternion.copy(u)}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),i&&(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"),i=e.mesh.geometry.getAttribute("velocity"),o=e.mesh.geometry.getAttribute("rotation"),s=e.mesh.geometry.getAttribute("color");let n=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);s.setXYZW(n,e.r,e.g,e.b,1),s.needsUpdate=!0}l.useAlpha&&(s.setW(n,l.alpha),s.needsUpdate=!0),"number"==typeof l.rotation?o.setX(n,l.rotation):o.setX(n,l.rotation.x);const e=l.position;if(t.setXYZ(n,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(n,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;i.setXYZW(n,m.x*c,m.y*c,m.z*c,d),n++}n>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*n),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*n),r.needsUpdate=!0,s.clearUpdateRanges(),s.addUpdateRange(0,4*n),s.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,4*n),i.needsUpdate=!0,o.clearUpdateRanges(),o.addUpdateRange(0,n),o.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 n&&null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(null==r){const o=this.calcMaxCount(e),s=new a.InstancedBufferGeometry;s.setIndex(t.geometry.getIndex()),s.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&s.setAttribute("normal",t.geometry.getAttribute("normal")),s.setAttribute("uv",t.geometry.getAttribute("uv"));const n=new i(new Float32Array(3*o),3);n.setUsage(a.DynamicDrawUsage),s.setAttribute("offset",n);const l=new i(new Float32Array(4*o),4);if(l.setUsage(a.DynamicDrawUsage),s.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 i(new Float32Array(3*o),3);d.setUsage(a.DynamicDrawUsage),s.setAttribute("size",d);const m=new i(new Float32Array(4*o),4);m.setUsage(a.DynamicDrawUsage),s.setAttribute("velocity",m);const h=new i(new Float32Array(4*o),1);h.setUsage(a.DynamicDrawUsage),s.setAttribute("rotation",h),r={mesh:new a.Mesh(s,t.material),indices:new Float32Array(o),particles:[]},this.meshes.push(r),this.container.add(r.mesh)}let o=r.indices.findIndex((e=>0===e));o<0&&(o=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[o]=performance.now(),e.target=o,r.particles[o]=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,h=new a.Vector3,u=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)){if(null==e.target){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 i=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,i),indices:new Array(i).fill(null),particles:[]},r.mesh.setColorAt(0,C.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="";const o=new Float32Array(3*i);b.makeScale(0,0,0);for(let e=0;e<i;e++)o[3*e+0]=1,o[3*e+1]=1,r.mesh.setMatrixAt(e,b);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(o,3)),this.meshes.push(r),this.container.add(r.mesh)}let i=r.indices.findIndex((e=>null==e));i<0&&(i=r.indices.indexOf(Math.min(...r.indices))),r.indices[i]=performance.now(),e.target=i,r.particles[i]=e}if("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:i}=e;if(null==t)return;const o=e.body,s=this.meshes.find((e=>e.mesh.geometry.uuid===o.geometry.uuid&&e.mesh.material.uuid===o.material.uuid));if(null==s)return;f(e,s.mesh),a&&(s.mesh.setColorAt(e.target,C.copy(e.color)),s.mesh.instanceColor.needsUpdate=!0);const n=s.mesh.geometry.getAttribute("particleData");r&&n.setX(e.target,e.alpha),n.setY(e.target,e.energy),n.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 o;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,i=r.count,o=[],s=r.geometry.getAttribute("particleData"),n=new a.Vector3;for(let l=0;l<i;l++){const i=new a.Matrix4,c=new a.Color;r.getMatrixAt(l,i),r.getColorAt(l,c);const d=s.getX(l);n.setFromMatrixPosition(i);const m=n.distanceTo(t.position);o.push({index:l,distance:m,matrix:i,particle:e.particles[l],color:c,pdx:d})}o.sort(((e,t)=>t.distance-e.distance));for(let e=0;e<i;e++){const t=o[e].matrix;null==o[e].particle&&t.makeScale(0,0,0),r.setMatrixAt(e,t),r.setColorAt(e,o[e].color),s.setX(e,o[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 i,Object3D as o}from"three";import{NodeShaderMaterial as s}from"three-shader-graph";import{StretchedSprite as n}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){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,i="world"===t?this.worldRenderers:this.localRenderers;return"trail"===e.body.type?(null==i[d.trail]&&(i[d.trail]=new TrailRenderer(r,this.three)),e._renderer=i[d.trail]):e.body instanceof n?(null==i[d.stretchedBillboard]&&(i[d.stretchedBillboard]=new StretchedSpriteInstancedRenderer(r,this.three,this.view)),e._renderer=i[d.stretchedBillboard]):e.body instanceof a.Sprite||e.body instanceof a.Mesh&&"sprite"===e.body.name?(null==i[d.sprite]&&(i[d.sprite]=new CombinedRenderer(r,this.three)),e._renderer=i[d.sprite]):e.body instanceof a.Mesh&&0==e.body.children.length&&e.body.material instanceof s?(null==i[d.instanced]&&(i[d.instanced]=new InstancedRenderer(r,this.three,this.view)),e._renderer=i[d.instanced]):e.body instanceof a.Object3D?(null==i[d.mesh]&&(i[d.mesh]=new CombinedRenderer(r,this.three)),e._renderer=i[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,!0),i=new o,s=l.createBaseMaterial(t.texture,t.scrollSpeed,t.opacityChannel);s.uniforms.taper.value=t.taper??!1;const n=new a.Color(t.color??0).multiplyScalar(t.intensity),c=new a.Color(t.colorEnd??0).multiplyScalar(t.intensityEnd??t.intensity??1);s.uniforms.headColor&&s.uniforms.tailColor&&(s.uniforms.headColor.value=new a.Vector4(n.r,n.g,n.b,t.opacityStart??1),s.uniforms.tailColor.value=new a.Vector4(c.r,c.g,c.b,t.opacityEnd??1)),t.bloom&&(s.userData.hasBloom=!0),r.initialize(s,Math.round(t.length??10),!1,t.width,null,i);const d=e.rotation;i.rotation.set(d.x,d.y,d.z);e.scale;r.activate(),this.trails.push(r),e.target=i}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 i=w;i.setFromUnitVectors(a,y),t.rotation.set(0,0,0),t.applyQuaternion(i);const o=this.trails.findIndex((e=>e.targetObject.id===t.id));if(-1!=o){const t=this.trails[o];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(),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 o&&(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:i,rotation:s}=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(s.x,s.y,s.z)),this.scale(e),e.transform&&e.transform.orientAlongVelocity&&t instanceof o){const r=m.set(e.velocity.x,e.velocity.y,e.velocity.z).normalize(),a=t.getWorldDirection(h);a.applyAxisAngle(p,Math.PI/-2),u.setFromUnitVectors(a,r),t.quaternion.copy(u)}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),i&&(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"),i=e.mesh.geometry.getAttribute("velocity"),o=e.mesh.geometry.getAttribute("rotation"),s=e.mesh.geometry.getAttribute("color");let n=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);s.setXYZW(n,e.r,e.g,e.b,1),s.needsUpdate=!0}l.useAlpha&&(s.setW(n,l.alpha),s.needsUpdate=!0),"number"==typeof l.rotation?o.setX(n,l.rotation):o.setX(n,l.rotation.x);const e=l.position;if(t.setXYZ(n,e.x,e.y,e.z),"number"!=typeof l.scale)throw new Error("Particle scale is not a number");r.setXYZ(n,l.scale,l.scale,l.scale);let c=l.body.scaleFactor;0===c&&(c=.001);const d=1,m=l.velocity;i.setXYZW(n,m.x*c,m.y*c,m.z*c,d),n++}n>0&&(t.clearUpdateRanges(),t.addUpdateRange(0,3*n),t.needsUpdate=!0,r.clearUpdateRanges(),r.addUpdateRange(0,3*n),r.needsUpdate=!0,s.clearUpdateRanges(),s.addUpdateRange(0,4*n),s.needsUpdate=!0,i.clearUpdateRanges(),i.addUpdateRange(0,4*n),i.needsUpdate=!0,o.clearUpdateRanges(),o.addUpdateRange(0,n),o.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 n&&null==e.target){const t=e.body;let r=this.meshes.find((e=>e.mesh.material.uuid===t.material.uuid));if(null==r){const o=this.calcMaxCount(e),s=new a.InstancedBufferGeometry;s.setIndex(t.geometry.getIndex()),s.setAttribute("position",t.geometry.getAttribute("position")),t.geometry.hasAttribute("normal")&&s.setAttribute("normal",t.geometry.getAttribute("normal")),s.setAttribute("uv",t.geometry.getAttribute("uv"));const n=new i(new Float32Array(3*o),3);n.setUsage(a.DynamicDrawUsage),s.setAttribute("offset",n);const l=new i(new Float32Array(4*o),4);if(l.setUsage(a.DynamicDrawUsage),s.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 i(new Float32Array(3*o),3);d.setUsage(a.DynamicDrawUsage),s.setAttribute("size",d);const m=new i(new Float32Array(4*o),4);m.setUsage(a.DynamicDrawUsage),s.setAttribute("velocity",m);const h=new i(new Float32Array(4*o),1);h.setUsage(a.DynamicDrawUsage),s.setAttribute("rotation",h),r={mesh:new a.Mesh(s,t.material),indices:new Float32Array(o),particles:[]},this.meshes.push(r),this.container.add(r.mesh)}let o=r.indices.findIndex((e=>0===e));o<0&&(o=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[o]=performance.now(),e.target=o,r.particles[o]=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,h=new a.Vector3,u=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)){if(null==e.target){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 i=this.calcMaxCount(e);r={mesh:new a.InstancedMesh(t.geometry,t.material,i),indices:new Array(i).fill(null),particles:[]},r.mesh.setColorAt(0,C.setScalar(1)),r.mesh.instanceColor.needsUpdate=!0,r.mesh.material.defines.USE_INSTANCING="";const o=new Float32Array(3*i);b.makeScale(0,0,0);for(let e=0;e<i;e++)o[3*e+0]=1,o[3*e+1]=1,r.mesh.setMatrixAt(e,b);r.mesh.instanceMatrix.needsUpdate=!0,r.mesh.geometry.setAttribute("particleData",new a.InstancedBufferAttribute(o,3)),this.meshes.push(r),this.container.add(r.mesh)}let i=r.indices.findIndex((e=>null==e));i<0&&(i=r.indices.indexOf(Math.min(...r.indices))),r.indices[i]=performance.now(),e.target=i,r.particles[i]=e}if("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:i}=e;if(null==t)return;const o=e.body,s=this.meshes.find((e=>e.mesh.geometry.uuid===o.geometry.uuid&&e.mesh.material.uuid===o.material.uuid));if(null==s)return;f(e,s.mesh),a&&(s.mesh.setColorAt(e.target,C.copy(e.color)),s.mesh.instanceColor.needsUpdate=!0);const n=s.mesh.geometry.getAttribute("particleData");r&&n.setX(e.target,e.alpha),n.setY(e.target,e.energy),n.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 o;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,i=r.count,o=[],s=r.geometry.getAttribute("particleData"),n=new a.Vector3;for(let l=0;l<i;l++){const i=new a.Matrix4,c=new a.Color;r.getMatrixAt(l,i),r.getColorAt(l,c);const d=s.getX(l);n.setFromMatrixPosition(i);const m=n.distanceTo(t.position);o.push({index:l,distance:m,matrix:i,particle:e.particles[l],color:c,pdx:d})}o.sort(((e,t)=>t.distance-e.distance));for(let e=0;e<i;e++){const t=o[e].matrix;null==o[e].particle&&t.makeScale(0,0,0),r.setMatrixAt(e,t),r.setColorAt(e,o[e].color),s.setX(e,o[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
  */
@@ -1 +1 @@
1
- {"version":3,"file":"initiate.d.ts","sourceRoot":"","sources":["../../src/gameplay/initiate.ts"],"names":[],"mappings":"AAAA,OAAkB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAA;AAEpE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAE5D,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAa3C,OAAO,EAAE,UAAU,EAAW,MAAM,MAAM,CAAA;AAO1C,KAAK,SAAS,CAAC,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC,CAAA;AAGpC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,WAAW,CAAA;IACpB,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAAA;KAAE,CAAA;IACvC,MAAM,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,CAAA;IACrC,EAAE,CAAC,EAAE;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,UAA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,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(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(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()}}/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -6,7 +6,6 @@ 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
- import { World } from '../world.js';
10
9
  import { AbstractPhysicsSystem, ActorPhysicsOptions } from './abstract-physics-system.js';
11
10
  export { Component, ActorComponent, type ComponentOptions, attach, Attach } from '../../actors/component.js';
12
11
  export declare class RayTestResult {
@@ -35,7 +34,6 @@ export declare enum PhysicsBodyType {
35
34
  */
36
35
  export declare class PhysicsSystem extends AbstractPhysicsSystem {
37
36
  viewController: ViewController;
38
- private gameWorld;
39
37
  readonly ready: Promise<void>;
40
38
  private world;
41
39
  private rapier;
@@ -51,7 +49,7 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
51
49
  private shouldRenderDebug;
52
50
  set showDebug(value: boolean);
53
51
  get showDebug(): boolean;
54
- constructor(viewController: ViewController, gameWorld: World);
52
+ constructor(viewController: ViewController);
55
53
  private shapeCacheBox;
56
54
  hasBoxIntersection(box: THREE.Box3): boolean;
57
55
  private debugMesh;
@@ -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,EAGL,cAAc,EASf,MAAM,mBAAmB,CAAA;AAM1B,OAAO,EAAE,YAAY,EAAQ,MAAM,wBAAwB,CAAA;AAC3D,OAAO,EAAW,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAKnC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAA;AAGzF,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,KAAK,gBAAgB,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AAG7G,qBAAa,aAAa;IAGxB,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,MAAM,EAAE,OAAO,CAAQ;IACvB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,OAAO,CAAgB;IACjC,SAAS,EAAE,OAAO,CAAgB;CACnC;AAED,UAAU,cAAc;IACtB,UAAU,CAAC,EAAE,mBAAmB,CAAA;IAChC,aAAa,CAAC,EAAE,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@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 v,Vector3 as B}from"three";import{Service as b}from"typedi";import{AssetMeshInstance as A}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as C,CapsuleCollisionShape as D,CollisionShapeSource as z,ConeCollisionShape as M,ConvexPolyhedronCollisionShape as S,CylinderCollisionShape as R,PhysicalShapeMesh as T,PlaneCollisionShape as E,SphereCollisionShape as W,TrimeshCollisionShape as F}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 P from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as I}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as L}from"./abstract-physics-system.js";import{ActorComponent as k,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 B,this.hitNormal=new B}}export var PhysicsBodyType;!function(e){e[e.dynamic=1]="dynamic",e[e.static=2]="static",e[e.kinematic=4]="kinematic",e[e.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const G=new B,q=new B,Q=new w;let U=class extends L{set showDebug(e){this.shouldRenderDebug=e,this.debugMesh&&(this.debugMesh.visible=e)}get showDebug(){return this.shouldRenderDebug}constructor(e,t){super(),this.viewController=e,this.gameWorld=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._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new B,this._raytestDirection=new B,this.controlledActors=new Set,this.ready=this.setup()}hasBoxIntersection(e){const t=e.getCenter(G),i=e.getSize(q),o=i.x+1e6*i.y+1e12*i.z;if(!this.shapeCacheBox.has(o)){const e=new s.Cuboid(i.x/2,i.y/2,i.z/2);this.shapeCacheBox.set(o,e)}const n=this.shapeCacheBox.get(o);return null!=this.world.intersectionWithShape(t,Q,n)}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.gameWorld.scene.add(this.debugMesh));const e=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new u(e.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await te(),this.eventQueue=new s.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((e=>{e=Math.min(.1,e),this.beforeStep.next(e),this.updatePhysics(e),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((e=>{if(e.isFixed())return;const t=this.staticMeshes.get(e)??this.bodyActors.get(e)?.object;var s,i;null!=t&&(t.parent instanceof v&&(ie(t.position,e.translation()),(e.isDynamic()||e.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(e)?.id))&&(s=t.quaternion,i=e.rotation(),s.x=i.x,s.y=i.y,s.z=i.z,s.w=i.w),t.updateMatrix(),t.updateWorldMatrix(!1,!1)))})),this.afterStep.next(e)}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(e){this.world.timestep=e,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((e,t,s)=>{this.collisionEvents.next({handle1:e,handle2:t,started:s}),this.collisionEvents.next({handle1:t,handle2:e,started:s})}))}rayTestFromCamera(e,t,s){this._raycaster.setFromCamera(ee,this.viewController.getCamera());const i=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(e).add(i);return this.rayTest(i,o,t,s)}rayTest(e,t,s,i){null==s&&(s=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(t,e),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),s;se(le.origin,e),se(le.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(le,r,!1,void 0,void 0,void 0,null!=i?.excludeActor?this.actorBodies.get(i.excludeActor.id):void 0,i?.excludeTriggers?e=>!e.isSensor():void 0);if(s.hasHit=null!=a,s.hasHit){const t=le.pointAt(a.timeOfImpact);s._internal=a,ie(s.hitNormal,a.normal),ie(s.hitPoint,t),s.distance=ne.subVectors(s.hitPoint,e).length();const i=this.world.bodies.getAll().find((e=>function(e,t){for(let s=0,i=e.numColliders();s<i;s++){const i=e.collider(s);if(t(i))return i}}(e,(e=>e===a.collider))));s.actor=null!=i?this.bodyActors.get(i):null}if(this.showDebug){const t=new h(n,e,r,i?.debugColor??255);this.gameWorld.scene.add(t),setTimeout((()=>this.gameWorld.scene.remove(t)),i?.debugLifetime??200)}return s}setGravity(e,t,s){this.world.gravity.x=e,this.world.gravity.y=t,this.world.gravity.z=s}getGravity(){return Y.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(e){this.addRecursively(e);for(const e of this.staticBodies.values())oe(e,(e=>e.setActiveEvents(s.ActiveEvents.COLLISION_EVENTS)))}addRecursively(e){if(this.removeSceneObject(e),!function(e){if(null!=e.userData?.src){const t=e.userData?.src;return"actor"===t.type}return!1}(e))if(e instanceof T&&null!=e.collisionShape){const t=this.createStaticBody(e,[e.collisionShape],e.physics);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else if(e instanceof A&&!1!==e.userData?.src?.collisionDetection)if(e.children[0]&&e.children[0].instanceMatrix)this.createForInstancedMesh(e.children[0],e.collisionShapes);else{const t=this.createStaticBody(e,e.collisionShapes,e.physics);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else e instanceof j?this.addLandscapeGroup(e):(e instanceof p||e instanceof v)&&e.children.forEach((e=>this.addRecursively(e)))}createForInstancedMesh(e,t){const s=new m,i=t.map((e=>e.source===z.rendered?e.withOffset(he):e));for(let t=0;t<e.count;t++){const o=new f;o.matrix.identity(),s.fromArray(e.instanceMatrix.array,16*t),o.applyMatrix4(s);this.createStaticBody(o,i)}}getCharacterController(e){return this.world?.createCharacterController(e)}getActorComputedMovement(e,t,s,o=null){const n=this.actorBodies.get(e.id);this.controlledActors.add(e.id);const r=n.collider(0);t.computeColliderMovement(r,s,i.EXCLUDE_SENSORS,o,ae);const a=t.computedMovement();return ie(re,a),re}setNextKinematicTranslation(e,t){const s=this.actorBodies.get(e.id),i=s.translation();i.x+=t.x,i.y+=t.y,i.z+=t.z,s?.setNextKinematicTranslation(i)}setAngularVelocity(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.setAngvel(Z,!0)}setLinearVelocity(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.setLinvel(Z,!0)}getLinearVelocity(e,t=new B){const s=this.actorBodies.get(e.id).linvel();return t.x=s.x,t.y=s.y,t.z=s.z,t}getAngularVelocity(e,t=new B){const s=this.actorBodies.get(e.id).angvel();return t.x=s.x,t.y=s.y,t.z=s.z,t}setLinearDamping(e,t){const s=this.actorBodies.get(e.id);s?.setLinearDamping(t)}setAngularDamping(e,t){const s=this.actorBodies.get(e.id);s?.setAngularDamping(t)}addLandscapeGroup(e){const t=e.userData.src,i=t.landscape.heightMaps;for(const n of e.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new B);if(t.landscape.holes&&t.landscape.holes.some((e=>e.m===n.name&&0!==e.w[0]))){const e=n.geometry.clone(),i=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(e.getAttribute("position").array);for(let e=0;e<a.length;e+=3)a[e]*=i.x,a[e+1]*=i.y,a[e+2]*=i.z;const c=e.index;for(let e=0;e<c.count;e+=3){const t=r.getX(c.getX(e)),s=r.getX(c.getY(e)),i=r.getX(c.getZ(e));(t>.5||s>.5||i>.5)&&(c.setX(e,0),c.setY(e,0),c.setZ(e,0))}const l=s.ColliderDesc.trimesh(a,new Uint32Array(e.getIndex().array));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(s.RigidBodyDesc.fixed()),t=new s.Vector3(0,0,0);se(t,o),e.setTranslation(t,!1),this.world.createCollider(l,e),this.staticBodies.set(n,e)}continue}const e=t.landscape.options.density+1,r=t.landscape.options.sectionSize,a=new Array(e);for(let t=0;t<e;t++)a[t]=new Array(e).fill(0);const c=i.find((e=>e.x===n.x&&e.y==n.y));if(null!=c)for(const t of c.points){if(null==a[t.i%e])continue;const s=e-1-Math.floor(t.i/e);s in a[t.i%e]?a[t.i%e][s]=t.y/r:console.warn("wrong index",{points:a,point:t,i:t.i%e,k:s,heightMap:c})}const l=t.landscape.options.density,d=a.flatMap((e=>e.reverse())),h=s.ColliderDesc.heightfield(l,l,new Float32Array(d),new s.Vector3(r,r,r));if(!1!==t.collisionDetection){const e=this.world.createRigidBody(s.RigidBodyDesc.fixed()),t=new s.Vector3(0,0,0);se(t,o),e.setTranslation(t,!1),this.world.createCollider(h,e),this.staticBodies.set(n,e)}}}setEnabled(e,t){const s=this.actorBodies.get(e.id);s?.setEnabled(t)}addActor(e,t,i={}){if(0==t.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(e);const o=e.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 e of t)this.addShape(r,e,o);oe(r,(e=>{null!=i.isTrigger&&(e.setSensor(i.isTrigger),e.setActiveCollisionTypes(s.ActiveCollisionTypes.ALL),e.setActiveEvents(s.ActiveEvents.COLLISION_EVENTS)),null!=i.friction&&e.setFriction(i.friction),null!=i.density&&e.setDensity(i.density),null!=i.mass&&e.setMass(i.mass),null!=i.restitution&&e.setRestitution(i.restitution)})),K(r,o),!0===i.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(e.id,r),this.bodyActors.set(r,e)}applyTorque(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.addTorque(Z,!0)}applyTorqueImpulse(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.applyTorqueImpulse(Z,!0)}resetForces(e){const t=this.actorBodies.get(e.id);t?.resetForces(!1)}resetTorques(e){const t=this.actorBodies.get(e.id);t?.resetTorques(!1)}applyForce(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.addForce(Z,!0)}applyImpulse(e,t){const s=this.actorBodies.get(e.id);Z.x=t.x,Z.y=t.y,Z.z=t.z,s?.applyImpulse(Z,!0)}applyLocalForce(e,t,s){const i=this.actorBodies.get(e.id);se(Z,t),null==s?i?.addForce(Z,!0):(se(J,s),i?.addForceAtPoint(Z,J,!0))}applyLocalImpulse(e,t,s){const i=this.actorBodies.get(e.id);se(Z,t),null==s?i.applyImpulse(Z,!0):(se(J,s),i.applyImpulseAtPoint(Z,J,!0))}applyRadiusImpulse(e,t,i){this.world.bodies.forEach((o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==s.RigidBodyType.Dynamic)return;const n=$;ie(n,o.translation());const r=n.clone().sub(e);if(r.length()>t)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(e){if(null==e)return;this.controlledActors.delete(e.id);const t=this.actorBodies.get(e.id);null!=t&&(this.bodyActors.delete(t),this.world.removeRigidBody(t)),this.actorBodies.delete(e.id)}removeRemoved(e){const t=new Set;e.traverse((e=>{t.add(e.uuid)}));for(const[e,s]of this.staticBodies.entries())!t.has(e.uuid)&&this.world.getRigidBody(s.handle)&&(this.staticBodies.delete(e),this.world.removeRigidBody(s))}removeSceneObject(e){if(e instanceof j){for(const t of e.sections)this.removeSceneObject(t);return}let t=this.staticBodies.get(e);null!=t&&this.world.getRigidBody(t.handle)&&this.world.removeRigidBody(t),this.staticBodies.delete(e)}activateActorEvents(e){this.actorBodies.get(e.id)}_onCollisionWithActorEvent(e,t,s){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((({started:e})=>e===s)),a((({handle1:e,handle2:t,started:s})=>({a1:this.bodyActors.get(this.world.getCollider(e)?.parent()),a2:this.bodyActors.get(this.world.getCollider(t)?.parent()),started:s}))),r((({a1:s,a2:i})=>null!=s&&null!=i&&s.id===e.id&&t(s,i))),a((({a2:e})=>e)))}onBeginContact(e){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((e=>e.started)),r((({handle1:t})=>{const s=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=s&&s.id===e.id})),a((e=>e.handle2)))}onEndContact(e){return this.activateActorEvents(e),this.collisionEvents.pipe(l(e.disposed),r((e=>!e.started)),r((({handle1:t})=>{const s=this.bodyActors.get(this.world.getCollider(t)?.parent());return null!=s&&s.id===e.id})),a((e=>e.handle2)))}onHasContactChanged(e){const t=new Set,s=new o(!1);return this.onBeginContact(e).subscribe((e=>{t.add(e),s.next(t.size>0)})),this.onEndContact(e).subscribe((e=>{t.delete(e),s.next(t.size>0)})),s.pipe(n())}onBeginOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>s instanceof t),!0)}onEndOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>s instanceof t),!1)}onBeginOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>t.id===s.id),!0)}onEndOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,s)=>t.id===s.id),!1)}onCollisionWithActor(e,t){return this.onBeginOverlapWithActor(e,t)}onCollisionWithActorType(e,t){return this.onBeginOverlapWithActorType(e,t)}updateActorTransform(e){const t=this.actorBodies.get(e.id);null!=t?K(t,e.object):console.warn("Actor has not been added to physics world",e)}setupWorld(){const e=new s.World({x:0,y:-9.81,z:0});this.world=e}getActorContacts(e,t){const i=this.actorBodies.get(e.id);if(i&&i.numColliders()>0){const o=i.collider(0);let n=o.shape,r=o.translation(),a=o.rotation(),c=t,l=.3;const d=this.world.castShape(r,a,c,n,.1,l,!0,null,null,null,this.actorBodies.get(e.id),(e=>e.shape.type!=s.ShapeType.HeightField));if(null!=d){const e=new B,t=new B,s=new B;return ie(e,d.witness2),ie(t,d.witness1),ie(s,d.normal1),s.negate(),[{ri:e,rj:t,ni:s}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world?.bodies.forEach((e=>this.world.removeRigidBody(e))),this.world?.free(),this.fixedupdateSub?.unsubscribe()}createStaticBody(e,t,i){const o=i?.type===PhysicsBodyType.dynamic?s.RigidBodyDesc.dynamic():s.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const s of t){if(null==s){console.warn("Collision shape is missing for object",e);continue}const o=this.addShape(n,s,e);null!=i?.friction&&o.setFriction(i.friction),null!=i?.density&&o.setDensity(i.density),null!=i?.mass&&o.setMass(i.mass/t.length),null!=i?.restitution&&o.setRestitution(i.restitution)}return K(n,e),n.userData=e.uuid,n}addShape(e,t,i){const o=i.getWorldScale(ce),n=this.createShape(t,o);null!=t.collisionGroup&&n.setCollisionGroups(t.collisionGroup),n.friction=t.friction??.1,null!=t.restitution&&(n.restitution=t.restitution),null!=t.density&&(n.density=t.density,n.massPropsMode=s.MassPropsMode.Density),null!=t.mass&&(n.mass=t.mass,n.massPropsMode=s.MassPropsMode.Mass);const r=t.offset.clone().multiply(o);se(n.translation,r);const a=(new w).setFromEuler(t.rotation);var c,l;t instanceof S&&t.mesh instanceof d.Mesh&&a.multiply(t.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,e)}createShape(e,t){if(e instanceof C)return s.ColliderDesc.cuboid(e.dimensions.x*t.x/2,e.dimensions.y*t.y/2,e.dimensions.z*t.z/2);if(e instanceof D){return s.ColliderDesc.capsule(e.length/2*t.y,e.radius*Math.max(t.z,t.x))}if(e instanceof F){const i=null!=e.geometry.getIndex()?e.geometry:P.mergeVertices(e.geometry),o=extractFloat32Array(i.getAttribute("position"));for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z;return s.ColliderDesc.trimesh(o,new Uint32Array(i.getIndex().array))}if(e instanceof S){let i;e.mesh instanceof d.Mesh?i=e.mesh.geometry:e.mesh instanceof d.BufferGeometry?i=e.mesh:console.log("Unknownd shape",{shapeInfo:e});const o=extractFloat32Array(i.getAttribute("position"));if(e.mesh instanceof d.Mesh){const t=I(e.mesh);for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z}for(let e=0;e<o.length;e+=3)o[e]*=t.x,o[e+1]*=t.y,o[e+2]*=t.z;const n=o;n.length;return s.ColliderDesc.convexHull(n)}if(e instanceof W){const i=2*t.x-t.y-t.z;return Math.abs(i)>.01?this.createShape(new S(new d.SphereGeometry(e.radius).scale(t.x,t.y,t.z)),new B(1,1,1)):s.ColliderDesc.ball(e.radius*Math.max(t.x,t.y,t.z))}return e instanceof R?s.ColliderDesc.cylinder(e.height/2*t.y,e.radiusTop*Math.max(t.z,t.x)):e instanceof M?s.ColliderDesc.cone(e.height*t.y,e.radiusBottom/2*Math.max(t.z,t.x)):e instanceof E?s.ColliderDesc.cuboid(e.width/2*t.x,e.height/2*t.y,.001):(console.error("Unsupported shape",e),s.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new s.CharacterCollision}};U=e([b(),t("design:paramtypes",[V,_])],U);export{U as PhysicsSystem};const H=new B,X=new d.Quaternion;function K(e,t){const i=t.getWorldPosition(H),o=t.getWorldQuaternion(X);e.setTranslation(new s.Vector3(i.x,i.y,i.z),!1),e.setRotation(new s.Quaternion(o.x,o.y,o.z,o.w),!1)}const Y=new B,Z=new s.Vector3(0,0,0),J=new s.Vector3(0,0,0),$=new B,ee=new d.Vector2,te=async()=>{let e=await import("@dimforge/rapier3d-compat");return await e.init(),e};function se(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function ie(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function oe(e,t){for(let s=0,i=e.numColliders();s<i;s++){t(e.collider(s))}}const ne=new B,re=new B,ae=e=>!e.isSensor(),ce=new B;const le=new s.Ray(new s.Vector3(0,0,0),new s.Vector3(0,1,0));let de=class extends k{constructor(){super(...arguments),this._active=!0,this.physics=N(U),this.world=N(_)}set active(e){this._active=e,e?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,e)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,e))}get active(){return this._active}};de=e([O()],de);export function extractFloat32Array(e){const t=e.itemSize,s=e.count,i=new Float32Array(s*t);for(let o=0;o<s;o++)for(let s=0;s<t;s++)i[o*t+s]=e.getComponent(o,s);return i}const he=new B;/*
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 v,Vector3 as B}from"three";import{Service as b}from"typedi";import{AssetMeshInstance as A}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as C,CapsuleCollisionShape as D,CollisionShapeSource as z,ConeCollisionShape as M,ConvexPolyhedronCollisionShape as S,CylinderCollisionShape as R,PhysicalShapeMesh as T,PlaneCollisionShape as E,SphereCollisionShape as F,TrimeshCollisionShape as j}from"../../../index.js";import{LandscapeGroup as W}from"../../../scene/landscape/landscape.js";import{ViewController as V}from"../render.js";import{World as _}from"../world.js";import*as P from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as I}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as L}from"./abstract-physics-system.js";import{ActorComponent as k,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 B,this.hitNormal=new B}}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 B,q=new B,Q=new w;let U=class extends L{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._raycaster=new x,this._reusableResult=new RayTestResult,this._raytestDiff=new B,this._raytestDirection=new B,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)}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 v&&(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 A&&!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 W?this.addLandscapeGroup(t):(t instanceof p||t instanceof v)&&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(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 B){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 B){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)}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 B);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 W){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 B,e=new B,s=new B;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 C)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 j){const i=null!=t.geometry.getIndex()?t.geometry:P.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=I(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 B(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 M?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 B,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 B,Z=new s.Vector3(0,0,0),J=new s.Vector3(0,0,0),$=new B,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 B,rt=new B,at=t=>!t.isSensor(),ct=new B;const lt=new s.Ray(new s.Vector3(0,0,0),new s.Vector3(0,1,0));let dt=class extends k{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 B;/*
2
2
  * Copyright (©) 2023. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */