hz-particles 1.5.1 → 1.5.2

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.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class $i{constructor(t={}){this.config=t,this._posOut=[0,0,0],this._rotMatrix=null,this._invRotMatrix=null,this._cachedRotX=void 0,this._cachedRotY=void 0,this._cachedRotZ=void 0}_updateRotationMatrix(){const t=this.config.emissionRotationX||0,e=this.config.emissionRotationY||0,i=this.config.emissionRotationZ||0;if(t===this._cachedRotX&&e===this._cachedRotY&&i===this._cachedRotZ)return;this._cachedRotX=t,this._cachedRotY=e,this._cachedRotZ=i;const r=t*Math.PI/180,n=e*Math.PI/180,a=i*Math.PI/180,o=Math.cos(r),c=Math.sin(r),l=Math.cos(n),d=Math.sin(n),S=Math.cos(a),b=Math.sin(a);this._rotMatrix=[l*S,c*d*S-o*b,o*d*S+c*b,l*b,c*d*b+o*S,o*d*b-c*S,-d,c*l,o*l],this._invRotMatrix=[this._rotMatrix[0],this._rotMatrix[3],this._rotMatrix[6],this._rotMatrix[1],this._rotMatrix[4],this._rotMatrix[7],this._rotMatrix[2],this._rotMatrix[5],this._rotMatrix[8]]}emitParticle(t,e,i){const r=this._posOut;if(this.config.emissionShape==="cube"||this.config.emissionShape==="box"?this._emitFromCube(r):this.config.emissionShape==="sphere"?this._emitFromSphere(r):this.config.emissionShape==="square"?this._emitFromSquare(r):this.config.emissionShape==="circle"?this._emitFromCircle(r):this.config.emissionShape==="cylinder"?this._emitFromCylinder(r):this.config.emissionShape==="plain"?this._emitFromPlain(r):this.config.emissionShape==="cone"?this._emitFromCone(r):this.config.emissionShape==="torus"?this._emitFromTorus(r):this.config.emissionShape==="line"?this._emitFromLine(r):this.config.emissionShape==="hemisphere"?this._emitFromHemisphere(r):this.config.emissionShape==="disc"?this._emitFromDisc(r):this.config.emissionShape==="annulus"?this._emitFromAnnulus(r):this.config.emissionShape==="capsule"?this._emitFromCapsule(r):this.config.emissionShape==="arc"?this._emitFromArc(r):this.config.emissionShape==="spiral"?this._emitFromSpiral(r):this.config.emissionShape==="frustum"?this._emitFromFrustum(r):this.config.emissionShape==="frustumSurface"?this._emitFromFrustumSurface(r):this.config.emissionShape==="cubeSurface"?this._emitFromCubeSurface(r):this.config.emissionShape==="sphereSurface"?this._emitFromSphereSurface(r):this.config.emissionShape==="boxFrame"?this._emitFromBoxFrame(r):this.config.emissionShape==="polygon"?this._emitFromPolygon(r):this.config.emissionShape==="rectangle"?this._emitFromRectangle(r):(r[0]=0,r[1]=0,r[2]=0),this.config.emissionRotationX||this.config.emissionRotationY||this.config.emissionRotationZ){this._updateRotationMatrix();const o=this._rotMatrix,c=r[0],l=r[1],d=r[2];r[0]=o[0]*c+o[1]*l+o[2]*d,r[1]=o[3]*c+o[4]*l+o[5]*d,r[2]=o[6]*c+o[7]*l+o[8]*d}(this.config.emissionPositionX||this.config.emissionPositionY||this.config.emissionPositionZ)&&(r[0]+=this.config.emissionPositionX||0,r[1]+=this.config.emissionPositionY||0,r[2]+=this.config.emissionPositionZ||0);const n=e*8;t[n]=r[0],t[n+1]=r[1],t[n+2]=r[2];const a=e*4;this.calculateVelocity(r[0],r[1],r[2],i,a),this.setParticleColor(t,n),this.setParticleLifetime(t,n)}applyRotation(t,e,i){this._updateRotationMatrix();const r=this._rotMatrix;return[r[0]*t+r[1]*e+r[2]*i,r[3]*t+r[4]*e+r[5]*i,r[6]*t+r[7]*e+r[8]*i]}inverseRotation(t,e,i){this._updateRotationMatrix();const r=this._invRotMatrix;return[r[0]*t+r[1]*e+r[2]*i,r[3]*t+r[4]*e+r[5]*i,r[6]*t+r[7]*e+r[8]*i]}_emitFromCube(t){let e=this.config.innerLength||0,i=this.config.outerLength||this.config.cubeLength;if(e>0){const r=Math.floor(Math.random()*6),n=Math.random()-.5,a=Math.random()-.5;let o,c,l;switch(r){case 0:o=n,c=a,l=.5;break;case 1:o=n,c=a,l=-.5;break;case 2:o=.5,c=n,l=a;break;case 3:o=-.5,c=n,l=a;break;case 4:o=n,c=.5,l=a;break;case 5:o=n,c=-.5,l=a;break}const d=Math.random(),S=e+d*(i-e);t[0]=o*S,t[1]=c*S,t[2]=l*S}else t[0]=(Math.random()-.5)*i,t[1]=(Math.random()-.5)*i,t[2]=(Math.random()-.5)*i}_emitFromSphere(t){const e=Math.random()*2*Math.PI,i=Math.acos(2*Math.random()-1),r=Math.sin(i)*Math.cos(e),n=Math.sin(i)*Math.sin(e),a=Math.cos(i);let o;this.config.innerRadius===0?o=this.config.outerRadius*Math.cbrt(Math.random()):o=this.config.innerRadius+(this.config.outerRadius-this.config.innerRadius)*Math.random(),t[0]=r*o,t[1]=n*o,t[2]=a*o}_emitFromSquare(t){const e=this.config.squareInnerSize||0,i=this.config.squareSize||2;if(e>0){const r=Math.floor(Math.random()*4);let n=e+(i-e)*Math.random();switch(r){case 0:t[0]=(Math.random()*2-1)*n,t[1]=n;break;case 1:t[0]=n,t[1]=(Math.random()*2-1)*n;break;case 2:t[0]=(Math.random()*2-1)*n,t[1]=-n;break;case 3:t[0]=-n,t[1]=(Math.random()*2-1)*n;break}}else t[0]=(Math.random()*2-1)*i,t[1]=(Math.random()*2-1)*i;t[2]=0}_emitFromCircle(t){const e=this.config.circleInnerRadius||0,i=this.config.circleOuterRadius||2,r=Math.random()*Math.PI*2;let n;e>0?n=e+(i-e)*Math.random():n=i*Math.sqrt(Math.random()),t[0]=Math.cos(r)*n,t[1]=Math.sin(r)*n,t[2]=0}_emitFromPlain(t){const e=this.config.planeWidth||2,i=this.config.planeDepth||2;t[0]=(Math.random()-.5)*e,t[1]=0,t[2]=(Math.random()-.5)*i}_emitFromCone(t){const e=this.config.coneInnerRadius||0,i=this.config.coneOuterRadius||2,r=this.config.coneHeight||4,n=Math.random()*Math.PI*2,a=Math.random(),o=a*r,c=i*(1-a);let l;if(e>0){const d=e*(1-a);l=d+(c-d)*Math.random()}else l=c*Math.sqrt(Math.random());t[0]=Math.cos(n)*l,t[1]=o,t[2]=Math.sin(n)*l}_emitFromTorus(t){const e=this.config.torusMajorRadius||2,i=this.config.torusMinorRadius||.5,r=Math.random()*Math.PI*2,n=Math.random()*Math.PI*2,a=i*Math.sqrt(Math.random());t[0]=(e+a*Math.cos(n))*Math.cos(r),t[1]=a*Math.sin(n),t[2]=(e+a*Math.cos(n))*Math.sin(r)}_emitFromLine(t){const e=this.config.lineLength||4,i=Math.random();t[0]=0,t[1]=(i-.5)*e,t[2]=0}_emitFromHemisphere(t){const e=this.config.hemisphereInnerRadius||0,i=this.config.hemisphereOuterRadius||2,r=Math.random()*Math.PI*2,n=Math.acos(Math.random()),a=Math.sin(n)*Math.cos(r),o=Math.cos(n),c=Math.sin(n)*Math.sin(r);let l;e>0?l=e+(i-e)*Math.random():l=i*Math.cbrt(Math.random()),t[0]=a*l,t[1]=o*l,t[2]=c*l}_emitFromDisc(t){const e=this.config.discRadius||2,i=Math.random()*Math.PI*2,r=e*Math.sqrt(Math.random());t[0]=Math.cos(i)*r,t[1]=0,t[2]=Math.sin(i)*r}_emitFromAnnulus(t){const e=this.config.annulusInnerRadius||1,i=this.config.annulusOuterRadius||2,r=Math.random()*Math.PI*2,n=e+(i-e)*Math.random();t[0]=Math.cos(r)*n,t[1]=0,t[2]=Math.sin(r)*n}_emitFromCapsule(t){const e=this.config.capsuleRadius||.5,i=this.config.capsuleHeight||4,r=i*.5,n=Math.PI*e*e*i,a=4/3*Math.PI*e*e*e,o=n/(n+a);if(Math.random()<o){const c=Math.random()*Math.PI*2,l=e*Math.sqrt(Math.random());t[0]=Math.cos(c)*l,t[1]=(Math.random()-.5)*i,t[2]=Math.sin(c)*l}else{const c=Math.random()*Math.PI*2,l=Math.acos(2*Math.random()-1),d=e*Math.cbrt(Math.random());t[0]=d*Math.sin(l)*Math.cos(c),t[1]=d*Math.cos(l),t[2]=d*Math.sin(l)*Math.sin(c),t[1]+=t[1]>=0?r:-r}}_emitFromArc(t){const e=this.config.arcStartAngle||0,i=this.config.arcEndAngle||180,r=this.config.arcInnerRadius||0,n=this.config.arcOuterRadius||2,a=e*Math.PI/180,o=i*Math.PI/180,c=a+Math.random()*(o-a);let l;r>0?l=r+(n-r)*Math.random():l=n*Math.sqrt(Math.random()),t[0]=Math.cos(c)*l,t[1]=Math.sin(c)*l,t[2]=0}_emitFromSpiral(t){const e=this.config.spiralTurns||3,i=this.config.spiralRadiusStart||.5,r=this.config.spiralRadiusEnd||2,n=this.config.spiralHeight||4,a=Math.random(),o=a*e*Math.PI*2,c=i+(r-i)*a;t[0]=Math.cos(o)*c,t[1]=(a-.5)*n,t[2]=Math.sin(o)*c}_emitFromFrustum(t){const e=this.config.frustumRadiusNear||.5,i=this.config.frustumRadiusFar||2,r=this.config.frustumHeight||4,n=Math.random()*Math.PI*2,a=Math.random(),o=a*r,l=(e+(i-e)*a)*Math.sqrt(Math.random());t[0]=Math.cos(n)*l,t[1]=o,t[2]=Math.sin(n)*l}_emitFromFrustumSurface(t){const e=this.config.frustumRadiusNear??.5,i=this.config.frustumRadiusFar??2,r=this.config.frustumHeight??4,n=Math.random()*Math.PI*2,a=i-e,o=e+a*.5;let c;if(Math.abs(a)<1e-6||o<=1e-6)c=Math.random();else{const S=Math.random(),b=.5*a,p=e,v=-S*o,E=Math.max(0,p*p-4*b*v);c=(-p+Math.sqrt(E))/(2*b),Number.isFinite(c)||(c=Math.random()),c=Math.min(1,Math.max(0,c))}const l=c*r,d=e+a*c;t[0]=Math.cos(n)*d,t[1]=l,t[2]=Math.sin(n)*d}_emitFromCubeSurface(t){const e=this.config.cubeSurfaceSize||2,i=e*.5,r=Math.floor(Math.random()*6),n=(Math.random()-.5)*e,a=(Math.random()-.5)*e;switch(r){case 0:t[0]=n,t[1]=a,t[2]=i;break;case 1:t[0]=n,t[1]=a,t[2]=-i;break;case 2:t[0]=i,t[1]=n,t[2]=a;break;case 3:t[0]=-i,t[1]=n,t[2]=a;break;case 4:t[0]=n,t[1]=i,t[2]=a;break;case 5:t[0]=n,t[1]=-i,t[2]=a;break}}_emitFromSphereSurface(t){const e=this.config.sphereSurfaceRadius||2,i=Math.random()*Math.PI*2,r=Math.acos(2*Math.random()-1);t[0]=e*Math.sin(r)*Math.cos(i),t[1]=e*Math.sin(r)*Math.sin(i),t[2]=e*Math.cos(r)}_emitFromBoxFrame(t){const e=this.config.boxFrameSize||2,i=e*.5,r=Math.floor(Math.random()*12),a=(Math.random()-.5)*e,o=[[-1,-1],[-1,1],[1,-1],[1,1]];if(r<4){const[c,l]=o[r];t[0]=a,t[1]=c*i,t[2]=l*i}else if(r<8){const[c,l]=o[r-4];t[0]=c*i,t[1]=a,t[2]=l*i}else{const[c,l]=o[r-8];t[0]=c*i,t[1]=l*i,t[2]=a}}_emitFromPolygon(t){const e=Math.max(3,Math.floor(this.config.polygonSides||6)),i=this.config.polygonRadius||2,r=Math.floor(Math.random()*e),n=r/e*Math.PI*2,a=(r+1)/e*Math.PI*2;let o=Math.random(),c=Math.random();o+c>1&&(o=1-o,c=1-c);const l=o*Math.cos(n)+c*Math.cos(a),d=o*Math.sin(n)+c*Math.sin(a);t[0]=l*i,t[1]=d*i,t[2]=0}_emitFromRectangle(t){const e=this.config.rectangleWidth||2,i=this.config.rectangleHeight||2;t[0]=(Math.random()-.5)*e,t[1]=(Math.random()-.5)*i,t[2]=0}_emitFromCylinder(t){const e=this.config.cylinderInnerRadius||0,i=this.config.cylinderOuterRadius||2,r=this.config.cylinderHeight||4,n=Math.random()*Math.PI*2;let a;e>0?a=e+(i-e)*Math.random():a=i*Math.sqrt(Math.random()),t[0]=Math.cos(n)*a,t[1]=(Math.random()-.5)*r,t[2]=Math.sin(n)*a}calculateVelocity(t,e,i,r,n){const a=this.config.emissionPositionX||0,o=this.config.emissionPositionY||0,c=this.config.emissionPositionZ||0,l=t-a,d=e-o,S=i-c,b=Math.sqrt(l*l+d*d+S*S);let p,v,E;if(b>1e-4){let z=!1;if(this.config.emissionShape==="circle"&&this.config.circleVelocityDirection==="tangential"){const _=this.inverseRotation(l,d,S),W=Math.sqrt(_[0]*_[0]+_[1]*_[1]);if(W>1e-4){const T=-_[1]/W,G=_[0]/W,F=this.applyRotation(T,G,0);p=F[0],v=F[1],E=F[2],z=!0}}else if(this.config.emissionShape==="cylinder"&&this.config.cylinderVelocityDirection==="tangential"){const _=this.inverseRotation(l,d,S),W=Math.sqrt(_[0]*_[0]+_[2]*_[2]);if(W>1e-4){const T=-_[2]/W,G=_[0]/W,F=this.applyRotation(T,0,G);p=F[0],v=F[1],E=F[2],z=!0}else{const T=Math.random()*Math.PI*2,G=this.applyRotation(Math.cos(T),0,Math.sin(T));p=G[0],v=G[1],E=G[2],z=!0}}z||(p=l/b,v=d/b,E=S/b)}else{const z=Math.random()*Math.PI*2,_=Math.acos(2*Math.random()-1);p=Math.sin(_)*Math.cos(z),v=Math.sin(_)*Math.sin(z),E=Math.cos(_)}let I;this.config.randomSpeed?I=(this.config.minSpeed||0)+Math.random()*((this.config.maxSpeed||1)-(this.config.minSpeed||0)):I=this.config.particleSpeed,r[n]=this.config.overrideXVelocity?this.config.xVelocity:p*I,r[n+1]=this.config.overrideYVelocity?this.config.yVelocity:v*I,r[n+2]=this.config.overrideZVelocity?this.config.zVelocity:E*I,r[n+3]=0}setParticleColor(t,e){if(this.config.randomColorEnabled&&this.config.randomColors.length>0){const i=this.config.randomColors,r=i[Math.floor(Math.random()*i.length)];t[e+3]=r[0],t[e+4]=r[1],t[e+5]=r[2]}else this.config.colorTransitionEnabled?(t[e+3]=this.config.startColor[0],t[e+4]=this.config.startColor[1],t[e+5]=this.config.startColor[2]):(t[e+3]=this.config.particleColor[0],t[e+4]=this.config.particleColor[1],t[e+5]=this.config.particleColor[2])}setParticleLifetime(t,e){const i=this.config.lifetime||5;t[e+6]=0,t[e+7]=i+(Math.random()*.4-.2)*i}}const Ji=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class Ji{constructor(t={}){this.config=t,this._posOut=[0,0,0],this._rotMatrix=null,this._invRotMatrix=null,this._cachedRotX=void 0,this._cachedRotY=void 0,this._cachedRotZ=void 0}_updateRotationMatrix(){const t=this.config.emissionRotationX||0,e=this.config.emissionRotationY||0,i=this.config.emissionRotationZ||0;if(t===this._cachedRotX&&e===this._cachedRotY&&i===this._cachedRotZ)return;this._cachedRotX=t,this._cachedRotY=e,this._cachedRotZ=i;const r=t*Math.PI/180,a=e*Math.PI/180,n=i*Math.PI/180,o=Math.cos(r),l=Math.sin(r),c=Math.cos(a),d=Math.sin(a),S=Math.cos(n),b=Math.sin(n);this._rotMatrix=[c*S,l*d*S-o*b,o*d*S+l*b,c*b,l*d*b+o*S,o*d*b-l*S,-d,l*c,o*c],this._invRotMatrix=[this._rotMatrix[0],this._rotMatrix[3],this._rotMatrix[6],this._rotMatrix[1],this._rotMatrix[4],this._rotMatrix[7],this._rotMatrix[2],this._rotMatrix[5],this._rotMatrix[8]]}emitParticle(t,e,i){const r=this._posOut;if(this.config.emissionShape==="cube"||this.config.emissionShape==="box"?this._emitFromCube(r):this.config.emissionShape==="sphere"?this._emitFromSphere(r):this.config.emissionShape==="square"?this._emitFromSquare(r):this.config.emissionShape==="circle"?this._emitFromCircle(r):this.config.emissionShape==="cylinder"?this._emitFromCylinder(r):this.config.emissionShape==="plain"?this._emitFromPlain(r):this.config.emissionShape==="cone"?this._emitFromCone(r):this.config.emissionShape==="torus"?this._emitFromTorus(r):this.config.emissionShape==="line"?this._emitFromLine(r):this.config.emissionShape==="hemisphere"?this._emitFromHemisphere(r):this.config.emissionShape==="disc"?this._emitFromDisc(r):this.config.emissionShape==="annulus"?this._emitFromAnnulus(r):this.config.emissionShape==="capsule"?this._emitFromCapsule(r):this.config.emissionShape==="arc"?this._emitFromArc(r):this.config.emissionShape==="spiral"?this._emitFromSpiral(r):this.config.emissionShape==="frustum"?this._emitFromFrustum(r):this.config.emissionShape==="frustumSurface"?this._emitFromFrustumSurface(r):this.config.emissionShape==="cubeSurface"?this._emitFromCubeSurface(r):this.config.emissionShape==="sphereSurface"?this._emitFromSphereSurface(r):this.config.emissionShape==="boxFrame"?this._emitFromBoxFrame(r):this.config.emissionShape==="polygon"?this._emitFromPolygon(r):this.config.emissionShape==="rectangle"?this._emitFromRectangle(r):(r[0]=0,r[1]=0,r[2]=0),this.config.emissionRotationX||this.config.emissionRotationY||this.config.emissionRotationZ){this._updateRotationMatrix();const o=this._rotMatrix,l=r[0],c=r[1],d=r[2];r[0]=o[0]*l+o[1]*c+o[2]*d,r[1]=o[3]*l+o[4]*c+o[5]*d,r[2]=o[6]*l+o[7]*c+o[8]*d}(this.config.emissionPositionX||this.config.emissionPositionY||this.config.emissionPositionZ)&&(r[0]+=this.config.emissionPositionX||0,r[1]+=this.config.emissionPositionY||0,r[2]+=this.config.emissionPositionZ||0);const a=e*8;t[a]=r[0],t[a+1]=r[1],t[a+2]=r[2];const n=e*4;this.calculateVelocity(r[0],r[1],r[2],i,n),this.setParticleColor(t,a),this.setParticleLifetime(t,a)}applyRotation(t,e,i){this._updateRotationMatrix();const r=this._rotMatrix;return[r[0]*t+r[1]*e+r[2]*i,r[3]*t+r[4]*e+r[5]*i,r[6]*t+r[7]*e+r[8]*i]}inverseRotation(t,e,i){this._updateRotationMatrix();const r=this._invRotMatrix;return[r[0]*t+r[1]*e+r[2]*i,r[3]*t+r[4]*e+r[5]*i,r[6]*t+r[7]*e+r[8]*i]}_emitFromCube(t){let e=this.config.innerLength||0,i=this.config.outerLength||this.config.cubeLength;if(e>0){const r=Math.floor(Math.random()*6),a=Math.random()-.5,n=Math.random()-.5;let o,l,c;switch(r){case 0:o=a,l=n,c=.5;break;case 1:o=a,l=n,c=-.5;break;case 2:o=.5,l=a,c=n;break;case 3:o=-.5,l=a,c=n;break;case 4:o=a,l=.5,c=n;break;case 5:o=a,l=-.5,c=n;break}const d=Math.random(),S=e+d*(i-e);t[0]=o*S,t[1]=l*S,t[2]=c*S}else t[0]=(Math.random()-.5)*i,t[1]=(Math.random()-.5)*i,t[2]=(Math.random()-.5)*i}_emitFromSphere(t){const e=Math.random()*2*Math.PI,i=Math.acos(2*Math.random()-1),r=Math.sin(i)*Math.cos(e),a=Math.sin(i)*Math.sin(e),n=Math.cos(i);let o;this.config.innerRadius===0?o=this.config.outerRadius*Math.cbrt(Math.random()):o=this.config.innerRadius+(this.config.outerRadius-this.config.innerRadius)*Math.random(),t[0]=r*o,t[1]=a*o,t[2]=n*o}_emitFromSquare(t){const e=this.config.squareInnerSize||0,i=this.config.squareSize||2;if(e>0){const r=Math.floor(Math.random()*4);let a=e+(i-e)*Math.random();switch(r){case 0:t[0]=(Math.random()*2-1)*a,t[1]=a;break;case 1:t[0]=a,t[1]=(Math.random()*2-1)*a;break;case 2:t[0]=(Math.random()*2-1)*a,t[1]=-a;break;case 3:t[0]=-a,t[1]=(Math.random()*2-1)*a;break}}else t[0]=(Math.random()*2-1)*i,t[1]=(Math.random()*2-1)*i;t[2]=0}_emitFromCircle(t){const e=this.config.circleInnerRadius||0,i=this.config.circleOuterRadius||2,r=Math.random()*Math.PI*2;let a;e>0?a=e+(i-e)*Math.random():a=i*Math.sqrt(Math.random()),t[0]=Math.cos(r)*a,t[1]=Math.sin(r)*a,t[2]=0}_emitFromPlain(t){const e=this.config.planeWidth||2,i=this.config.planeDepth||2;t[0]=(Math.random()-.5)*e,t[1]=0,t[2]=(Math.random()-.5)*i}_emitFromCone(t){const e=this.config.coneInnerRadius||0,i=this.config.coneOuterRadius||2,r=this.config.coneHeight||4,a=Math.random()*Math.PI*2,n=Math.random(),o=n*r,l=i*(1-n);let c;if(e>0){const d=e*(1-n);c=d+(l-d)*Math.random()}else c=l*Math.sqrt(Math.random());t[0]=Math.cos(a)*c,t[1]=o,t[2]=Math.sin(a)*c}_emitFromTorus(t){const e=this.config.torusMajorRadius||2,i=this.config.torusMinorRadius||.5,r=Math.random()*Math.PI*2,a=Math.random()*Math.PI*2,n=i*Math.sqrt(Math.random());t[0]=(e+n*Math.cos(a))*Math.cos(r),t[1]=n*Math.sin(a),t[2]=(e+n*Math.cos(a))*Math.sin(r)}_emitFromLine(t){const e=this.config.lineLength||4,i=Math.random();t[0]=0,t[1]=(i-.5)*e,t[2]=0}_emitFromHemisphere(t){const e=this.config.hemisphereInnerRadius||0,i=this.config.hemisphereOuterRadius||2,r=Math.random()*Math.PI*2,a=Math.acos(Math.random()),n=Math.sin(a)*Math.cos(r),o=Math.cos(a),l=Math.sin(a)*Math.sin(r);let c;e>0?c=e+(i-e)*Math.random():c=i*Math.cbrt(Math.random()),t[0]=n*c,t[1]=o*c,t[2]=l*c}_emitFromDisc(t){const e=this.config.discRadius||2,i=Math.random()*Math.PI*2,r=e*Math.sqrt(Math.random());t[0]=Math.cos(i)*r,t[1]=0,t[2]=Math.sin(i)*r}_emitFromAnnulus(t){const e=this.config.annulusInnerRadius||1,i=this.config.annulusOuterRadius||2,r=Math.random()*Math.PI*2,a=e+(i-e)*Math.random();t[0]=Math.cos(r)*a,t[1]=0,t[2]=Math.sin(r)*a}_emitFromCapsule(t){const e=this.config.capsuleRadius||.5,i=this.config.capsuleHeight||4,r=i*.5,a=Math.PI*e*e*i,n=4/3*Math.PI*e*e*e,o=a/(a+n);if(Math.random()<o){const l=Math.random()*Math.PI*2,c=e*Math.sqrt(Math.random());t[0]=Math.cos(l)*c,t[1]=(Math.random()-.5)*i,t[2]=Math.sin(l)*c}else{const l=Math.random()*Math.PI*2,c=Math.acos(2*Math.random()-1),d=e*Math.cbrt(Math.random());t[0]=d*Math.sin(c)*Math.cos(l),t[1]=d*Math.cos(c),t[2]=d*Math.sin(c)*Math.sin(l),t[1]+=t[1]>=0?r:-r}}_emitFromArc(t){const e=this.config.arcStartAngle||0,i=this.config.arcEndAngle||180,r=this.config.arcInnerRadius||0,a=this.config.arcOuterRadius||2,n=e*Math.PI/180,o=i*Math.PI/180,l=n+Math.random()*(o-n);let c;r>0?c=r+(a-r)*Math.random():c=a*Math.sqrt(Math.random()),t[0]=Math.cos(l)*c,t[1]=Math.sin(l)*c,t[2]=0}_emitFromSpiral(t){const e=this.config.spiralTurns||3,i=this.config.spiralRadiusStart||.5,r=this.config.spiralRadiusEnd||2,a=this.config.spiralHeight||4,n=Math.random(),o=n*e*Math.PI*2,l=i+(r-i)*n;t[0]=Math.cos(o)*l,t[1]=(n-.5)*a,t[2]=Math.sin(o)*l}_emitFromFrustum(t){const e=this.config.frustumRadiusNear||.5,i=this.config.frustumRadiusFar||2,r=this.config.frustumHeight||4,a=Math.random()*Math.PI*2,n=Math.random(),o=n*r,c=(e+(i-e)*n)*Math.sqrt(Math.random());t[0]=Math.cos(a)*c,t[1]=o,t[2]=Math.sin(a)*c}_emitFromFrustumSurface(t){const e=this.config.frustumRadiusNear??.5,i=this.config.frustumRadiusFar??2,r=this.config.frustumHeight??4,a=Math.random()*Math.PI*2,n=i-e,o=e+n*.5;let l;if(Math.abs(n)<1e-6||o<=1e-6)l=Math.random();else{const S=Math.random(),b=.5*n,h=e,v=-S*o,C=Math.max(0,h*h-4*b*v);l=(-h+Math.sqrt(C))/(2*b),Number.isFinite(l)||(l=Math.random()),l=Math.min(1,Math.max(0,l))}const c=l*r,d=e+n*l;t[0]=Math.cos(a)*d,t[1]=c,t[2]=Math.sin(a)*d}_emitFromCubeSurface(t){const e=this.config.cubeSurfaceSize||2,i=e*.5,r=Math.floor(Math.random()*6),a=(Math.random()-.5)*e,n=(Math.random()-.5)*e;switch(r){case 0:t[0]=a,t[1]=n,t[2]=i;break;case 1:t[0]=a,t[1]=n,t[2]=-i;break;case 2:t[0]=i,t[1]=a,t[2]=n;break;case 3:t[0]=-i,t[1]=a,t[2]=n;break;case 4:t[0]=a,t[1]=i,t[2]=n;break;case 5:t[0]=a,t[1]=-i,t[2]=n;break}}_emitFromSphereSurface(t){const e=this.config.sphereSurfaceRadius||2,i=Math.random()*Math.PI*2,r=Math.acos(2*Math.random()-1);t[0]=e*Math.sin(r)*Math.cos(i),t[1]=e*Math.sin(r)*Math.sin(i),t[2]=e*Math.cos(r)}_emitFromBoxFrame(t){const e=this.config.boxFrameSize||2,i=e*.5,r=Math.floor(Math.random()*12),n=(Math.random()-.5)*e,o=[[-1,-1],[-1,1],[1,-1],[1,1]];if(r<4){const[l,c]=o[r];t[0]=n,t[1]=l*i,t[2]=c*i}else if(r<8){const[l,c]=o[r-4];t[0]=l*i,t[1]=n,t[2]=c*i}else{const[l,c]=o[r-8];t[0]=l*i,t[1]=c*i,t[2]=n}}_emitFromPolygon(t){const e=Math.max(3,Math.floor(this.config.polygonSides||6)),i=this.config.polygonRadius||2,r=Math.floor(Math.random()*e),a=r/e*Math.PI*2,n=(r+1)/e*Math.PI*2;let o=Math.random(),l=Math.random();o+l>1&&(o=1-o,l=1-l);const c=o*Math.cos(a)+l*Math.cos(n),d=o*Math.sin(a)+l*Math.sin(n);t[0]=c*i,t[1]=d*i,t[2]=0}_emitFromRectangle(t){const e=this.config.rectangleWidth||2,i=this.config.rectangleHeight||2;t[0]=(Math.random()-.5)*e,t[1]=(Math.random()-.5)*i,t[2]=0}_emitFromCylinder(t){const e=this.config.cylinderInnerRadius||0,i=this.config.cylinderOuterRadius||2,r=this.config.cylinderHeight||4,a=Math.random()*Math.PI*2;let n;e>0?n=e+(i-e)*Math.random():n=i*Math.sqrt(Math.random()),t[0]=Math.cos(a)*n,t[1]=(Math.random()-.5)*r,t[2]=Math.sin(a)*n}calculateVelocity(t,e,i,r,a){const n=this.config.emissionPositionX||0,o=this.config.emissionPositionY||0,l=this.config.emissionPositionZ||0,c=t-n,d=e-o,S=i-l,b=Math.sqrt(c*c+d*d+S*S);let h,v,C;if(b>1e-4){let D=!1;if(this.config.emissionShape==="circle"&&this.config.circleVelocityDirection==="tangential"){const _=this.inverseRotation(c,d,S),Z=Math.sqrt(_[0]*_[0]+_[1]*_[1]);if(Z>1e-4){const T=-_[1]/Z,G=_[0]/Z,F=this.applyRotation(T,G,0);h=F[0],v=F[1],C=F[2],D=!0}}else if(this.config.emissionShape==="cylinder"&&this.config.cylinderVelocityDirection==="tangential"){const _=this.inverseRotation(c,d,S),Z=Math.sqrt(_[0]*_[0]+_[2]*_[2]);if(Z>1e-4){const T=-_[2]/Z,G=_[0]/Z,F=this.applyRotation(T,0,G);h=F[0],v=F[1],C=F[2],D=!0}else{const T=Math.random()*Math.PI*2,G=this.applyRotation(Math.cos(T),0,Math.sin(T));h=G[0],v=G[1],C=G[2],D=!0}}D||(h=c/b,v=d/b,C=S/b)}else{const D=Math.random()*Math.PI*2,_=Math.acos(2*Math.random()-1);h=Math.sin(_)*Math.cos(D),v=Math.sin(_)*Math.sin(D),C=Math.cos(_)}let z;this.config.randomSpeed?z=(this.config.minSpeed||0)+Math.random()*((this.config.maxSpeed||1)-(this.config.minSpeed||0)):z=this.config.particleSpeed,r[a]=this.config.overrideXVelocity?this.config.xVelocity:h*z,r[a+1]=this.config.overrideYVelocity?this.config.yVelocity:v*z,r[a+2]=this.config.overrideZVelocity?this.config.zVelocity:C*z,r[a+3]=0}setParticleColor(t,e){if(this.config.randomColorEnabled&&this.config.randomColors.length>0){const i=this.config.randomColors,r=i[Math.floor(Math.random()*i.length)];t[e+3]=r[0],t[e+4]=r[1],t[e+5]=r[2]}else this.config.colorTransitionEnabled?(t[e+3]=this.config.startColor[0],t[e+4]=this.config.startColor[1],t[e+5]=this.config.startColor[2]):(t[e+3]=this.config.particleColor[0],t[e+4]=this.config.particleColor[1],t[e+5]=this.config.particleColor[2])}setParticleLifetime(t,e){const i=this.config.lifetime||5;t[e+6]=0,t[e+7]=i+(Math.random()*.4-.2)*i}}const Ki=`
2
2
  struct Uniforms {
3
3
  transform: mat4x4<f32>,
4
4
  cameraPosition: vec3<f32>,
@@ -79,8 +79,26 @@
79
79
  @location(3) noiseOffset : vec2<f32>,
80
80
  }
81
81
 
82
+ // Hachage SANS TRANSCENDANTAL (Dave Hoskins, « Hash without Sine »).
83
+ //
84
+ // ⚠️ LE fract(sin(dot(...))) QU'IL REMPLACE ÉTAIT LE PREMIER POSTE DE COÛT DE CE SHADER. Il est
85
+ // appelé QUATRE fois par valueNoise, et la distorsion en appelle DEUX : huit sin par pixel couvert.
86
+ // Sur un GPU mobile, sin n'est pas une instruction à un cycle — elle est souvent émulée, et elle
87
+ // domine tout le reste du fragment.
88
+ //
89
+ // ⚠️ ET AUCUN ACCENT GRAVE DANS CE COMMENTAIRE : on est à l'intérieur d'un littéral gabarit
90
+ // JavaScript. Un seul le referme, et le shader entier devient une erreur de syntaxe.
91
+ //
92
+ // Mesuré sur la map du propriétaire : 27 nuages additifs de 4,2 m qui se recouvrent, soit ~19 écrans
93
+ // pleins de pixels couverts — donc ~150 sin par pixel d'écran et par image. Il rapportait
94
+ // « ça lag pour de pauvres nuages », et éteindre le bruit supprimait le lag.
95
+ //
96
+ // Le remplaçant tient en trois lignes de fract/dot, sans aucune fonction transcendantale, et
97
+ // garde les mêmes propriétés statistiques (distribution uniforme, décorrélation spatiale).
82
98
  fn hash21(p: vec2<f32>) -> f32 {
83
- return fract(sin(dot(p, vec2<f32>(127.1, 311.7))) * 43758.5453);
99
+ var p3 = fract(vec3<f32>(p.x, p.y, p.x) * 0.1031);
100
+ p3 = p3 + dot(p3, vec3<f32>(p3.y, p3.z, p3.x) + 33.33);
101
+ return fract((p3.x + p3.y) * p3.z);
84
102
  }
85
103
 
86
104
  fn valueNoise(p: vec2<f32>) -> f32 {
@@ -422,7 +440,7 @@
422
440
  return vec4<f32>(input.color, alpha);
423
441
  }
424
442
  }
425
- `,Ki=`
443
+ `,Qi=`
426
444
  struct BloomUniforms {
427
445
  direction: vec2<f32>,
428
446
  resolution: vec2<f32>,
@@ -482,7 +500,7 @@
482
500
 
483
501
  return result / totalWeight * 1.1;
484
502
  }
485
- `,Qi=`
503
+ `,es=`
486
504
  struct BloomIntensityUniforms {
487
505
  intensity: f32,
488
506
  color: vec3<f32>,
@@ -528,7 +546,7 @@
528
546
 
529
547
  return vec4<f32>(originalColor.rgb + (mappedBloom * bloomUniforms.intensity), originalColor.a);
530
548
  }
531
- `,es=`
549
+ `,ts=`
532
550
  struct BloomIntensityUniforms {
533
551
  intensity: f32,
534
552
  color: vec3<f32>,
@@ -569,7 +587,7 @@
569
587
  fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
570
588
  return textureSample(originalTexture, texSampler, input.texCoord);
571
589
  }
572
- `,pr=`
590
+ `,mr=`
573
591
  @binding(0) @group(0) var texSampler: sampler;
574
592
  @binding(1) @group(0) var originalTexture: texture_2d<f32>;
575
593
  @binding(2) @group(0) var blurredTexture: texture_2d<f32>;
@@ -601,7 +619,7 @@
601
619
  let c = textureSample(originalTexture, texSampler, input.texCoord);
602
620
  return vec4<f32>(aces(c.rgb), c.a);
603
621
  }
604
- `,ts=`
622
+ `,is=`
605
623
  struct PhysicsUniforms {
606
624
  deltaTime: f32,
607
625
  particleSpeed: f32,
@@ -811,7 +829,7 @@
811
829
  particleBuffer[baseIndex + 1u] = newPos.y;
812
830
  particleBuffer[baseIndex + 2u] = newPos.z;
813
831
  }
814
- `,hr=`
832
+ `,yr=`
815
833
  @group(0) @binding(0) var<storage, read> restData: array<f32>;
816
834
  @group(0) @binding(1) var<storage, read> jointWeightsData: array<f32>;
817
835
  @group(0) @binding(2) var<storage, read> jointIndicesData: array<u32>;
@@ -867,7 +885,7 @@
867
885
  outputData[outBase + 6u] = uv_u;
868
886
  outputData[outBase + 7u] = uv_v;
869
887
  }
870
- `;class is{constructor(t,e=1e4){this.device=t,this.physicsSettings={deltaTime:.016,gravity:0,turbulence:0,attractorStrength:0,attractorPosition:[0,0,0],damping:0,confinementEnabled:!1,confinementShape:"box",confinementMode:"bounce",confinementSpace:"world",confinementBoxHalfSize:[2,2,2],confinementSphereRadius:3,confinementRestitution:.8,confinementFriction:.1,confinementCenter:[0,0,0],softBoundaryEnabled:!1,softBoundaryStrength:5,softBoundaryFalloff:.5},this.fixedDeltaTime=1/60,this.physicsClock=0,this.physicsAccumulator=0,this.minUpdatesPerSecond=30,this.lastUpdateTime=0,this.computeReady=!1,this.computePipeline=null,this.computeBindGroupLayout=null,this._physicsData=new Float32Array(32),this._physicsDataU32View=new Uint32Array(this._physicsData.buffer),this.physicsUniformBuffer=t.createBuffer({size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"physicsUniformBuffer"}),this._maxParticles=e,this._particleDataStagingBuffer=t.createBuffer({size:e*8*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"ParticleDataReadbackBuffer_Pooled"}),this._velocityStagingBuffer=t.createBuffer({size:e*4*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"VelocityReadbackBuffer_Pooled"}),this._stagingInUse=!1,this._renderStagingParticleBuffer=t.createBuffer({size:e*8*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"RenderReadback_ParticleData"}),this._renderStagingVelocityBuffer=t.createBuffer({size:e*4*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"RenderReadback_Velocity"}),this._renderStagingInUse=!1,this._scriptStagingParticleBuffer=t.createBuffer({size:e*8*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"ScriptReadback_ParticleData"}),this._scriptStagingVelocityBuffer=t.createBuffer({size:e*4*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"ScriptReadback_Velocity"}),this._scriptStagingInUse=!1}async initComputePipeline(t,e,i){try{return await this.createComputePipeline(t,e,i),this.computeReady=!0,!0}catch(r){return console.error("Error initializing compute pipeline:",r),!1}}async createComputePipeline(t,e,i){this.computeBindGroupLayout=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.computePipeline=this.device.createComputePipeline({layout:this.device.createPipelineLayout({bindGroupLayouts:[this.computeBindGroupLayout]}),compute:{module:this.device.createShaderModule({code:ts}),entryPoint:"main"}}),this.computeBindGroup=this.device.createBindGroup({layout:this.computeBindGroupLayout,entries:[{binding:0,resource:{buffer:this.physicsUniformBuffer}},{binding:1,resource:{buffer:t}},{binding:2,resource:{buffer:e}},{binding:3,resource:{buffer:i}}]})}updatePhysics(t,e,i,r,n,a){if(e<=0||!this.computeReady)return;const o=this._physicsData,c=this.physicsSettings;o[0]=t,o[1]=i.particleSpeed,o[2]=c.gravity,o[3]=c.turbulence,o[4]=c.attractorStrength,o[5]=c.damping,o[6]=c.attractorPosition[0],o[7]=c.attractorPosition[1],o[8]=c.attractorPosition[2],this._physicsDataU32View[9]=e,o[10]=c.confinementEnabled?1:0,o[11]=c.confinementShape==="sphere"?1:0,o[12]=c.confinementMode==="kill"?1:0,o[13]=c.confinementSpace==="local"?1:0,o[14]=c.confinementBoxHalfSize[0],o[15]=c.confinementBoxHalfSize[1],o[16]=c.confinementBoxHalfSize[2],o[17]=c.confinementSphereRadius,o[18]=c.confinementRestitution,o[19]=c.confinementFriction,o[20]=c.confinementCenter[0],o[21]=c.confinementCenter[1],o[22]=c.confinementCenter[2],o[23]=c.softBoundaryEnabled?1:0,o[24]=c.softBoundaryStrength,o[25]=c.softBoundaryFalloff,o[26]=i.velocityStretchEnabled?1:0,o[27]=i.velocityStretchFactor??1,o[28]=0,o[29]=0,o[30]=0,o[31]=0,this.device.queue.writeBuffer(this.physicsUniformBuffer,0,o);const l=a||this.device.createCommandEncoder({label:"ParticlePhysicsEncoder"}),d=l.beginComputePass({label:"ParticlePhysicsPass"});d.setPipeline(this.computePipeline),d.setBindGroup(0,this.computeBindGroup);const S=Math.max(1,Math.ceil(e/64));d.dispatchWorkgroups(S,1,1),d.end(),a||this.device.queue.submit([l.finish()]),this.lastUpdateTime=performance.now()/1e3}async readbackAndProcessParticles(t,e,i,r,n){if(t<=0)return{activeCount:0,shouldUpdate:!1};if(this._stagingInUse)return{activeCount:t,shouldUpdate:!1};try{this._stagingInUse=!0;const a=this.device.createCommandEncoder({label:"ParticleReadbackEncoder"}),o=t*8*4;a.copyBufferToBuffer(r,0,this._particleDataStagingBuffer,0,o);const c=t*4*4;return a.copyBufferToBuffer(n,0,this._velocityStagingBuffer,0,c),this.device.queue.submit([a.finish()]),await Promise.all([(async()=>{await this._particleDataStagingBuffer.mapAsync(GPUMapMode.READ,0,o);const l=new Float32Array(this._particleDataStagingBuffer.getMappedRange(0,o));e.set(l),this._particleDataStagingBuffer.unmap()})(),(async()=>{await this._velocityStagingBuffer.mapAsync(GPUMapMode.READ,0,c);const l=new Float32Array(this._velocityStagingBuffer.getMappedRange(0,c));i.set(l),this._velocityStagingBuffer.unmap()})()]),this._stagingInUse=!1,{particleData:e,particleVelocities:i,shouldUpdate:!0}}catch(a){return this._stagingInUse=!1,a&&a.name==="AbortError"||console.error("Error reading back particle data:",a),{activeCount:t,shouldUpdate:!1}}}setDamping(t){this.physicsSettings.damping=t}setGravity(t){this.physicsSettings.gravity=t}setAttractor(t,e,i=!1){const r=Math.abs(t||0);this.physicsSettings.attractorStrength=i?-r:r,this.physicsSettings.attractorPosition=e}setConfinement(t){const e=this.physicsSettings;t.enabled!==void 0&&(e.confinementEnabled=t.enabled),t.shape!==void 0&&(e.confinementShape=t.shape),t.mode!==void 0&&(e.confinementMode=t.mode),t.space!==void 0&&(e.confinementSpace=t.space),t.boxSize!==void 0&&(e.confinementBoxHalfSize=t.boxSize),t.sphereRadius!==void 0&&(e.confinementSphereRadius=t.sphereRadius),t.restitution!==void 0&&(e.confinementRestitution=t.restitution),t.friction!==void 0&&(e.confinementFriction=t.friction),t.center!==void 0&&(e.confinementCenter=t.center)}async readbackForRendering(t,e,i,r,n){if(t<=0)return{shouldUpdate:!1};if(this._renderStagingInUse)return{shouldUpdate:!1};try{this._renderStagingInUse=!0;const a=t*8*4,o=t*4*4,c=this.device.createCommandEncoder({label:"RenderReadbackEncoder"});return c.copyBufferToBuffer(r,0,this._renderStagingParticleBuffer,0,a),c.copyBufferToBuffer(n,0,this._renderStagingVelocityBuffer,0,o),this.device.queue.submit([c.finish()]),await Promise.all([(async()=>{await this._renderStagingParticleBuffer.mapAsync(GPUMapMode.READ,0,a);const l=new Float32Array(this._renderStagingParticleBuffer.getMappedRange(0,a));e.set(l),this._renderStagingParticleBuffer.unmap()})(),(async()=>{await this._renderStagingVelocityBuffer.mapAsync(GPUMapMode.READ,0,o);const l=new Float32Array(this._renderStagingVelocityBuffer.getMappedRange(0,o));i.set(l),this._renderStagingVelocityBuffer.unmap()})()]),this._renderStagingInUse=!1,{particleData:e,particleVelocities:i,shouldUpdate:!0}}catch(a){return this._renderStagingInUse=!1,console.error("Error in rendering readback:",a),{shouldUpdate:!1}}}async readbackForScript(t,e,i,r,n){if(t<=0)return{shouldUpdate:!1};if(this._scriptStagingInUse)return{shouldUpdate:!1};try{this._scriptStagingInUse=!0;const a=t*8*4,o=t*4*4,c=this.device.createCommandEncoder({label:"ScriptReadbackEncoder"});return c.copyBufferToBuffer(r,0,this._scriptStagingParticleBuffer,0,a),c.copyBufferToBuffer(n,0,this._scriptStagingVelocityBuffer,0,o),this.device.queue.submit([c.finish()]),await Promise.all([(async()=>{await this._scriptStagingParticleBuffer.mapAsync(GPUMapMode.READ,0,a);const l=new Float32Array(this._scriptStagingParticleBuffer.getMappedRange(0,a));e.set(l),this._scriptStagingParticleBuffer.unmap()})(),(async()=>{await this._scriptStagingVelocityBuffer.mapAsync(GPUMapMode.READ,0,o);const l=new Float32Array(this._scriptStagingVelocityBuffer.getMappedRange(0,o));i.set(l),this._scriptStagingVelocityBuffer.unmap()})()]),this._scriptStagingInUse=!1,{shouldUpdate:!0}}catch(a){return this._scriptStagingInUse=!1,console.error("Error in script readback:",a),{shouldUpdate:!1}}}destroy(){this.physicsUniformBuffer.destroy(),this._particleDataStagingBuffer.destroy(),this._velocityStagingBuffer.destroy(),this._renderStagingParticleBuffer.destroy(),this._renderStagingVelocityBuffer.destroy(),this._scriptStagingParticleBuffer.destroy(),this._scriptStagingVelocityBuffer.destroy()}setSoftBoundary(t){const e=this.physicsSettings;t.enabled!==void 0&&(e.softBoundaryEnabled=t.enabled),t.strength!==void 0&&(e.softBoundaryStrength=t.strength),t.falloff!==void 0&&(e.softBoundaryFalloff=t.falloff)}}class ss{constructor(t){this.device=t,this.defaultTexture=null,this.createDefaultTexture()}createDefaultTexture(){const t=new Uint8Array([255,255,255,255]);this.defaultTexture=this.device.createTexture({size:[1,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:"defaultParticleTexture"}),this.device.queue.writeTexture({texture:this.defaultTexture},t,{bytesPerRow:4},[1,1])}async loadTexture(t){const e=this.device.createTexture({size:[t.width,t.height],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,label:"particleTexture"});return this.device.queue.copyExternalImageToTexture({source:t},{texture:e},[t.width,t.height]),e}getDefaultTexture(){return this.defaultTexture}destroyTexture(t){t&&t.label!=="defaultParticleTexture"&&t.destroy()}}const rs=Object.freeze({sin:Math.sin,cos:Math.cos,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,min:Math.min,max:Math.max,sqrt:Math.sqrt,pow:Math.pow,random:Math.random,PI:Math.PI,TAU:Math.PI*2,clamp(s,t,e){return s<t?t:s>e?e:s},lerp(s,t,e){return s+(t-s)*e},smoothstep(s,t,e){const i=rs.clamp((e-s)/(t-s),0,1);return i*i*(3-2*i)}}),Ct=new Set(["particleSize","particleSpeed","particleColor","startColor","endColor","opacity","emissionRate","gravityStrength","dampingStrength","attractorStrength","attractorReverse","attractorPosition","pulseAmplitude","pulseFrequency","bloomIntensity","emissionPositionX","emissionPositionY","emissionPositionZ","emissionRotationX","emissionRotationY","emissionRotationZ","circleInnerRadius","circleOuterRadius","discRadius","annulusInnerRadius","annulusOuterRadius","arcStartAngle","arcEndAngle","arcInnerRadius","arcOuterRadius","squareSize","rectangleWidth","rectangleHeight","planeWidth","planeDepth","lineLength","polygonRadius","shapeStrokeWidth","shapeStrokeAmplitude","shapeStrokeFrequency","shapeStrokeSpeed"]);class mr{constructor(t){this._collection=t,this._pd=null,this._vd=null,this._pi=0,this._vi=0}_bind(t,e,i){return this._pd=t,this._vd=e,this._pi=i*8,this._vi=i*4,this}get x(){return this._pd[this._pi]}set x(t){this._pd[this._pi]=t,this._collection._dirty=!0}get y(){return this._pd[this._pi+1]}set y(t){this._pd[this._pi+1]=t,this._collection._dirty=!0}get z(){return this._pd[this._pi+2]}set z(t){this._pd[this._pi+2]=t,this._collection._dirty=!0}get r(){return this._pd[this._pi+3]}set r(t){this._pd[this._pi+3]=t,this._collection._dirty=!0}get g(){return this._pd[this._pi+4]}set g(t){this._pd[this._pi+4]=t,this._collection._dirty=!0}get b(){return this._pd[this._pi+5]}set b(t){this._pd[this._pi+5]=t,this._collection._dirty=!0}get age(){return this._pd[this._pi+6]}set age(t){this._pd[this._pi+6]=t,this._collection._dirty=!0}get lifetime(){return this._pd[this._pi+7]}set lifetime(t){this._pd[this._pi+7]=t,this._collection._dirty=!0}get vx(){return this._vd[this._vi]}set vx(t){this._vd[this._vi]=t,this._collection._dirty=!0}get vy(){return this._vd[this._vi+1]}set vy(t){this._vd[this._vi+1]=t,this._collection._dirty=!0}get vz(){return this._vd[this._vi+2]}set vz(t){this._vd[this._vi+2]=t,this._collection._dirty=!0}}class yr{constructor(){this._proxy=new mr(this),this._pd=null,this._vd=null,this.count=0,this._dirty=!1}_bind(t,e,i){this._pd=t,this._vd=e,this.count=i,this._dirty=!1}get(t){return t<0||t>=this.count?null:this._proxy._bind(this._pd,this._vd,t)}}const gr=1e6;function br(s){let t=0;return s.replace(/\b(for|while)\s*\([^)]*\)\s*\{/g,e=>{const i=`__lc${t++}`;return`${e} if(++${i}>${gr})throw new Error("Loop limit exceeded");`}).replace(/\b(for|while)\s*\([^)]*\)\s*\{/g,e=>e).replace(/^/,()=>{let e="";for(let i=0;i<t;i++)e+=`let __lc${i}=0;`;return e})}const ni=new Map;for(const s of Ct)ni.set(s.toLowerCase(),s);function Sr(s){const t={value:!1},e=new Set;return new Proxy(s,{get(r,n){if(n==="__dirty")return t.value;if(n==="__resetDirty")return()=>{t.value=!1};if(typeof n!="string")return;if(Ct.has(n))return r[n];const a=ni.get(n.toLowerCase());if(a)return e.has(n)||(e.add(n),console.warn(`[ParticleScript] config.${n} → did you mean config.${a}?`)),r[a]},set(r,n,a){if(typeof n!="string")return!0;let o=n;if(!Ct.has(o)){const c=ni.get(o.toLowerCase());if(c)e.has(n)||(e.add(n),console.warn(`[ParticleScript] config.${n} → did you mean config.${c}?`)),o=c;else return!0}return r[o]=a,t.value=!0,!0}})}class ai{constructor(t,e,i){this._particles=new yr,this._configProxy=Sr(e),this._configSnapshot=null,this._fn=null,this._error=!1,this.compile(t)}compile(t){if(this._fn=null,this._error=!1,!(!t||typeof t!="string"))try{const i=`
888
+ `;class ss{constructor(t,e=1e4){this.device=t,this.physicsSettings={deltaTime:.016,gravity:0,turbulence:0,attractorStrength:0,attractorPosition:[0,0,0],damping:0,confinementEnabled:!1,confinementShape:"box",confinementMode:"bounce",confinementSpace:"world",confinementBoxHalfSize:[2,2,2],confinementSphereRadius:3,confinementRestitution:.8,confinementFriction:.1,confinementCenter:[0,0,0],softBoundaryEnabled:!1,softBoundaryStrength:5,softBoundaryFalloff:.5},this.fixedDeltaTime=1/60,this.physicsClock=0,this.physicsAccumulator=0,this.minUpdatesPerSecond=30,this.lastUpdateTime=0,this.computeReady=!1,this.computePipeline=null,this.computeBindGroupLayout=null,this._physicsData=new Float32Array(32),this._physicsDataU32View=new Uint32Array(this._physicsData.buffer),this.physicsUniformBuffer=t.createBuffer({size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"physicsUniformBuffer"}),this._maxParticles=e,this._particleDataStagingBuffer=t.createBuffer({size:e*8*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"ParticleDataReadbackBuffer_Pooled"}),this._velocityStagingBuffer=t.createBuffer({size:e*4*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"VelocityReadbackBuffer_Pooled"}),this._stagingInUse=!1,this._renderStagingParticleBuffer=t.createBuffer({size:e*8*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"RenderReadback_ParticleData"}),this._renderStagingVelocityBuffer=t.createBuffer({size:e*4*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"RenderReadback_Velocity"}),this._renderStagingInUse=!1,this._scriptStagingParticleBuffer=t.createBuffer({size:e*8*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"ScriptReadback_ParticleData"}),this._scriptStagingVelocityBuffer=t.createBuffer({size:e*4*4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"ScriptReadback_Velocity"}),this._scriptStagingInUse=!1}async initComputePipeline(t,e,i){try{return await this.createComputePipeline(t,e,i),this.computeReady=!0,!0}catch(r){return console.error("Error initializing compute pipeline:",r),!1}}async createComputePipeline(t,e,i){this.computeBindGroupLayout=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.computePipeline=this.device.createComputePipeline({layout:this.device.createPipelineLayout({bindGroupLayouts:[this.computeBindGroupLayout]}),compute:{module:this.device.createShaderModule({code:is}),entryPoint:"main"}}),this.computeBindGroup=this.device.createBindGroup({layout:this.computeBindGroupLayout,entries:[{binding:0,resource:{buffer:this.physicsUniformBuffer}},{binding:1,resource:{buffer:t}},{binding:2,resource:{buffer:e}},{binding:3,resource:{buffer:i}}]})}updatePhysics(t,e,i,r,a,n){if(e<=0||!this.computeReady)return;const o=this._physicsData,l=this.physicsSettings;o[0]=t,o[1]=i.particleSpeed,o[2]=l.gravity,o[3]=l.turbulence,o[4]=l.attractorStrength,o[5]=l.damping,o[6]=l.attractorPosition[0],o[7]=l.attractorPosition[1],o[8]=l.attractorPosition[2],this._physicsDataU32View[9]=e,o[10]=l.confinementEnabled?1:0,o[11]=l.confinementShape==="sphere"?1:0,o[12]=l.confinementMode==="kill"?1:0,o[13]=l.confinementSpace==="local"?1:0,o[14]=l.confinementBoxHalfSize[0],o[15]=l.confinementBoxHalfSize[1],o[16]=l.confinementBoxHalfSize[2],o[17]=l.confinementSphereRadius,o[18]=l.confinementRestitution,o[19]=l.confinementFriction,o[20]=l.confinementCenter[0],o[21]=l.confinementCenter[1],o[22]=l.confinementCenter[2],o[23]=l.softBoundaryEnabled?1:0,o[24]=l.softBoundaryStrength,o[25]=l.softBoundaryFalloff,o[26]=i.velocityStretchEnabled?1:0,o[27]=i.velocityStretchFactor??1,o[28]=0,o[29]=0,o[30]=0,o[31]=0,this.device.queue.writeBuffer(this.physicsUniformBuffer,0,o);const c=n||this.device.createCommandEncoder({label:"ParticlePhysicsEncoder"}),d=c.beginComputePass({label:"ParticlePhysicsPass"});d.setPipeline(this.computePipeline),d.setBindGroup(0,this.computeBindGroup);const S=Math.max(1,Math.ceil(e/64));d.dispatchWorkgroups(S,1,1),d.end(),n||this.device.queue.submit([c.finish()]),this.lastUpdateTime=performance.now()/1e3}async readbackAndProcessParticles(t,e,i,r,a){if(t<=0)return{activeCount:0,shouldUpdate:!1};if(this._stagingInUse)return{activeCount:t,shouldUpdate:!1};try{this._stagingInUse=!0;const n=this.device.createCommandEncoder({label:"ParticleReadbackEncoder"}),o=t*8*4;n.copyBufferToBuffer(r,0,this._particleDataStagingBuffer,0,o);const l=t*4*4;return n.copyBufferToBuffer(a,0,this._velocityStagingBuffer,0,l),this.device.queue.submit([n.finish()]),await Promise.all([(async()=>{await this._particleDataStagingBuffer.mapAsync(GPUMapMode.READ,0,o);const c=new Float32Array(this._particleDataStagingBuffer.getMappedRange(0,o));e.set(c),this._particleDataStagingBuffer.unmap()})(),(async()=>{await this._velocityStagingBuffer.mapAsync(GPUMapMode.READ,0,l);const c=new Float32Array(this._velocityStagingBuffer.getMappedRange(0,l));i.set(c),this._velocityStagingBuffer.unmap()})()]),this._stagingInUse=!1,{particleData:e,particleVelocities:i,shouldUpdate:!0}}catch(n){return this._stagingInUse=!1,n&&n.name==="AbortError"||console.error("Error reading back particle data:",n),{activeCount:t,shouldUpdate:!1}}}setDamping(t){this.physicsSettings.damping=t}setGravity(t){this.physicsSettings.gravity=t}setAttractor(t,e,i=!1){const r=Math.abs(t||0);this.physicsSettings.attractorStrength=i?-r:r,this.physicsSettings.attractorPosition=e}setConfinement(t){const e=this.physicsSettings;t.enabled!==void 0&&(e.confinementEnabled=t.enabled),t.shape!==void 0&&(e.confinementShape=t.shape),t.mode!==void 0&&(e.confinementMode=t.mode),t.space!==void 0&&(e.confinementSpace=t.space),t.boxSize!==void 0&&(e.confinementBoxHalfSize=t.boxSize),t.sphereRadius!==void 0&&(e.confinementSphereRadius=t.sphereRadius),t.restitution!==void 0&&(e.confinementRestitution=t.restitution),t.friction!==void 0&&(e.confinementFriction=t.friction),t.center!==void 0&&(e.confinementCenter=t.center)}async readbackForRendering(t,e,i,r,a){if(t<=0)return{shouldUpdate:!1};if(this._renderStagingInUse)return{shouldUpdate:!1};try{this._renderStagingInUse=!0;const n=t*8*4,o=t*4*4,l=this.device.createCommandEncoder({label:"RenderReadbackEncoder"});return l.copyBufferToBuffer(r,0,this._renderStagingParticleBuffer,0,n),l.copyBufferToBuffer(a,0,this._renderStagingVelocityBuffer,0,o),this.device.queue.submit([l.finish()]),await Promise.all([(async()=>{await this._renderStagingParticleBuffer.mapAsync(GPUMapMode.READ,0,n);const c=new Float32Array(this._renderStagingParticleBuffer.getMappedRange(0,n));e.set(c),this._renderStagingParticleBuffer.unmap()})(),(async()=>{await this._renderStagingVelocityBuffer.mapAsync(GPUMapMode.READ,0,o);const c=new Float32Array(this._renderStagingVelocityBuffer.getMappedRange(0,o));i.set(c),this._renderStagingVelocityBuffer.unmap()})()]),this._renderStagingInUse=!1,{particleData:e,particleVelocities:i,shouldUpdate:!0}}catch(n){return this._renderStagingInUse=!1,console.error("Error in rendering readback:",n),{shouldUpdate:!1}}}async readbackForScript(t,e,i,r,a){if(t<=0)return{shouldUpdate:!1};if(this._scriptStagingInUse)return{shouldUpdate:!1};try{this._scriptStagingInUse=!0;const n=t*8*4,o=t*4*4,l=this.device.createCommandEncoder({label:"ScriptReadbackEncoder"});return l.copyBufferToBuffer(r,0,this._scriptStagingParticleBuffer,0,n),l.copyBufferToBuffer(a,0,this._scriptStagingVelocityBuffer,0,o),this.device.queue.submit([l.finish()]),await Promise.all([(async()=>{await this._scriptStagingParticleBuffer.mapAsync(GPUMapMode.READ,0,n);const c=new Float32Array(this._scriptStagingParticleBuffer.getMappedRange(0,n));e.set(c),this._scriptStagingParticleBuffer.unmap()})(),(async()=>{await this._scriptStagingVelocityBuffer.mapAsync(GPUMapMode.READ,0,o);const c=new Float32Array(this._scriptStagingVelocityBuffer.getMappedRange(0,o));i.set(c),this._scriptStagingVelocityBuffer.unmap()})()]),this._scriptStagingInUse=!1,{shouldUpdate:!0}}catch(n){return this._scriptStagingInUse=!1,console.error("Error in script readback:",n),{shouldUpdate:!1}}}destroy(){this.physicsUniformBuffer.destroy(),this._particleDataStagingBuffer.destroy(),this._velocityStagingBuffer.destroy(),this._renderStagingParticleBuffer.destroy(),this._renderStagingVelocityBuffer.destroy(),this._scriptStagingParticleBuffer.destroy(),this._scriptStagingVelocityBuffer.destroy()}setSoftBoundary(t){const e=this.physicsSettings;t.enabled!==void 0&&(e.softBoundaryEnabled=t.enabled),t.strength!==void 0&&(e.softBoundaryStrength=t.strength),t.falloff!==void 0&&(e.softBoundaryFalloff=t.falloff)}}class rs{constructor(t){this.device=t,this.defaultTexture=null,this.createDefaultTexture()}createDefaultTexture(){const t=new Uint8Array([255,255,255,255]);this.defaultTexture=this.device.createTexture({size:[1,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:"defaultParticleTexture"}),this.device.queue.writeTexture({texture:this.defaultTexture},t,{bytesPerRow:4},[1,1])}async loadTexture(t){const e=this.device.createTexture({size:[t.width,t.height],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,label:"particleTexture"});return this.device.queue.copyExternalImageToTexture({source:t},{texture:e},[t.width,t.height]),e}getDefaultTexture(){return this.defaultTexture}destroyTexture(t){t&&t.label!=="defaultParticleTexture"&&t.destroy()}}const as=Object.freeze({sin:Math.sin,cos:Math.cos,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,min:Math.min,max:Math.max,sqrt:Math.sqrt,pow:Math.pow,random:Math.random,PI:Math.PI,TAU:Math.PI*2,clamp(s,t,e){return s<t?t:s>e?e:s},lerp(s,t,e){return s+(t-s)*e},smoothstep(s,t,e){const i=as.clamp((e-s)/(t-s),0,1);return i*i*(3-2*i)}}),Ct=new Set(["particleSize","particleSpeed","particleColor","startColor","endColor","opacity","emissionRate","gravityStrength","dampingStrength","attractorStrength","attractorReverse","attractorPosition","pulseAmplitude","pulseFrequency","bloomIntensity","emissionPositionX","emissionPositionY","emissionPositionZ","emissionRotationX","emissionRotationY","emissionRotationZ","circleInnerRadius","circleOuterRadius","discRadius","annulusInnerRadius","annulusOuterRadius","arcStartAngle","arcEndAngle","arcInnerRadius","arcOuterRadius","squareSize","rectangleWidth","rectangleHeight","planeWidth","planeDepth","lineLength","polygonRadius","shapeStrokeWidth","shapeStrokeAmplitude","shapeStrokeFrequency","shapeStrokeSpeed"]);class gr{constructor(t){this._collection=t,this._pd=null,this._vd=null,this._pi=0,this._vi=0}_bind(t,e,i){return this._pd=t,this._vd=e,this._pi=i*8,this._vi=i*4,this}get x(){return this._pd[this._pi]}set x(t){this._pd[this._pi]=t,this._collection._dirty=!0}get y(){return this._pd[this._pi+1]}set y(t){this._pd[this._pi+1]=t,this._collection._dirty=!0}get z(){return this._pd[this._pi+2]}set z(t){this._pd[this._pi+2]=t,this._collection._dirty=!0}get r(){return this._pd[this._pi+3]}set r(t){this._pd[this._pi+3]=t,this._collection._dirty=!0}get g(){return this._pd[this._pi+4]}set g(t){this._pd[this._pi+4]=t,this._collection._dirty=!0}get b(){return this._pd[this._pi+5]}set b(t){this._pd[this._pi+5]=t,this._collection._dirty=!0}get age(){return this._pd[this._pi+6]}set age(t){this._pd[this._pi+6]=t,this._collection._dirty=!0}get lifetime(){return this._pd[this._pi+7]}set lifetime(t){this._pd[this._pi+7]=t,this._collection._dirty=!0}get vx(){return this._vd[this._vi]}set vx(t){this._vd[this._vi]=t,this._collection._dirty=!0}get vy(){return this._vd[this._vi+1]}set vy(t){this._vd[this._vi+1]=t,this._collection._dirty=!0}get vz(){return this._vd[this._vi+2]}set vz(t){this._vd[this._vi+2]=t,this._collection._dirty=!0}}class br{constructor(){this._proxy=new gr(this),this._pd=null,this._vd=null,this.count=0,this._dirty=!1}_bind(t,e,i){this._pd=t,this._vd=e,this.count=i,this._dirty=!1}get(t){return t<0||t>=this.count?null:this._proxy._bind(this._pd,this._vd,t)}}const Sr=1e6;function xr(s){let t=0;return s.replace(/\b(for|while)\s*\([^)]*\)\s*\{/g,e=>{const i=`__lc${t++}`;return`${e} if(++${i}>${Sr})throw new Error("Loop limit exceeded");`}).replace(/\b(for|while)\s*\([^)]*\)\s*\{/g,e=>e).replace(/^/,()=>{let e="";for(let i=0;i<t;i++)e+=`let __lc${i}=0;`;return e})}const ai=new Map;for(const s of Ct)ai.set(s.toLowerCase(),s);function vr(s){const t={value:!1},e=new Set;return new Proxy(s,{get(r,a){if(a==="__dirty")return t.value;if(a==="__resetDirty")return()=>{t.value=!1};if(typeof a!="string")return;if(Ct.has(a))return r[a];const n=ai.get(a.toLowerCase());if(n)return e.has(a)||(e.add(a),console.warn(`[ParticleScript] config.${a} → did you mean config.${n}?`)),r[n]},set(r,a,n){if(typeof a!="string")return!0;let o=a;if(!Ct.has(o)){const l=ai.get(o.toLowerCase());if(l)e.has(a)||(e.add(a),console.warn(`[ParticleScript] config.${a} → did you mean config.${l}?`)),o=l;else return!0}return r[o]=n,t.value=!0,!0}})}class ni{constructor(t,e,i){this._particles=new br,this._configProxy=vr(e),this._configSnapshot=null,this._fn=null,this._error=!1,this.compile(t)}compile(t){if(this._fn=null,this._error=!1,!(!t||typeof t!="string"))try{const i=`
871
889
  return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles, __config, __math) {
872
890
  var window = void 0, document = void 0, globalThis = void 0;
873
891
  var Function = void 0, eval = void 0, fetch = void 0;
@@ -875,8 +893,8 @@ return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles,
875
893
  var deltaTime = __deltaTime, time = __time;
876
894
  var currentFrame = __currentFrame, totalFrames = __totalFrames;
877
895
  var particles = __particles, config = __config, math = __math;
878
- ${br(t)}
879
- };`,r=new Function(i);this._fn=r()}catch(e){console.warn("[ParticleScript] Compilation error:",e.message),this._fn=null,this._error=!0}}execute(t,e,i,r,n,a,o){if(!this._fn||this._error)return{configDirty:!1,particlesDirty:!1};this._particles._bind(n,a,o),this._configProxy.__resetDirty();try{this._fn(t,e,i,r,this._particles,this._configProxy,rs)}catch(c){console.warn("[ParticleScript] Runtime error:",c.message)}return{configDirty:this._configProxy.__dirty,particlesDirty:this._particles._dirty}}snapshotConfig(t){const e={};for(const i of Ct){const r=t[i];r!==void 0&&(e[i]=Array.isArray(r)?[...r]:r)}this._configSnapshot=e}restoreConfig(t){if(this._configSnapshot){for(const e of Ct)if(e in this._configSnapshot){const i=this._configSnapshot[e];t[e]=Array.isArray(i)?[...i]:i}}}destroy(){this._fn=null,this._particles=null,this._configProxy=null,this._configSnapshot=null}}async function ns(s){const t=new DataView(s);if(t.getUint32(0,!0)!==1179937895)throw new Error("Invalid GLB file: incorrect magic number");const i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i} (only version 2 is supported)`);const r=t.getUint32(8,!0);let n=12,a=null,o=null;for(;n<r;){const T=t.getUint32(n,!0),G=t.getUint32(n+4,!0),F=s.slice(n+8,n+8+T);if(G===1313821514){const re=new TextDecoder("utf-8").decode(F);a=JSON.parse(re)}else G===5130562&&(o=F);n+=8+T}if(!a)throw new Error("GLB file missing JSON chunk");if(!a.meshes||a.meshes.length===0)throw new Error("GLB file contains no meshes");const l=a.meshes[0].primitives[0];if(!l)throw new Error("First mesh has no primitives");const d=l.attributes.POSITION;if(d===void 0)throw new Error("Mesh primitive missing POSITION attribute");const S=si(a,o,d,3,5126);let b;if(l.attributes.NORMAL!==void 0)b=si(a,o,l.attributes.NORMAL,3,5126);else{const T=l.indices;if(T===void 0)throw new Error("Cannot generate normals without indices");const G=Xi(a,o,T);b=xr(S,G)}const p=l.indices;if(p===void 0)throw new Error("Mesh primitive missing indices");const v=Xi(a,o,p),E=S.length/3,I=v.length;let z=null;l.attributes.TEXCOORD_0!==void 0&&(z=si(a,o,l.attributes.TEXCOORD_0,2,5126));let _=!1;if(a.materials&&a.materials.length>0){const T=a.materials[0];T.pbrMetallicRoughness&&T.pbrMetallicRoughness.baseColorTexture!==void 0&&(_=!0)}let W=null;if(a.skins&&a.skins.length>0)try{W=Br(a,o,l),globalThis.__HZFX_DEBUG&&console.log("Animation data extracted:",W)}catch(T){console.warn("Failed to extract animation data:",T)}return{positions:S,normals:b,indices:v,texCoords:z,vertexCount:E,indexCount:I,animationData:W,hasBaseColorTexture:_}}function si(s,t,e,i,r){const n=s.accessors[e],o={SCALAR:1,VEC2:2,VEC3:3,VEC4:4}[n.type];if(o!==i)throw new Error(`Attribute accessor type mismatch: expected ${i} components, got ${o}`);if(n.componentType!==r)throw new Error(`Attribute component type mismatch: expected ${r}, got ${n.componentType}`);const l=(s.bufferViews[n.bufferView].byteOffset||0)+(n.byteOffset||0),d=n.count,S=new DataView(t,l,d*i*4),b=new Float32Array(d*i);for(let p=0;p<d*i;p++)b[p]=S.getFloat32(p*4,!0);return b}function Xi(s,t,e){const i=s.accessors[e];if(i.type!=="SCALAR")throw new Error(`Indices accessor must be SCALAR, got ${i.type}`);const n=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),a=i.count;if(i.componentType===5123){const o=new DataView(t,n,a*2),c=new Uint16Array(a);for(let l=0;l<a;l++)c[l]=o.getUint16(l*2,!0);return c}else if(i.componentType===5125){const o=new DataView(t,n,a*4),c=new Uint32Array(a);for(let l=0;l<a;l++)c[l]=o.getUint32(l*4,!0);return c}else throw new Error(`Unsupported index component type: ${i.componentType}`)}function xr(s,t){const e=new Float32Array(s.length);for(let i=0;i<t.length;i+=3){const r=t[i]*3,n=t[i+1]*3,a=t[i+2]*3,o=[s[r],s[r+1],s[r+2]],c=[s[n],s[n+1],s[n+2]],l=[s[a],s[a+1],s[a+2]],d=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],S=[l[0]-o[0],l[1]-o[1],l[2]-o[2]],b=[d[1]*S[2]-d[2]*S[1],d[2]*S[0]-d[0]*S[2],d[0]*S[1]-d[1]*S[0]],p=Math.sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]);p>0&&(b[0]/=p,b[1]/=p,b[2]/=p),e[r]=e[n]=e[a]=b[0],e[r+1]=e[n+1]=e[a+1]=b[1],e[r+2]=e[n+2]=e[a+2]=b[2]}return e}function vr(s,t,e){const i=s.accessors[e];if(i.type!=="VEC4")throw new Error(`JOINTS_0 must be VEC4, got ${i.type}`);const n=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),a=i.count;if(i.componentType===5121){const o=new DataView(t,n,a*4),c=new Uint8Array(a*4);for(let l=0;l<a*4;l++)c[l]=o.getUint8(l);return c}else if(i.componentType===5123){const o=new DataView(t,n,a*8),c=new Uint8Array(a*4);for(let l=0;l<a*4;l++)c[l]=o.getUint16(l*2,!0);return c}else throw new Error(`Unsupported JOINTS_0 component type: ${i.componentType}`)}function Pr(s,t,e){const i=s.accessors[e];if(i.type!=="VEC4")throw new Error(`WEIGHTS_0 must be VEC4, got ${i.type}`);const n=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),a=i.count;if(i.componentType===5126){const o=new DataView(t,n,a*16),c=new Float32Array(a*4);for(let l=0;l<a*4;l++)c[l]=o.getFloat32(l*4,!0);return c}else if(i.componentType===5121){const o=new DataView(t,n,a*4),c=new Float32Array(a*4);for(let l=0;l<a*4;l++)c[l]=o.getUint8(l)/255;return c}else throw new Error(`Unsupported WEIGHTS_0 component type: ${i.componentType}`)}function _r(s,t,e){const i=s.accessors[e];if(i.type!=="MAT4")throw new Error(`Expected MAT4, got ${i.type}`);if(i.componentType!==5126)throw new Error(`Expected FLOAT component type for MAT4, got ${i.componentType}`);const n=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),a=i.count,o=new DataView(t,n,a*64),c=new Float32Array(a*16);for(let l=0;l<a*16;l++)c[l]=o.getFloat32(l*4,!0);return c}function Mr(s,t,e){const i=s.accessors[e];if(i.type!=="SCALAR")throw new Error(`Expected SCALAR, got ${i.type}`);if(i.componentType!==5126)throw new Error(`Expected FLOAT component type for SCALAR, got ${i.componentType}`);const n=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),a=i.count,o=new DataView(t,n,a*4),c=new Float32Array(a);for(let l=0;l<a;l++)c[l]=o.getFloat32(l*4,!0);return c}function wr(s,t,e){const i=s.accessors[e],n={VEC3:3,VEC4:4}[i.type];if(!n)throw new Error(`Expected VEC3 or VEC4, got ${i.type}`);if(i.componentType!==5126)throw new Error(`Expected FLOAT component type, got ${i.componentType}`);const o=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),c=i.count,l=new DataView(t,o,c*n*4),d=new Float32Array(c*n);for(let S=0;S<c*n;S++)d[S]=l.getFloat32(S*4,!0);return d}function Br(s,t,e){const i=s.skins[0],r=i.joints,n=_r(s,t,i.inverseBindMatrices),a=e.attributes.JOINTS_0!==void 0?vr(s,t,e.attributes.JOINTS_0):null,o=e.attributes.WEIGHTS_0!==void 0?Pr(s,t,e.attributes.WEIGHTS_0):null;if(!a||!o)throw new Error("Mesh missing JOINTS_0 or WEIGHTS_0 attributes");const c=s.nodes.map(d=>({translation:d.translation||[0,0,0],rotation:d.rotation||[0,0,0,1],scale:d.scale||[1,1,1],children:d.children||[],name:d.name||""})),l=[];if(s.animations&&s.animations.length>0)for(const d of s.animations){const S=[];let b=0;for(const p of d.channels){const v=d.samplers[p.sampler],E=Mr(s,t,v.input),I=wr(s,t,v.output),z=E[E.length-1];z>b&&(b=z),S.push({targetNode:p.target.node,targetPath:p.target.path,interpolation:v.interpolation||"LINEAR",timestamps:E,values:I})}l.push({name:d.name||`Animation ${l.length}`,duration:b,channels:S})}return{joints:r,inverseBindMatrices:n,jointIndices:a,jointWeights:o,nodes:c,animations:l}}async function oi(s){const t=new DataView(s);if(t.getUint32(0,!0)!==1179937895)throw new Error("Invalid GLB file: incorrect magic number");const i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);const r=t.getUint32(8,!0);let n=12,a=null,o=null;for(;n<r;){const W=t.getUint32(n,!0),T=t.getUint32(n+4,!0),G=s.slice(n+8,n+8+W);if(T===1313821514){const Z=new TextDecoder("utf-8").decode(G);a=JSON.parse(Z)}else T===5130562&&(o=G);n+=8+W}if(!a)throw new Error("GLB file missing JSON chunk");if(!a.materials||a.materials.length===0)return null;const c=a.materials[0];if(!c.pbrMetallicRoughness||c.pbrMetallicRoughness.baseColorTexture===void 0)return null;const l=c.pbrMetallicRoughness.baseColorTexture.index;if(!a.textures||!a.textures[l])return null;const S=a.textures[l].source;if(S===void 0||!a.images||!a.images[S])return null;const b=a.images[S],p=b.mimeType||"image/png";if(b.bufferView===void 0)return null;if(!o)throw new Error("GLB file missing BIN chunk (required for embedded textures)");const v=a.bufferViews[b.bufferView],E=v.byteOffset||0,I=v.byteLength,z=o.slice(E,E+I);return{imageBlob:new Blob([z],{type:p}),mimeType:p}}function Rr(s,t,e,i){return i=i||[0,0,0],i[0]=s[0]+(t[0]-s[0])*e,i[1]=s[1]+(t[1]-s[1])*e,i[2]=s[2]+(t[2]-s[2])*e,i}function Tr(s,t,e,i){i=i||[0,0,0,0];let r=s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3],n=1;if(r<0&&(r=-r,n=-1),r>.9995){i[0]=s[0]+(n*t[0]-s[0])*e,i[1]=s[1]+(n*t[1]-s[1])*e,i[2]=s[2]+(n*t[2]-s[2])*e,i[3]=s[3]+(n*t[3]-s[3])*e;const d=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]);return d>1e-4?(i[0]/=d,i[1]/=d,i[2]/=d,i[3]/=d):(i[0]=0,i[1]=0,i[2]=0,i[3]=1),i}const a=Math.acos(r),o=Math.sin(a),c=Math.sin((1-e)*a)/o,l=Math.sin(e*a)/o;return i[0]=s[0]*c+n*t[0]*l,i[1]=s[1]*c+n*t[1]*l,i[2]=s[2]*c+n*t[2]*l,i[3]=s[3]*c+n*t[3]*l,i}function Ar(s,t){const e=s[0],i=s[1],r=s[2],n=s[3],a=e+e,o=i+i,c=r+r,l=e*a,d=e*o,S=e*c,b=i*o,p=i*c,v=r*c,E=n*a,I=n*o,z=n*c,_=t||new Float32Array(16);return _[0]=1-(b+v),_[1]=d+z,_[2]=S-I,_[3]=0,_[4]=d-z,_[5]=1-(l+v),_[6]=p+E,_[7]=0,_[8]=S+I,_[9]=p-E,_[10]=1-(l+b),_[11]=0,_[12]=0,_[13]=0,_[14]=0,_[15]=1,_}const Er=new Float32Array(16);function Cr(s,t,e,i){const r=Ar(t,Er),n=i||new Float32Array(16);return n[0]=r[0]*e[0],n[1]=r[1]*e[0],n[2]=r[2]*e[0],n[3]=0,n[4]=r[4]*e[1],n[5]=r[5]*e[1],n[6]=r[6]*e[1],n[7]=0,n[8]=r[8]*e[2],n[9]=r[9]*e[2],n[10]=r[10]*e[2],n[11]=0,n[12]=s[0],n[13]=s[1],n[14]=s[2],n[15]=1,n}function Ni(s,t,e){const i=e||new Float32Array(16);for(let r=0;r<4;r++)for(let n=0;n<4;n++)i[r*4+n]=s[0+n]*t[r*4+0]+s[4+n]*t[r*4+1]+s[8+n]*t[r*4+2]+s[12+n]*t[r*4+3];return i}class as{constructor(t){this.joints=t.joints,this.inverseBindMatrices=t.inverseBindMatrices,this.jointWeights=t.jointWeights,this.jointIndices=t.jointIndices,this.nodes=t.nodes,this.animations=t.animations,this.restPositions=null,this.restNormals=null,this.currentAnimIndex=0,this.currentTime=0,this.playing=!0,this.speed=1,this.loop=!0,this.jointLocalTransforms=new Array(this.nodes.length),this.jointGlobalTransforms=new Array(this.nodes.length),this.jointFinalMatrices=new Array(this.joints.length);for(let e=0;e<this.nodes.length;e++)this.jointLocalTransforms[e]=new Float32Array(16),this.jointGlobalTransforms[e]=new Float32Array(16);for(let e=0;e<this.joints.length;e++)this.jointFinalMatrices[e]=new Float32Array(16);this.skinnedPositions=null,this.skinnedNormals=null,this._gpuSkinningReady=!1,this._sV0=new Float64Array(4),this._sV1=new Float64Array(4),this._scrT=new Float64Array(3),this._scrR=new Float64Array(4),this._scrS=new Float64Array(3),this._buildTopologicalOrder(),this._parentMap=new Array(this.nodes.length).fill(-1);for(let e=0;e<this.nodes.length;e++)for(const i of this.nodes[e].children)this._parentMap[i]=e;this._invBindViews=new Array(this.joints.length);for(let e=0;e<this.joints.length;e++)this._invBindViews[e]=this.inverseBindMatrices.subarray(e*16,e*16+16)}setRestPose(t,e){this.restPositions=new Float32Array(t),this.restNormals=new Float32Array(e),this.skinnedPositions=new Float32Array(t.length),this.skinnedNormals=new Float32Array(e.length)}async initGPUSkinning(t,e,i){try{this._gpuDevice=t,this._gpuOutputBuffer=e;const r=this.restPositions.length/3,n=new Float32Array(r*8);for(let c=0;c<r;c++){const l=c*8,d=c*3,S=c*2;n[l]=this.restPositions[d],n[l+1]=this.restPositions[d+1],n[l+2]=this.restPositions[d+2],n[l+3]=this.restNormals[d],n[l+4]=this.restNormals[d+1],n[l+5]=this.restNormals[d+2],n[l+6]=i?i[S]:0,n[l+7]=i?i[S+1]:0}this._gpuRestDataBuffer=t.createBuffer({size:n.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_restData"}),t.queue.writeBuffer(this._gpuRestDataBuffer,0,n),this._gpuJointWeightsBuffer=t.createBuffer({size:this.jointWeights.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_jointWeights"}),t.queue.writeBuffer(this._gpuJointWeightsBuffer,0,this.jointWeights);const a=new Uint32Array(this.jointIndices.length);for(let c=0;c<this.jointIndices.length;c++)a[c]=this.jointIndices[c];this._gpuJointIndicesBuffer=t.createBuffer({size:a.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_jointIndices"}),t.queue.writeBuffer(this._gpuJointIndicesBuffer,0,a),this._gpuJointMatricesBuffer=t.createBuffer({size:this.joints.length*16*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_jointMatrices"}),this._gpuJointMatricesData=new Float32Array(this.joints.length*16);const o=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]});this._gpuSkinningPipeline=t.createComputePipeline({layout:t.createPipelineLayout({bindGroupLayouts:[o]}),compute:{module:t.createShaderModule({code:hr}),entryPoint:"main"}}),this._gpuSkinningBindGroup=t.createBindGroup({layout:o,entries:[{binding:0,resource:{buffer:this._gpuRestDataBuffer}},{binding:1,resource:{buffer:this._gpuJointWeightsBuffer}},{binding:2,resource:{buffer:this._gpuJointIndicesBuffer}},{binding:3,resource:{buffer:this._gpuJointMatricesBuffer}},{binding:4,resource:{buffer:this._gpuOutputBuffer}}]}),this._gpuVertexCount=r,this._gpuSkinningReady=!0,globalThis.__HZFX_DEBUG&&console.log(`GPU skinning initialized: ${r} vertices, ${this.joints.length} joints`)}catch(r){console.warn("GPU skinning init failed, using CPU fallback:",r),this._gpuSkinningReady=!1}}_applySkinningGPU(){for(let i=0;i<this.joints.length;i++)this._gpuJointMatricesData.set(this.jointFinalMatrices[i],i*16);this._gpuDevice.queue.writeBuffer(this._gpuJointMatricesBuffer,0,this._gpuJointMatricesData);const t=this._gpuDevice.createCommandEncoder({label:"SkinningComputeEncoder"}),e=t.beginComputePass({label:"SkinningComputePass"});e.setPipeline(this._gpuSkinningPipeline),e.setBindGroup(0,this._gpuSkinningBindGroup),e.dispatchWorkgroups(Math.ceil(this._gpuVertexCount/64),1,1),e.end(),this._gpuDevice.queue.submit([t.finish()])}update(t){if(!this.playing||this.animations.length===0)return{positions:this.skinnedPositions,normals:this.skinnedNormals,changed:!1};this.currentTime+=t*this.speed;const e=this.animations[this.currentAnimIndex];return this.loop?this.currentTime=this.currentTime%e.duration:this.currentTime>e.duration&&(this.currentTime=e.duration,this.playing=!1),this._computeLocalTransforms(this.currentTime),this._computeGlobalTransforms(),this._computeFinalMatrices(),this._gpuSkinningReady?(this._applySkinningGPU(),{gpuSkinned:!0,changed:!0}):(this._applySkinning(),{positions:this.skinnedPositions,normals:this.skinnedNormals,changed:!0})}getCurrentAnimation(){return this.animations[this.currentAnimIndex]}setAnimation(t){t>=0&&t<this.animations.length&&(this.currentAnimIndex=t,this.currentTime=0)}getAnimationNames(){return this.animations.map(t=>t.name)}_buildTopologicalOrder(){const t=new Set,e=[],i=n=>{if(t.has(n))return;t.add(n);const a=this.nodes[n];for(const o of a.children)i(o);e.push(n)},r=new Set;for(const n of this.nodes)for(const a of n.children)r.add(a);for(let n=0;n<this.nodes.length;n++)r.has(n)||i(n);this.topologicalOrder=e.reverse()}_sampleChannel(t,e,i){const{timestamps:r,values:n,interpolation:a,targetPath:o}=t;if(e<=r[0])return this._extractValue(n,0,o,i);if(e>=r[r.length-1])return this._extractValue(n,r.length-1,o,i);let c=0,l=r.length-1;for(;l-c>1;){const E=Math.floor((c+l)/2);r[E]<=e?c=E:l=E}const d=r[c],S=r[l],b=(e-d)/(S-d),p=this._extractValue(n,c,o,this._sV0),v=this._extractValue(n,l,o,this._sV1);return a==="STEP"?(i[0]=p[0],i[1]=p[1],i[2]=p[2],o==="rotation"&&(i[3]=p[3]),i):o==="rotation"?Tr(p,v,b,i):Rr(p,v,b,i)}_extractValue(t,e,i,r){if(i==="rotation"){const n=e*4;r[0]=t[n],r[1]=t[n+1],r[2]=t[n+2],r[3]=t[n+3]}else{const n=e*3;r[0]=t[n],r[1]=t[n+1],r[2]=t[n+2]}return r}_computeLocalTransforms(t){const e=this.animations[this.currentAnimIndex];for(let i=0;i<this.nodes.length;i++){const r=this.nodes[i];let n=r.translation,a=r.rotation,o=r.scale;for(const c of e.channels)c.targetNode===i&&(c.targetPath==="translation"?n=this._sampleChannel(c,t,this._scrT):c.targetPath==="rotation"?a=this._sampleChannel(c,t,this._scrR):c.targetPath==="scale"&&(o=this._sampleChannel(c,t,this._scrS)));Cr(n,a,o,this.jointLocalTransforms[i])}}_computeGlobalTransforms(){const t=this._parentMap;for(const e of this.topologicalOrder){const i=t[e];i===-1?this.jointGlobalTransforms[e].set(this.jointLocalTransforms[e]):Ni(this.jointGlobalTransforms[i],this.jointLocalTransforms[e],this.jointGlobalTransforms[e])}}_computeFinalMatrices(){for(let t=0;t<this.joints.length;t++){const e=this.joints[t],i=this.jointGlobalTransforms[e];Ni(i,this._invBindViews[t],this.jointFinalMatrices[t])}}_applySkinning(){const t=this.restPositions.length/3,e=this.restPositions,i=this.restNormals,r=this.skinnedPositions,n=this.skinnedNormals,a=this.jointWeights,o=this.jointIndices,c=this.jointFinalMatrices;for(let l=0;l<t;l++){const d=l*3,S=l*4,b=e[d],p=e[d+1],v=e[d+2],E=i[d],I=i[d+1],z=i[d+2];let _=0,W=0,T=0,G=0,F=0,Z=0;for(let ae=0;ae<4;ae++){const ne=a[S+ae];if(ne===0)continue;const q=c[o[S+ae]];_+=(q[0]*b+q[4]*p+q[8]*v+q[12])*ne,W+=(q[1]*b+q[5]*p+q[9]*v+q[13])*ne,T+=(q[2]*b+q[6]*p+q[10]*v+q[14])*ne,G+=(q[0]*E+q[4]*I+q[8]*z)*ne,F+=(q[1]*E+q[5]*I+q[9]*z)*ne,Z+=(q[2]*E+q[6]*I+q[10]*z)*ne}const re=Math.sqrt(G*G+F*F+Z*Z);re>1e-4&&(n[d]=G/re,n[d+1]=F/re,n[d+2]=Z/re),r[d]=_,r[d+1]=W,r[d+2]=T}}}class os{constructor({duration:t=0,loop:e=!1,playbackRate:i=1}={}){this.currentTime=0,this.duration=t,this.loop=e,this.playbackRate=i,this.paused=!1,this._justLooped=!1}tick(t){if(this.paused)return 0;const e=t*this.playbackRate;return this.currentTime+=e,this._justLooped=!1,this.loop&&this.duration>0&&isFinite(this.duration)&&this.currentTime>=this.duration&&(this.currentTime=0,this._justLooped=!0),e}get justLooped(){return this._justLooped}reset(){this.currentTime=0,this._justLooped=!1}seek(t){this.currentTime=Math.max(0,t||0),this._justLooped=!1}}const Yi={linear:s=>s,easeInQuad:s=>s*s,easeOutQuad:s=>1-(1-s)*(1-s),easeInOutQuad:s=>s<.5?2*s*s:1-Math.pow(-2*s+2,2)/2,easeInCubic:s=>s*s*s,easeOutCubic:s=>1-Math.pow(1-s,3),easeInOutCubic:s=>s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,easeInQuart:s=>s*s*s*s,easeOutQuart:s=>1-Math.pow(1-s,4),easeInOutQuart:s=>s<.5?8*s*s*s*s:1-Math.pow(-2*s+2,4)/2,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeOutElastic:s=>{if(s===0||s===1)return s;const t=2*Math.PI/3;return Math.pow(2,-10*s)*Math.sin((s*10-.75)*t)+1}};function Ur(s,t,e,i){const r=3*s,n=3*(e-s)-r,a=1-r-n,o=3*t,c=3*(i-t)-o,l=1-o-c,d=p=>((a*p+n)*p+r)*p,S=p=>((l*p+c)*p+o)*p,b=p=>(3*a*p+2*n)*p+r;return p=>{if(p<=0)return 0;if(p>=1)return 1;let v=p;for(let E=0;E<8;E++){const I=d(v)-p;if(Math.abs(I)<1e-5)break;const z=b(v);if(Math.abs(z)<1e-6)break;v-=I/z}return S(v)}}function ls(s,t){return typeof s=="function"?s(t):Array.isArray(s)&&s.length===4?Ur(s[0],s[1],s[2],s[3])(t):(Yi[s]||Yi.linear)(t)}function Ir(s,t){if(!Array.isArray(s)||s.length===0)return;if(s.length===1||t<=s[0].t)return s[0].v;const e=s[s.length-1];if(t>=e.t)return e.v;for(let i=0;i<s.length-1;i++){const r=s[i],n=s[i+1];if(t>=r.t&&t<=n.t){const a=n.t-r.t,o=a>0?(t-r.t)/a:0;return r.v+(n.v-r.v)*ls(r.ease,o)}}return e.v}function zr(s,t,e){if(!Array.isArray(s)||s.length===0)return;const i=s.length,r=s[i-1];let n,a,o;if(i===1||t<=s[0].t)n=a=s[0].v,o=0;else if(t>=r.t)n=a=r.v,o=0;else{n=a=r.v,o=0;for(let S=0;S<i-1;S++){const b=s[S],p=s[S+1];if(t>=b.t&&t<=p.t){const v=p.t-b.t;n=b.v,a=p.v,o=ls(b.ease,v>0?(t-b.t)/v:0);break}}}const c=n[0]+(a[0]-n[0])*o,l=n[1]+(a[1]-n[1])*o,d=n[2]+(a[2]-n[2])*o;return e?(e[0]=c,e[1]=l,e[2]=d,e):[c,l,d]}const Gr=["gravityStrength","emissionRate","damping","dampingStrength","particleSize","particleSpeed","opacity","bloomIntensity","emissionPositionX","emissionPositionY","emissionPositionZ","emissionRotationX","emissionRotationY","emissionRotationZ","circleInnerRadius","circleOuterRadius","discRadius","annulusInnerRadius","annulusOuterRadius","arcStartAngle","arcEndAngle","arcInnerRadius","arcOuterRadius","squareSize","rectangleWidth","rectangleHeight","planeWidth","planeDepth","lineLength","polygonRadius","shapeStrokeWidth","shapeStrokeAmplitude","shapeStrokeFrequency","shapeStrokeSpeed"],Fr={square:0,circle:1,triangle:2,diamond:3,star:4,hexagon:5,ring:6,heart:7,cross:8,spark:9,leaf:10,capsule:11,crescent:12,line:13,"curved-line":14};function ji(s){const t=atob(s),e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e.buffer}class kt{constructor(t,e){this.device=t,this.config=e,this.MAX_PARTICLES=e.maxParticles||1e4,this.particleCount=e.particleCount||100,this.activeParticles=0,this.emitting=!1,this.currentEmissionTime=0,this.emissionAccumulator=0,this.destroyed=!1,this.particleData=new Float32Array(this.MAX_PARTICLES*8),this.particleVelocities=new Float32Array(this.MAX_PARTICLES*4),this.instanceBuffer=t.createBuffer({size:this.MAX_PARTICLES*8*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC,label:"particleInstanceBuffer"}),this.velocityBuffer=t.createBuffer({size:this.MAX_PARTICLES*4*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,label:"particleVelocityBuffer"}),this.trailBuffer=t.createBuffer({size:this.MAX_PARTICLES*4*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,label:"particleTrailBuffer"}),this._trailResetData=new Float32Array(this.MAX_PARTICLES*4),this.appearanceUniformBuffer=t.createBuffer({size:224,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"appearanceUniformBuffer"}),this.bloomIntensityBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"systemBloomIntensityBuffer"}),e.overrideXVelocity===void 0&&(e.overrideXVelocity=!1),e.overrideYVelocity===void 0&&(e.overrideYVelocity=!1),e.overrideZVelocity===void 0&&(e.overrideZVelocity=!1),e.xVelocity===void 0&&(e.xVelocity=0),e.yVelocity===void 0&&(e.yVelocity=0),e.zVelocity===void 0&&(e.zVelocity=0),e.textureEnabled===void 0&&(e.textureEnabled=!1),e.glbModelEnabled===void 0&&(e.glbModelEnabled=!1),e.textureType===void 0&&(e.textureType="image"),e.glbFileName===void 0&&(e.glbFileName=null),e.animationIndex===void 0&&(e.animationIndex=0),e.animationSpeed===void 0&&(e.animationSpeed=1),e.animationLoop===void 0&&(e.animationLoop=!0),e.useGlbTexture===void 0&&(e.useGlbTexture=!1),e.glbHasTexture===void 0&&(e.glbHasTexture=!1),e.particleShape===void 0&&(e.particleShape="square"),e.particleShapeRotation!==void 0&&(e.rotation=(e.rotation||0)+e.particleShapeRotation,delete e.particleShapeRotation),e.particleShapeRotationX===void 0&&(e.particleShapeRotationX=0),e.particleShapeRotationY===void 0&&(e.particleShapeRotationY=0),e.particleShapeRotationZ===void 0&&(e.particleShapeRotationZ=0),e.particleColor===void 0&&(e.particleColor=[1,1,1]),e.startColor===void 0&&(e.startColor=[1,0,0]),e.endColor===void 0&&(e.endColor=[0,0,1]),e.fadeEnabled===void 0&&(e.fadeEnabled=!0),e.colorTransitionEnabled===void 0&&(e.colorTransitionEnabled=!1),e.randomColorEnabled===void 0&&(e.randomColorEnabled=!1),e.randomColors===void 0&&(e.randomColors=[]),e.particleSize===void 0&&(e.particleSize=.1),e.particleSpeed===void 0&&(e.particleSpeed=1),e.opacity===void 0&&(e.opacity=1),e.aspectRatio===void 0&&(e.aspectRatio=1),e.rotation===void 0&&(e.rotation=0),e.rotationMode===void 0&&(e.rotationMode="fixed"),e.minRotation===void 0&&(e.minRotation=0),e.maxRotation===void 0&&(e.maxRotation=90),e.orientX===void 0&&(e.orientX=0),e.orientY===void 0&&(e.orientY=0),e.orientZ===void 0&&(e.orientZ=0),e.randomSize===void 0&&(e.randomSize=!1),e.minSize===void 0&&(e.minSize=.05),e.maxSize===void 0&&(e.maxSize=.15),e.randomSpeed===void 0&&(e.randomSpeed=!1),e.minSpeed===void 0&&(e.minSpeed=.1),e.maxSpeed===void 0&&(e.maxSpeed=1),e.fadeSizeEnabled===void 0&&(e.fadeSizeEnabled=!1),e.increaseSizeEnabled===void 0&&(e.increaseSizeEnabled=!1),e.sizeLifetimeSpeed===void 0&&(e.sizeLifetimeSpeed=1),e.bloomEnabled===void 0&&(e.bloomEnabled=!0),e.bloomIntensity===void 0&&(e.bloomIntensity=1),e.bloomColor===void 0&&(e.bloomColor=[1,1,1]),e.gravityEnabled===void 0&&(e.gravityEnabled=!1),e.gravityStrength===void 0&&(e.gravityStrength=2),e.dampingEnabled===void 0&&(e.dampingEnabled=!1),e.dampingStrength===void 0&&(e.dampingStrength=1),e.attractorEnabled===void 0&&(e.attractorEnabled=!1),e.attractorStrength===void 0&&(e.attractorStrength=1),e.attractorPosition===void 0&&(e.attractorPosition=[0,0,0]),e.attractorReverse===void 0&&(e.attractorReverse=!1),e.burstMode===void 0&&(e.burstMode=!1),e.emissionShape===void 0&&(e.emissionShape="cube"),e.lifetime===void 0&&(e.lifetime=5),e.emissionRate===void 0&&(e.emissionRate=10),e.startAt===void 0&&(e.startAt=0),e.emissionDuration===void 0&&(e.emissionDuration=10),e.emissionDurationInfinite===void 0&&(e.emissionDurationInfinite=!1),e.emissionDuration>300&&(e.emissionDurationInfinite=!0,e.emissionDuration=10),e.outerLength===void 0&&(e.outerLength=e.cubeLength??2),e.innerLength===void 0&&(e.innerLength=0),e.outerRadius===void 0&&(e.outerRadius=2),e.innerRadius===void 0&&(e.innerRadius=0),e.squareSize===void 0&&(e.squareSize=2),e.squareInnerSize===void 0&&(e.squareInnerSize=0),e.circleInnerRadius===void 0&&(e.circleInnerRadius=0),e.circleOuterRadius===void 0&&(e.circleOuterRadius=2),e.circleVelocityDirection===void 0&&(e.circleVelocityDirection="outward"),e.cylinderInnerRadius===void 0&&(e.cylinderInnerRadius=0),e.cylinderOuterRadius===void 0&&(e.cylinderOuterRadius=2),e.cylinderHeight===void 0&&(e.cylinderHeight=4),e.cylinderVelocityDirection===void 0&&(e.cylinderVelocityDirection="outward"),e.planeWidth===void 0&&(e.planeWidth=2),e.planeDepth===void 0&&(e.planeDepth=2),e.coneOuterRadius===void 0&&(e.coneOuterRadius=2),e.coneInnerRadius===void 0&&(e.coneInnerRadius=0),e.coneHeight===void 0&&(e.coneHeight=4),e.torusMajorRadius===void 0&&(e.torusMajorRadius=2),e.torusMinorRadius===void 0&&(e.torusMinorRadius=.5),e.lineLength===void 0&&(e.lineLength=4),e.hemisphereOuterRadius===void 0&&(e.hemisphereOuterRadius=2),e.hemisphereInnerRadius===void 0&&(e.hemisphereInnerRadius=0),e.discRadius===void 0&&(e.discRadius=2),e.annulusInnerRadius===void 0&&(e.annulusInnerRadius=1),e.annulusOuterRadius===void 0&&(e.annulusOuterRadius=2),e.capsuleRadius===void 0&&(e.capsuleRadius=.5),e.capsuleHeight===void 0&&(e.capsuleHeight=4),e.arcStartAngle===void 0&&(e.arcStartAngle=0),e.arcEndAngle===void 0&&(e.arcEndAngle=180),e.arcInnerRadius===void 0&&(e.arcInnerRadius=0),e.arcOuterRadius===void 0&&(e.arcOuterRadius=2),e.spiralTurns===void 0&&(e.spiralTurns=3),e.spiralRadiusStart===void 0&&(e.spiralRadiusStart=.5),e.spiralRadiusEnd===void 0&&(e.spiralRadiusEnd=2),e.spiralHeight===void 0&&(e.spiralHeight=4),e.frustumRadiusNear===void 0&&(e.frustumRadiusNear=.5),e.frustumRadiusFar===void 0&&(e.frustumRadiusFar=2),e.frustumHeight===void 0&&(e.frustumHeight=4),e.cubeSurfaceSize===void 0&&(e.cubeSurfaceSize=2),e.sphereSurfaceRadius===void 0&&(e.sphereSurfaceRadius=2),e.boxFrameSize===void 0&&(e.boxFrameSize=2),e.polygonSides===void 0&&(e.polygonSides=6),e.polygonRadius===void 0&&(e.polygonRadius=2),e.emissionRotationX===void 0&&(e.emissionRotationX=0),e.emissionRotationY===void 0&&(e.emissionRotationY=0),e.emissionRotationZ===void 0&&(e.emissionRotationZ=0),e.emissionPositionX===void 0&&(e.emissionPositionX=e.emissionTranslationX??0),e.emissionPositionY===void 0&&(e.emissionPositionY=e.emissionTranslationY??0),e.emissionPositionZ===void 0&&(e.emissionPositionZ=e.emissionTranslationZ??0),e.pulseEnabled===void 0&&(e.pulseEnabled=!1),e.pulseAmplitude===void 0&&(e.pulseAmplitude=.5),e.pulseFrequency===void 0&&(e.pulseFrequency=1),e.pulsePhaseRandom===void 0&&(e.pulsePhaseRandom=0),e.pulseOpacity===void 0&&(e.pulseOpacity=!1),e.confinementEnabled===void 0&&(e.confinementEnabled=!1),e.confinementShape===void 0&&(e.confinementShape="box"),e.confinementMode===void 0&&(e.confinementMode="bounce"),e.confinementSpace===void 0&&(e.confinementSpace="world"),e.confinementBoxHalfSize===void 0&&(e.confinementBoxHalfSize=[2,2,2]),e.confinementSphereRadius===void 0&&(e.confinementSphereRadius=3),e.confinementRestitution===void 0&&(e.confinementRestitution=.8),e.confinementFriction===void 0&&(e.confinementFriction=.1),e.softBoundaryEnabled===void 0&&(e.softBoundaryEnabled=!1),e.softBoundaryStrength===void 0&&(e.softBoundaryStrength=5),e.softBoundaryFalloff===void 0&&(e.softBoundaryFalloff=.5),e.depthWriteEnabled===void 0&&(e.depthWriteEnabled=!1),e.velocityStretchEnabled===void 0&&(e.velocityStretchEnabled=!1),e.velocityStretchFactor===void 0&&(e.velocityStretchFactor=1),e.blendMode===void 0&&(e.blendMode="normal"),e.noiseDistortEnabled===void 0&&(e.noiseDistortEnabled=!1),e.noiseTilingX===void 0&&(e.noiseTilingX=3),e.noiseTilingY===void 0&&(e.noiseTilingY=3),e.noiseSpeed===void 0&&(e.noiseSpeed=-1.5),e.noiseAmplitude===void 0&&(e.noiseAmplitude=.08),e.emissionTrailEnabled===void 0&&(e.emissionTrailEnabled=!1),e.emissionTrailDuration===void 0&&(e.emissionTrailDuration=1),e.emissionTrailWidth===void 0&&(e.emissionTrailWidth=.3),e.emissionTrailMinDistance===void 0&&(e.emissionTrailMinDistance=.05),e.emissionTrailMaxPoints===void 0&&(e.emissionTrailMaxPoints=256),e.emissionTrailSegments===void 0&&(e.emissionTrailSegments=8),e.emissionTrailMode===void 0&&(e.emissionTrailMode="ribbon"),e.emissionTrailShape===void 0&&(e.emissionTrailShape="straight"),e.emissionTrailShapeAmplitude===void 0&&(e.emissionTrailShapeAmplitude=.1),e.emissionTrailShapeFrequency===void 0&&(e.emissionTrailShapeFrequency=4),e.emissionTrailShapeSpeed===void 0&&(e.emissionTrailShapeSpeed=0),e.shapeStrokeEnabled===void 0&&(e.shapeStrokeEnabled=!1),e.shapeStrokeWidth===void 0&&(e.shapeStrokeWidth=.08),e.shapeStrokeSegments===void 0&&(e.shapeStrokeSegments=96),e.shapeStrokeShape===void 0&&(e.shapeStrokeShape="straight"),e.shapeStrokeAmplitude===void 0&&(e.shapeStrokeAmplitude=.08),e.shapeStrokeFrequency===void 0&&(e.shapeStrokeFrequency=10),e.shapeStrokeSpeed===void 0&&(e.shapeStrokeSpeed=0),e.shapeDisplay===void 0&&(e.shapeDisplay=!0),e.followSystemTranslation===void 0&&(e.followSystemTranslation=!0),e.followSystemId===void 0&&(e.followSystemId=null),this._newEmissions=[],this._emptyEmissions=[],this._pendingFollowEmissions=this._emptyEmissions,this.glbVertexBuffer=null,this.glbIndexBuffer=null,this.glbIndexCount=0,this.glbIndexFormat="uint16",this.glbMeshData=null,this.glbRawArrayBuffer=null,this.glbAnimator=null,this.glbAnimated=!1,this._glbInterleavedData=null,this._appearanceData=new Float32Array(56),this._bloomIntensityData=new Float32Array(16),this._simPosition=[0,0,0],this._simVelocity=[0,0,0],this._simRotMatrix=null,this._simRotX=0,this._simRotZ=0,this._emitSimRotY=0,this.emitter=new $i(e),this.physics=new is(t,this.MAX_PARTICLES),this.textureManager=new ss(t),e.gravityEnabled&&this.setGravity(e.gravityStrength||0),e.dampingEnabled&&this.physics.setDamping(e.dampingStrength||0),e.attractorEnabled&&e.attractorPosition&&this.setAttractor(e.attractorStrength||0,e.attractorPosition,e.attractorReverse),e.confinementEnabled&&this.setConfinement({enabled:!0,shape:e.confinementShape,mode:e.confinementMode,space:e.confinementSpace,boxSize:e.confinementBoxHalfSize,sphereRadius:e.confinementSphereRadius,restitution:e.confinementRestitution,friction:e.confinementFriction}),e.softBoundaryEnabled&&this.setSoftBoundary({enabled:!0,strength:e.softBoundaryStrength,falloff:e.softBoundaryFalloff}),this.particleTexture=this.textureManager.getDefaultTexture(),this.updateBloomIntensity(),this.updateAppearanceUniform(),this.frameCount=0,this.shouldReset=!1,this._scriptParticleData=new Float32Array(this.MAX_PARTICLES*8),this._scriptVelocityData=new Float32Array(this.MAX_PARTICLES*4),this._scriptReadbackPending=!1,this._scriptReadbackReady=!1,this._scriptFrame=0,this._scriptTime=0,this._scriptConfigRestored=!1,this._particleScript=null,e.script&&(this._particleScript=new ai(e.script,e,this.MAX_PARTICLES)),this.initComputePipeline(t)}async initComputePipeline(t){this.computeReady=await this.physics.initComputePipeline(this.instanceBuffer,this.velocityBuffer,this.trailBuffer)}setScript(t){this._particleScript&&(this._particleScript.destroy(),this._particleScript=null),this._scriptReadbackPending=!1,this._scriptReadbackReady=!1,this._scriptFrame=0,this._scriptTime=0,this._scriptConfigRestored=!1,t?(this.config.script=t,this._particleScript=new ai(t,this.config,this.MAX_PARTICLES),this._particleScript.snapshotConfig(this.config)):delete this.config.script}async setTexture(t){this.destroyed||(this.textureManager.destroyTexture(this.particleTexture),this.particleTexture=await this.textureManager.loadTexture(t),this.config.textureEnabled=!0,this.updateAppearanceUniform(),this.updateBuffers())}resetTexture(){this.destroyed||(this.textureManager.destroyTexture(this.particleTexture),this.particleTexture=this.textureManager.getDefaultTexture(),this.config.textureEnabled=!1,this.updateAppearanceUniform(),this.updateBuffers())}async setGLBModel(t){try{this.glbRawArrayBuffer=t;const e=await ns(t);this.glbMeshData=e,this.config.glbHasTexture=e.hasBaseColorTexture||!1;const i=new Float32Array(e.vertexCount*8);for(let r=0;r<e.vertexCount;r++){const n=r*8,a=r*3,o=r*2;i[n+0]=e.positions[a+0],i[n+1]=e.positions[a+1],i[n+2]=e.positions[a+2],i[n+3]=e.normals[a+0],i[n+4]=e.normals[a+1],i[n+5]=e.normals[a+2],e.texCoords?(i[n+6]=e.texCoords[o+0],i[n+7]=e.texCoords[o+1]):(i[n+6]=0,i[n+7]=0)}if(this.glbVertexBuffer&&this.glbVertexBuffer.destroy(),this.glbIndexBuffer&&this.glbIndexBuffer.destroy(),this.glbVertexBuffer=this.device.createBuffer({size:i.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE,label:"glbVertexBuffer"}),this.device.queue.writeBuffer(this.glbVertexBuffer,0,i),this.glbIndexBuffer=this.device.createBuffer({size:e.indices.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST,label:"glbIndexBuffer"}),this.device.queue.writeBuffer(this.glbIndexBuffer,0,e.indices),this.glbIndexCount=e.indexCount,this.glbIndexFormat=e.indices instanceof Uint32Array?"uint32":"uint16",this.config.glbModelEnabled=!0,this.config.textureType="glb",e.animationData){this.glbAnimator=new as(e.animationData),this.glbAnimator.setRestPose(e.positions,e.normals),this.glbAnimated=!0,this.config.glbAnimated=!0,this.glbAnimator.loop=this.config.animationLoop,this._glbInterleavedData=new Float32Array(e.vertexCount*8);try{await this.glbAnimator.initGPUSkinning(this.device,this.glbVertexBuffer,e.texCoords)}catch(r){console.warn("GPU skinning init failed, using CPU fallback:",r)}globalThis.__HZFX_DEBUG&&console.log(`GLB animated model loaded: ${e.animationData.animations.length} animations`)}else this.glbAnimator=null,this.glbAnimated=!1,this.config.glbAnimated=!1,this._glbInterleavedData=null;globalThis.__HZFX_DEBUG&&console.log(`GLB model loaded: ${e.vertexCount} vertices, ${e.indexCount} indices`)}catch(e){throw console.error("Failed to load GLB model:",e),e}}resetGLBModel(){this.glbVertexBuffer&&(this.glbVertexBuffer.destroy(),this.glbVertexBuffer=null),this.glbIndexBuffer&&(this.glbIndexBuffer.destroy(),this.glbIndexBuffer=null),this.glbIndexCount=0,this.glbIndexFormat="uint16",this.glbMeshData=null,this.glbRawArrayBuffer=null,this.glbAnimator=null,this.glbAnimated=!1,this.config.glbAnimated=!1,this._glbInterleavedData=null,this.config.glbFileName=null,this.config.glbHasTexture=!1,this.config.useGlbTexture=!1,this.config.glbModelEnabled=!1,this.config.textureType="image"}setSimulationTransform(t){if(t.position&&(this._simPosition[0]=t.position[0],this._simPosition[1]=t.position[1],this._simPosition[2]=t.position[2]),t.rotation){this._simRotX=t.rotation[0]||0,this._simRotZ=t.rotation[1]||0,this._simRotY=t.rotation[2]||0;const e=Math.cos(this._simRotX),i=Math.sin(this._simRotX),r=Math.cos(this._simRotZ),n=Math.sin(this._simRotZ),a=Math.cos(this._simRotY),o=Math.sin(this._simRotY);this._simRotMatrix=[a*r,-a*n*e+o*i,a*n*i+o*e,n,r*e,-r*i,-o*r,o*n*e+a*i,-o*n*i+a*e]}else this._simRotMatrix=null,this._simRotX=0,this._simRotZ=0,this._simRotY=0;t.velocity&&(this._simVelocity[0]=t.velocity[0],this._simVelocity[1]=t.velocity[1],this._simVelocity[2]=t.velocity[2])}clearSimulationTransform(){this._simPosition[0]=this._simPosition[1]=this._simPosition[2]=0,this._simVelocity[0]=this._simVelocity[1]=this._simVelocity[2]=0,this._simRotMatrix=null,this._simRotX=0,this._simRotZ=0}updateAnimatedGLBBuffer(){if(!this.glbAnimator||!this.glbAnimator.playing)return!1;if(this.glbAnimator._gpuSkinningReady)return!0;const t=this.glbAnimator.skinnedPositions,e=this.glbAnimator.skinnedNormals,i=this.glbMeshData.texCoords;for(let r=0;r<this.glbMeshData.vertexCount;r++){const n=r*8,a=r*3,o=r*2;this._glbInterleavedData[n]=t[a],this._glbInterleavedData[n+1]=t[a+1],this._glbInterleavedData[n+2]=t[a+2],this._glbInterleavedData[n+3]=e[a],this._glbInterleavedData[n+4]=e[a+1],this._glbInterleavedData[n+5]=e[a+2],i?(this._glbInterleavedData[n+6]=i[o],this._glbInterleavedData[n+7]=i[o+1]):(this._glbInterleavedData[n+6]=0,this._glbInterleavedData[n+7]=0)}return this.device.queue.writeBuffer(this.glbVertexBuffer,0,this._glbInterleavedData),!0}updateAppearanceUniform(){if(this.destroyed)return;let t=0;this.config.rotationMode==="random"?t=1:this.config.rotationMode==="velocity"?t=2:this.config.rotationMode==="oriented"?t=3:this.config.rotationMode==="cylindrical"&&(t=4);const e=Fr[this.config.particleShape]??0,i=this._appearanceData;i[0]=this.config.fadeEnabled?1:0,i[1]=this.config.randomColorEnabled?2:this.config.colorTransitionEnabled?1:0,i[2]=this.config.particleSize,i[3]=this.config.textureEnabled?1:0,i[4]=this.config.particleColor[0],i[5]=this.config.particleColor[1],i[6]=this.config.particleColor[2],i[7]=this.config.rotation||0,i[8]=this.config.startColor[0],i[9]=this.config.startColor[1],i[10]=this.config.startColor[2],i[11]=t,i[12]=this.config.endColor[0],i[13]=this.config.endColor[1],i[14]=this.config.endColor[2],i[15]=this.config.minRotation||0,i[16]=this.config.maxRotation||90,i[17]=this.config.aspectRatio||1,i[18]=this.config.randomSize?1:0,i[19]=this.config.minSize||.1,i[20]=this.config.maxSize||.5,i[21]=this.config.fadeSizeEnabled?1:0,i[22]=this.config.opacity!==void 0?this.config.opacity:1,i[23]=this.config.increaseSizeEnabled?1:0,i[24]=this.config.sizeLifetimeSpeed??1,i[25]=e,i[26]=0,i[27]=this.config.pulseEnabled?1:0,i[28]=this.config.pulseAmplitude??.5,i[29]=this.config.pulseFrequency??1,i[30]=this.config.pulsePhaseRandom??0,i[31]=this.config.pulseOpacity?1:0,i[32]=this.config.particleShapeRotationX||0,i[33]=this.config.particleShapeRotationY||0,i[34]=this.config.particleShapeRotationZ||0,i[35]=0;const r=this.config.followSystemTranslation??!0;i[36]=r?this._simPosition[0]:0,i[37]=r?this._simPosition[1]:0,i[38]=r?this._simPosition[2]:0,i[39]=0,i[40]=this._simRotX,i[41]=this._simRotZ,i[42]=this.config.velocityStretchEnabled?1:0,i[43]=this.config.velocityStretchFactor??1,i[44]=this.config.noiseDistortEnabled?1:0,i[45]=this.config.noiseTilingX??3,i[46]=this.config.noiseTilingY??3,i[47]=this.config.noiseSpeed??-1.5,i[48]=this.config.noiseAmplitude??.08,i[49]=r?this._simVelocity[0]:0,i[50]=r?this._simVelocity[1]:0,i[51]=r?this._simVelocity[2]:0,i[52]=this.config.orientX??0,i[53]=this.config.orientY??0,i[54]=this.config.orientZ??0,i[55]=0,this.device.queue.writeBuffer(this.appearanceUniformBuffer,0,i)}updateBloomIntensity(){const t=this._bloomIntensityData;t[0]=this.config.bloomIntensity||1;const e=this.config.bloomColor||[1,1,1];t[4]=e[0],t[5]=e[1],t[6]=e[2],this.device.queue.writeBuffer(this.bloomIntensityBuffer,0,t)}spawnParticles(t){if(this.activeParticles=0,this.currentEmissionTime=0,this.emissionAccumulator=0,this._newEmissions.length=0,this._pendingFollowEmissions=this._emptyEmissions,this._scriptFrame=0,this._scriptTime=0,this._scriptReadbackPending=!1,this._scriptReadbackReady=!1,this._scriptConfigRestored=!1,this._particleScript&&(this._particleScript._configSnapshot?(this._particleScript.restoreConfig(this.config),this.config.gravityEnabled&&this.setGravity(this.config.gravityStrength),this.config.dampingEnabled&&this.physics.setDamping(this.config.dampingStrength),this.config.attractorEnabled&&this.setAttractor(this.config.attractorStrength,this.config.attractorPosition,this.config.attractorReverse),this.updateAppearanceUniform(),this.updateBloomIntensity()):this._particleScript.snapshotConfig(this.config)),typeof t=="function"&&t(this),this.device.queue.writeBuffer(this.trailBuffer,0,this._trailResetData,0,this.MAX_PARTICLES*4),this.glbAnimator&&(this.glbAnimator.currentTime=0,this.glbAnimator.playing=!0),this.config.followSystemId){this.emitting=!0,this.particleCount=this.MAX_PARTICLES;return}if(this.config.burstMode){const e=this.config.particleCount;this.particleCount=e;let i=0;const r=500;for(let n=0;n<e;n++)if(this.emitParticle(),i++,i>=r||n===e-1){const a=n-i+1,o=a*8,c=a*4;this.device.queue.writeBuffer(this.instanceBuffer,o*4,this.particleData,o,i*8),this.device.queue.writeBuffer(this.velocityBuffer,c*4,this.particleVelocities,c,i*4),i=0}this.emitting=!1}else{this.emitting=!0;const e=this.config.lifetime||5,i=this.config.emissionDurationInfinite?e:Math.min(this.config.emissionDuration||10,e);this.particleCount=Math.min(Math.ceil((this.config.emissionRate||10)*i),this.MAX_PARTICLES)}}get effectiveEmissionDuration(){return this.config.emissionDurationInfinite?1/0:this.config.emissionDuration??10}_applySimTransformToParticle(t){this._emitSimRotY=this._simRotY||0;const e=t*8,i=t*4;if(this._simRotMatrix){const r=this._simRotMatrix,n=this.particleData[e],a=this.particleData[e+1],o=this.particleData[e+2],c=this.particleVelocities[i],l=this.particleVelocities[i+1],d=this.particleVelocities[i+2];this.particleData[e]=r[0]*n+r[1]*a+r[2]*o,this.particleData[e+1]=r[3]*n+r[4]*a+r[5]*o,this.particleData[e+2]=r[6]*n+r[7]*a+r[8]*o,this.particleVelocities[i]=r[0]*c+r[1]*l+r[2]*d,this.particleVelocities[i+1]=r[3]*c+r[4]*l+r[5]*d,this.particleVelocities[i+2]=r[6]*c+r[7]*l+r[8]*d}(this.config.followSystemTranslation??!0)||(this.particleData[e]+=this._simPosition[0],this.particleData[e+1]+=this._simPosition[1],this.particleData[e+2]+=this._simPosition[2])}emitParticle(){if(this.activeParticles>=this.particleCount)return!1;this.emitter.emitParticle(this.particleData,this.activeParticles,this.particleVelocities);const t=this.activeParticles*8,e=this.activeParticles*4;return this._applySimTransformToParticle(this.activeParticles),this._newEmissions.push(this.particleData[t],this.particleData[t+1],this.particleData[t+2],this.particleVelocities[e],this.particleVelocities[e+1],this.particleVelocities[e+2]),this.activeParticles++,!0}emitFollowerParticle(t,e,i){if(this.activeParticles>=this.particleCount)return!1;const r=this.activeParticles*8,n=t+(this.config.emissionPositionX||0),a=e+(this.config.emissionPositionY||0),o=i+(this.config.emissionPositionZ||0);this.particleData[r]=n,this.particleData[r+1]=a,this.particleData[r+2]=o;const c=this.activeParticles*4;return this.emitter.calculateVelocity(n,a,o,this.particleVelocities,c),this.emitter.setParticleColor(this.particleData,r),this.emitter.setParticleLifetime(this.particleData,r),this.activeParticles++,!0}updateParticles(t,e,i=0){const r=this.config.startAt||0,n=r>0&&i<r;if(this._particleScript&&this._scriptReadbackReady){this._scriptReadbackReady=!1,this._scriptTime+=t,this._scriptFrame++;const d=this.config.emissionDurationInfinite?1/0:(this.config.emissionDuration||0)+(this.config.lifetime||0);if(d>0&&this._scriptTime>=d&&!this._scriptConfigRestored)this._scriptConfigRestored=!0,this._particleScript._configSnapshot&&(this._particleScript.restoreConfig(this.config),this.updateAppearanceUniform(),this.updateBloomIntensity(),this.config.gravityEnabled&&this.setGravity(this.config.gravityStrength),this.config.dampingEnabled&&this.physics.setDamping(this.config.dampingStrength),this.config.attractorEnabled&&this.setAttractor(this.config.attractorStrength,this.config.attractorPosition,this.config.attractorReverse));else if(!this._scriptConfigRestored){const S=d>0?Math.ceil(d/.016666666666666666):0,{configDirty:b,particlesDirty:p}=this._particleScript.execute(t,this._scriptTime,this._scriptFrame,S,this._scriptParticleData,this._scriptVelocityData,this.activeParticles);p&&this.activeParticles>0&&(this.device.queue.writeBuffer(this.instanceBuffer,0,this._scriptParticleData,0,this.activeParticles*8),this.device.queue.writeBuffer(this.velocityBuffer,0,this._scriptVelocityData,0,this.activeParticles*4)),b&&(this.updateAppearanceUniform(),this.updateBloomIntensity(),this.config.gravityEnabled&&this.setGravity(this.config.gravityStrength),this.config.dampingEnabled&&this.physics.setDamping(this.config.dampingStrength),this.config.attractorEnabled&&this.setAttractor(this.config.attractorStrength,this.config.attractorPosition,this.config.attractorReverse))}}this.physics.physicsAccumulator+=t;const a=performance.now()/1e3,c=a-this.physics.lastUpdateTime>1/this.physics.minUpdatesPerSecond,l=this.activeParticles;if(!n&&!this.emitting&&!this.config.burstMode&&!this.config.followSystemId&&this.currentEmissionTime<this.effectiveEmissionDuration&&(this.emitting=!0),!n&&this.emitting)if(this.currentEmissionTime+=t,this.currentEmissionTime<this.effectiveEmissionDuration){const d=this.activeParticles;let S=!1;if(this.config.followSystemId){if(this._pendingFollowEmissions.length>0){const b=this._pendingFollowEmissions.length/6;for(let p=0;p<b;p++){const v=p*6;if(this.emitFollowerParticle(this._pendingFollowEmissions[v],this._pendingFollowEmissions[v+1],this._pendingFollowEmissions[v+2]))S=!0;else break}}}else{let b=0;const p=Math.max(0,this.config.emissionRate||0);this.activeParticles<this.particleCount&&p>0?(this.emissionAccumulator+=p*t,b=Math.floor(this.emissionAccumulator+1e-9),b>0&&(this.emissionAccumulator-=b)):this.activeParticles>=this.particleCount&&(this.emissionAccumulator=0);for(let v=0;v<b;v++)if(this.emitParticle())S=!0;else{this.emissionAccumulator=0;break}}if(S){const b=this.activeParticles-d,p=d*8,v=d*4;this.device.queue.writeBuffer(this.instanceBuffer,p*4,this.particleData,p,b*8),this.device.queue.writeBuffer(this.velocityBuffer,v*4,this.particleVelocities,v,b*4)}}else this.emitting=!1,this.currentEmissionTime=this.config.emissionDuration;for(;this.physics.physicsAccumulator>=this.physics.fixedDeltaTime;)this.physics.updatePhysics(this.physics.fixedDeltaTime,l,this.config,this.instanceBuffer,this.velocityBuffer,e),this.physics.physicsAccumulator-=this.physics.fixedDeltaTime,this.physics.physicsClock+=this.physics.fixedDeltaTime;c&&l>0&&(this.physics.updatePhysics(this.physics.fixedDeltaTime,l,this.config,this.instanceBuffer,this.velocityBuffer,e),this.physics.lastUpdateTime=a),this.frameCount++,(this.activeParticles>=this.particleCount||this.frameCount%300===0)&&this.readbackAndProcessParticles(),this._particleScript&&this.activeParticles>0&&!this._scriptReadbackPending&&(this._scriptReadbackPending=!0,this.physics.readbackForScript(this.activeParticles,this._scriptParticleData,this._scriptVelocityData,this.instanceBuffer,this.velocityBuffer).then(d=>{this._scriptReadbackPending=!1,d.shouldUpdate&&(this._scriptReadbackReady=!0)}).catch(()=>{this._scriptReadbackPending=!1}))}async readbackAndProcessParticles(){if(!(this.activeParticles<=0))try{if(!(await this.physics.readbackAndProcessParticles(this.activeParticles,this.particleData,this.particleVelocities,this.instanceBuffer,this.velocityBuffer)).shouldUpdate)return;let e=0,i=!1;for(let r=0;r<this.activeParticles;r++){const n=this.particleData[r*8+6],a=this.particleData[r*8+7];if(n>=a){if(this.emitting&&this.currentEmissionTime<this.effectiveEmissionDuration&&e<this.particleCount){this.respawnParticle(r,e),e++,i=!0;continue}continue}if(e!==r){const o=r*8,c=e*8;this.particleData.copyWithin(c,o,o+8);const l=r*4,d=e*4;this.particleVelocities.copyWithin(d,l,l+4),i=!0}e++}(e!==this.activeParticles||i)&&(this.activeParticles=e,this.device.queue.writeBuffer(this.instanceBuffer,0,this.particleData,0,this.activeParticles*8),this.device.queue.writeBuffer(this.velocityBuffer,0,this.particleVelocities,0,this.activeParticles*4))}catch(t){t&&t.name==="AbortError"||console.error("Error reading back particle data:",t)}}respawnParticle(t,e){!this.emitting||this.currentEmissionTime>=this.effectiveEmissionDuration||this.config.followSystemId||(this.emitter.emitParticle(this.particleData,e,this.particleVelocities),this._applySimTransformToParticle(e))}updateBuffers(){this.destroyed||!this.particleData||this.activeParticles>0&&this.device.queue.writeBuffer(this.instanceBuffer,0,this.particleData,0,this.activeParticles*8)}updateParticleColors(){if(!(this.destroyed||!this.particleData)){for(let t=0;t<this.activeParticles;t++){const e=t*8;if(this.config.randomColorEnabled&&this.config.randomColors.length>0){const i=this.config.randomColors,r=i[Math.floor(Math.random()*i.length)];this.particleData[e+3]=r[0],this.particleData[e+4]=r[1],this.particleData[e+5]=r[2]}else this.config.colorTransitionEnabled?(this.particleData[e+3]=this.config.startColor[0],this.particleData[e+4]=this.config.startColor[1],this.particleData[e+5]=this.config.startColor[2]):(this.particleData[e+3]=this.config.particleColor[0],this.particleData[e+4]=this.config.particleColor[1],this.particleData[e+5]=this.config.particleColor[2])}this.activeParticles>0&&this.device.queue.writeBuffer(this.instanceBuffer,0,this.particleData,0,this.activeParticles*8)}}updateParticleVelocities(){for(let t=0;t<this.activeParticles;t++){const e=t*8,i=t*4,r=this.particleData[e],n=this.particleData[e+1],a=this.particleData[e+2],o=this.particleVelocities[i],c=this.particleVelocities[i+1],l=this.particleVelocities[i+2],d=Math.sqrt(o*o+c*c+l*l);if(d>.001){const S=this.config.particleSpeed*2;this.particleVelocities[i]=o/d*S,this.particleVelocities[i+1]=c/d*S,this.particleVelocities[i+2]=l/d*S}else{const S=Math.sqrt(r*r+n*n+a*a);if(S>.001){const b=this.config.particleSpeed*2;this.particleVelocities[i]=r/S*b,this.particleVelocities[i+1]=n/S*b,this.particleVelocities[i+2]=a/S*b}else this.particleVelocities[i]=0,this.particleVelocities[i+1]=this.config.particleSpeed*2,this.particleVelocities[i+2]=0}}this.activeParticles>0&&this.device.queue.writeBuffer(this.velocityBuffer,0,this.particleVelocities,0,this.activeParticles*4)}async readbackForRendering(t,e){return this.physics.readbackForRendering(this.activeParticles,t,e,this.instanceBuffer,this.velocityBuffer)}destroy(){this.destroyed=!0,this.instanceBuffer.destroy(),this.velocityBuffer.destroy(),this.trailBuffer.destroy(),this.appearanceUniformBuffer.destroy(),this.bloomIntensityBuffer.destroy(),this.physics.destroy(),this.glbVertexBuffer&&(this.glbVertexBuffer.destroy(),this.glbVertexBuffer=null),this.glbIndexBuffer&&(this.glbIndexBuffer.destroy(),this.glbIndexBuffer=null),this.textureManager.destroyTexture(this.particleTexture),this._particleScript&&(this._particleScript.destroy(),this._particleScript=null),this.glbAnimator=null,this.glbMeshData=null,this.glbRawArrayBuffer=null,this.particleData=null,this.particleVelocities=null,this._scriptParticleData=null,this._scriptVelocityData=null}setGravity(t){this.physics.setGravity(t)}setAttractor(t,e,i=this.config.attractorReverse){this.config.attractorStrength=t,this.config.attractorPosition=e,this.config.attractorReverse=!!i,this.physics.setAttractor(t,e,i)}setConfinement(t){const e=t.center||this.config.confinementCenter||[0,0,0],i=t.space==="local"?[this.config.emissionPositionX||0,this.config.emissionPositionY||0,this.config.emissionPositionZ||0]:[0,0,0],r=[i[0]+(e[0]||0),i[1]+(e[1]||0),i[2]+(e[2]||0)];this.physics.setConfinement({...t,center:r})}setSoftBoundary(t){this.physics.setSoftBoundary(t)}}class cs{constructor(t){this.device=t,this.particleSystems=[],this.activeSystemIndex=0,this.systemCounter=1,this.onSystemCreated=null,this.loop=void 0,this.clock=new os({loop:!!this.loop}),this.ready=!0}createParticleSystem(t={}){const e=this.systemCounter++,i=t.name||`System ${e+1}`,r={...t,name:i,id:e},n=new kt(this.device,r);return this.particleSystems.push({system:n,config:r}),this.particleSystems.length===1&&(this.activeSystemIndex=0),this.onSystemCreated&&typeof this.onSystemCreated=="function"&&this.onSystemCreated(e,r),e}getActiveSystem(){return this.particleSystems.length===0?null:this.particleSystems[this.activeSystemIndex].system}getActiveConfig(){return this.particleSystems.length===0?null:this.particleSystems[this.activeSystemIndex].config}setActiveSystem(t){return t>=0&&t<this.particleSystems.length?(this.activeSystemIndex=t,!0):!1}getSystemById(t){return this.particleSystems.find(({config:e})=>e.id===t)||null}destroy(){for(const{system:t}of this.particleSystems)t.destroy();this.particleSystems=[],this.activeSystemIndex=0}removeSystem(t){if(t>=0&&t<this.particleSystems.length){const e=this.particleSystems[t].config;this.particleSystems[t].system.destroy(),this.particleSystems.splice(t,1);const i=e.id;for(const{config:r}of this.particleSystems)r.followSystemId===i&&(r.followSystemId=null);return this.particleSystems.length===0?this.activeSystemIndex=0:t<=this.activeSystemIndex&&(this.activeSystemIndex=Math.max(0,this.activeSystemIndex-1)),!0}return!1}respawnAllSystems(){var t;(t=this.clock)==null||t.reset();for(const{system:e,config:i}of this.particleSystems)e.spawnParticles(()=>this._applyKeyframesToSystem(e,i,0))}getTotalDuration(){let t=0;for(const{config:e}of this.particleSystems){if(e.emissionDurationInfinite)return 1/0;const i=e.lifetime||5,r=(e.burstMode||e.oneOnlyMode?i:(e.emissionDuration||10)+i)+(e.startAt||0);r>t&&(t=r)}return t||1}updateAllSystems(t){const e=this.device.createCommandEncoder({label:"BatchedPhysicsEncoder"});let i=!1;const r=this.clock?this.clock.currentTime:0,n=this.clock?this.clock.duration:0;if(this.clock&&n>0&&isFinite(n)){const a=Math.min(1,this.clock.currentTime/n);for(const{system:o,config:c}of this.particleSystems)this._applyKeyframesToSystem(o,c,a)}for(const{system:a,config:o}of this.particleSystems){if(o.hidden||o.followSystemId)continue;const c=a.activeParticles>0;a.updateParticles(t,e,r),(c||a.activeParticles>0)&&(i=!0)}for(const{system:a,config:o}of this.particleSystems){if(o.hidden||!o.followSystemId)continue;const c=this.getSystemById(o.followSystemId);c&&(a._pendingFollowEmissions=c.system._newEmissions);const l=a.activeParticles>0;a.updateParticles(t,e,r),(l||a.activeParticles>0)&&(i=!0)}i&&this.device.queue.submit([e.finish()]);for(const{system:a}of this.particleSystems)a._newEmissions.length=0,a._pendingFollowEmissions=a._emptyEmissions}getSystemsList(){return this.particleSystems.map(({config:t},e)=>({name:t.name,id:t.id,index:e,isActive:e===this.activeSystemIndex,hidden:t.hidden||!1}))}duplicateActiveSystem(){if(this.particleSystems.length===0)return-1;const t=this.getActiveConfig(),e=JSON.parse(JSON.stringify(t));return e.name=`${t.name} (Copy)`,e.onAppearanceChange=null,e.onColorChange=null,e.onSizeChange=null,e.onSpeedChange=null,e.onPhysicsChange=null,e.onBloomIntensityChange=null,e.onRespawn=null,e.getActiveSystem=null,delete e.id,this.createParticleSystem(e)}async replaceSystems(t){var e;if(!t||!t.systems||!Array.isArray(t.systems))return console.error("Invalid scene data provided"),!1;this.ready=!1;try{this.particleSystems=[],this.systemCounter=1;for(const r of t.systems){const n=this.systemCounter++,a={...r,id:n},o=new kt(this.device,a);this.particleSystems.push({system:o,config:a})}const i={};t.systems.forEach((r,n)=>{i[r.id]=this.particleSystems[n].config.id});for(const{config:r}of this.particleSystems)r.followSystemId&&i[r.followSystemId]!==void 0&&(r.followSystemId=i[r.followSystemId]);t.activeSystemIndex!==void 0&&t.activeSystemIndex>=0&&t.activeSystemIndex<this.particleSystems.length?this.activeSystemIndex=t.activeSystemIndex:this.activeSystemIndex=0,this.loop=t.loop;for(const{system:r,config:n}of this.particleSystems)if(n.glbModelEnabled)try{let a=null;if(n.glbModelData)a=ji(n.glbModelData);else if(n.glbFileName){const o=await fetch(`/${n.glbFileName}`);o.ok?a=await o.arrayBuffer():console.warn(`GLB file not found: ${n.glbFileName}`)}if(a){if(await r.setGLBModel(a),n.animationIndex!==void 0&&r.glbAnimator&&r.glbAnimator.setAnimation(n.animationIndex),n.animationSpeed!==void 0&&r.glbAnimator&&(r.glbAnimator.speed=n.animationSpeed),n.animationLoop!==void 0&&r.glbAnimator&&(r.glbAnimator.loop=n.animationLoop),n.useGlbTexture&&(n.textureEnabled=!0),n.useGlbTexture&&((e=r.glbMeshData)!=null&&e.hasBaseColorTexture))try{const o=await oi(a);if(o){const c=await createImageBitmap(o.imageBlob);await r.setTexture(c),globalThis.__HZFX_DEBUG&&console.log(`GLB embedded texture restored for ${n.name}`)}}catch(o){console.warn(`Failed to restore GLB texture for ${n.name}:`,o),n.useGlbTexture=!1}}else n.glbModelEnabled=!1}catch(a){console.warn(`Failed to load GLB for ${n.name}:`,a),n.glbModelEnabled=!1}for(const{system:r,config:n}of this.particleSystems)if(n.textureEnabled&&!n.glbModelEnabled&&n.textureImageData)try{const a=new Image;await new Promise((c,l)=>{a.onload=c,a.onerror=l,a.src=n.textureImageData});const o=await createImageBitmap(a);await r.setTexture(o)}catch(a){console.warn(`Failed to restore texture for ${n.name}:`,a),n.textureEnabled=!1}for(const{system:r,config:n}of this.particleSystems)r.updateAppearanceUniform();return this.respawnAllSystems(),!0}catch(i){return console.error("Error replacing systems:",i),!1}finally{this.ready=!0}}async addSystems(t,e=[0,0,0]){var r;if(!t||!t.systems||!Array.isArray(t.systems))return console.error("Invalid scene data provided"),!1;this.ready=!1;const i=[];try{for(const o of t.systems){const c=this.systemCounter++;i.push(c);const l={...o,id:c,emissionPositionX:(o.emissionPositionX||0)+e[0],emissionPositionY:(o.emissionPositionY||0)+e[1],emissionPositionZ:(o.emissionPositionZ||0)+e[2]};o.attractorEnabled&&o.attractorPosition&&(l.attractorPosition=[o.attractorPosition[0]+e[0],o.attractorPosition[1]+e[1],o.attractorPosition[2]+e[2]]),o.confinementEnabled&&o.confinementSpace==="world"&&Array.isArray(o.confinementCenter)&&(l.confinementCenter=[(o.confinementCenter[0]||0)+e[0],(o.confinementCenter[1]||0)+e[1],(o.confinementCenter[2]||0)+e[2]]);const d=new kt(this.device,l);this.particleSystems.push({system:d,config:l}),this.onSystemCreated&&typeof this.onSystemCreated=="function"&&this.onSystemCreated(c,l)}const n=this.particleSystems.length-t.systems.length,a={};t.systems.forEach((o,c)=>{a[o.id]=this.particleSystems[n+c].config.id});for(let o=n;o<this.particleSystems.length;o++){const{config:c}=this.particleSystems[o];c.followSystemId&&a[c.followSystemId]!==void 0&&(c.followSystemId=a[c.followSystemId])}for(const{system:o,config:c}of this.particleSystems)if(c.glbModelEnabled&&!o.glbMeshData)try{let l=null;if(c.glbModelData)l=ji(c.glbModelData);else if(c.glbFileName){const d=await fetch(`/${c.glbFileName}`);d.ok?l=await d.arrayBuffer():console.warn(`GLB file not found: ${c.glbFileName}`)}if(l){if(await o.setGLBModel(l),c.animationIndex!==void 0&&o.glbAnimator&&o.glbAnimator.setAnimation(c.animationIndex),c.animationSpeed!==void 0&&o.glbAnimator&&(o.glbAnimator.speed=c.animationSpeed),c.animationLoop!==void 0&&o.glbAnimator&&(o.glbAnimator.loop=c.animationLoop),c.useGlbTexture&&(c.textureEnabled=!0),c.useGlbTexture&&((r=o.glbMeshData)!=null&&r.hasBaseColorTexture))try{const d=await oi(l);if(d){const S=await createImageBitmap(d.imageBlob);await o.setTexture(S),globalThis.__HZFX_DEBUG&&console.log(`GLB embedded texture restored for ${c.name}`)}}catch(d){console.warn(`Failed to restore GLB texture for ${c.name}:`,d),c.useGlbTexture=!1}}else c.glbModelEnabled=!1}catch(l){console.warn(`Failed to load GLB for ${c.name}:`,l),c.glbModelEnabled=!1}for(const{system:o,config:c}of this.particleSystems)if(c.textureEnabled&&!c.glbModelEnabled&&c.textureImageData&&!o._textureRestored)try{const l=new Image;await new Promise((S,b)=>{l.onload=S,l.onerror=b,l.src=c.textureImageData});const d=await createImageBitmap(l);await o.setTexture(d),o._textureRestored=!0}catch(l){console.warn(`Failed to restore texture for ${c.name}:`,l),c.textureEnabled=!1}return i}catch(n){return console.error("Error adding systems:",n),!1}finally{this.ready=!0}}_applyKeyframesToSystem(t,e,i){const r=e.keyframes;if(!r||e.keyframesEnabled===!1)return;let n=!1,a=!1,o=!1,c=!1,l=!1;for(const d of Gr){const S=r[d];if(!S||!S.length)continue;const b=Ir(S,i);if(b!==void 0){if(d==="damping"){e.dampingStrength=b,c=!0;continue}e[d]=b,(d==="particleSize"||d==="opacity")&&(n=!0),d==="bloomIntensity"&&(a=!0),d==="gravityStrength"&&(o=!0),d==="dampingStrength"&&(c=!0),(d==="attractorStrength"||d==="attractorReverse")&&(l=!0)}}if(r.particleColor&&r.particleColor.length){const d=e.particleColor,S=d&&typeof d.length=="number"&&d.length>=3?d:void 0,b=zr(r.particleColor,i,S);b&&(e.particleColor=b,n=!0)}n&&t.updateAppearanceUniform(),a&&t.updateBloomIntensity(),o&&e.gravityEnabled&&t.setGravity(e.gravityStrength),c&&e.dampingEnabled&&t.physics.setDamping(e.dampingStrength),l&&e.attractorEnabled&&e.attractorPosition&&t.setAttractor(e.attractorStrength,e.attractorPosition,e.attractorReverse)}}async function us(s){if(!s)throw new Error("canvas is required for initWebGPU()");if(!navigator.gpu)throw new Error("WebGPU not supported on this browser.");const t=s.getContext("webgpu"),i=await(await navigator.gpu.requestAdapter()).requestDevice(),r=navigator.gpu.getPreferredCanvasFormat();return t.configure({device:i,format:r,alphaMode:"premultiplied"}),{device:i,context:t,format:r,canvas:s}}const ke="rgba16float";function li(s,t,e,i){const r=s.createTexture({size:[e,i],format:ke,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),n=s.createTexture({size:[e,i],format:ke,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),a=s.createTexture({size:[e,i],format:ke,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1});return{sceneTexture:r,bloomTexA:n,bloomTexB:a}}function ci(s,t,e){return s.createTexture({size:[t,e],format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT})}function pt(s,t,e){const i=s.createBuffer({size:t.byteLength,usage:e,mappedAtCreation:!0});return new t.constructor(i.getMappedRange()).set(t),i.unmap(),i}const ds=`
896
+ ${xr(t)}
897
+ };`,r=new Function(i);this._fn=r()}catch(e){console.warn("[ParticleScript] Compilation error:",e.message),this._fn=null,this._error=!0}}execute(t,e,i,r,a,n,o){if(!this._fn||this._error)return{configDirty:!1,particlesDirty:!1};this._particles._bind(a,n,o),this._configProxy.__resetDirty();try{this._fn(t,e,i,r,this._particles,this._configProxy,as)}catch(l){console.warn("[ParticleScript] Runtime error:",l.message)}return{configDirty:this._configProxy.__dirty,particlesDirty:this._particles._dirty}}snapshotConfig(t){const e={};for(const i of Ct){const r=t[i];r!==void 0&&(e[i]=Array.isArray(r)?[...r]:r)}this._configSnapshot=e}restoreConfig(t){if(this._configSnapshot){for(const e of Ct)if(e in this._configSnapshot){const i=this._configSnapshot[e];t[e]=Array.isArray(i)?[...i]:i}}}destroy(){this._fn=null,this._particles=null,this._configProxy=null,this._configSnapshot=null}}async function ns(s){const t=new DataView(s);if(t.getUint32(0,!0)!==1179937895)throw new Error("Invalid GLB file: incorrect magic number");const i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i} (only version 2 is supported)`);const r=t.getUint32(8,!0);let a=12,n=null,o=null;for(;a<r;){const T=t.getUint32(a,!0),G=t.getUint32(a+4,!0),F=s.slice(a+8,a+8+T);if(G===1313821514){const se=new TextDecoder("utf-8").decode(F);n=JSON.parse(se)}else G===5130562&&(o=F);a+=8+T}if(!n)throw new Error("GLB file missing JSON chunk");if(!n.meshes||n.meshes.length===0)throw new Error("GLB file contains no meshes");const c=n.meshes[0].primitives[0];if(!c)throw new Error("First mesh has no primitives");const d=c.attributes.POSITION;if(d===void 0)throw new Error("Mesh primitive missing POSITION attribute");const S=si(n,o,d,3,5126);let b;if(c.attributes.NORMAL!==void 0)b=si(n,o,c.attributes.NORMAL,3,5126);else{const T=c.indices;if(T===void 0)throw new Error("Cannot generate normals without indices");const G=Xi(n,o,T);b=Pr(S,G)}const h=c.indices;if(h===void 0)throw new Error("Mesh primitive missing indices");const v=Xi(n,o,h),C=S.length/3,z=v.length;let D=null;c.attributes.TEXCOORD_0!==void 0&&(D=si(n,o,c.attributes.TEXCOORD_0,2,5126));let _=!1;if(n.materials&&n.materials.length>0){const T=n.materials[0];T.pbrMetallicRoughness&&T.pbrMetallicRoughness.baseColorTexture!==void 0&&(_=!0)}let Z=null;if(n.skins&&n.skins.length>0)try{Z=Tr(n,o,c),globalThis.__HZFX_DEBUG&&console.log("Animation data extracted:",Z)}catch(T){console.warn("Failed to extract animation data:",T)}return{positions:S,normals:b,indices:v,texCoords:D,vertexCount:C,indexCount:z,animationData:Z,hasBaseColorTexture:_}}function si(s,t,e,i,r){const a=s.accessors[e],o={SCALAR:1,VEC2:2,VEC3:3,VEC4:4}[a.type];if(o!==i)throw new Error(`Attribute accessor type mismatch: expected ${i} components, got ${o}`);if(a.componentType!==r)throw new Error(`Attribute component type mismatch: expected ${r}, got ${a.componentType}`);const c=(s.bufferViews[a.bufferView].byteOffset||0)+(a.byteOffset||0),d=a.count,S=new DataView(t,c,d*i*4),b=new Float32Array(d*i);for(let h=0;h<d*i;h++)b[h]=S.getFloat32(h*4,!0);return b}function Xi(s,t,e){const i=s.accessors[e];if(i.type!=="SCALAR")throw new Error(`Indices accessor must be SCALAR, got ${i.type}`);const a=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),n=i.count;if(i.componentType===5123){const o=new DataView(t,a,n*2),l=new Uint16Array(n);for(let c=0;c<n;c++)l[c]=o.getUint16(c*2,!0);return l}else if(i.componentType===5125){const o=new DataView(t,a,n*4),l=new Uint32Array(n);for(let c=0;c<n;c++)l[c]=o.getUint32(c*4,!0);return l}else throw new Error(`Unsupported index component type: ${i.componentType}`)}function Pr(s,t){const e=new Float32Array(s.length);for(let i=0;i<t.length;i+=3){const r=t[i]*3,a=t[i+1]*3,n=t[i+2]*3,o=[s[r],s[r+1],s[r+2]],l=[s[a],s[a+1],s[a+2]],c=[s[n],s[n+1],s[n+2]],d=[l[0]-o[0],l[1]-o[1],l[2]-o[2]],S=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],b=[d[1]*S[2]-d[2]*S[1],d[2]*S[0]-d[0]*S[2],d[0]*S[1]-d[1]*S[0]],h=Math.sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]);h>0&&(b[0]/=h,b[1]/=h,b[2]/=h),e[r]=e[a]=e[n]=b[0],e[r+1]=e[a+1]=e[n+1]=b[1],e[r+2]=e[a+2]=e[n+2]=b[2]}return e}function _r(s,t,e){const i=s.accessors[e];if(i.type!=="VEC4")throw new Error(`JOINTS_0 must be VEC4, got ${i.type}`);const a=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),n=i.count;if(i.componentType===5121){const o=new DataView(t,a,n*4),l=new Uint8Array(n*4);for(let c=0;c<n*4;c++)l[c]=o.getUint8(c);return l}else if(i.componentType===5123){const o=new DataView(t,a,n*8),l=new Uint8Array(n*4);for(let c=0;c<n*4;c++)l[c]=o.getUint16(c*2,!0);return l}else throw new Error(`Unsupported JOINTS_0 component type: ${i.componentType}`)}function Mr(s,t,e){const i=s.accessors[e];if(i.type!=="VEC4")throw new Error(`WEIGHTS_0 must be VEC4, got ${i.type}`);const a=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),n=i.count;if(i.componentType===5126){const o=new DataView(t,a,n*16),l=new Float32Array(n*4);for(let c=0;c<n*4;c++)l[c]=o.getFloat32(c*4,!0);return l}else if(i.componentType===5121){const o=new DataView(t,a,n*4),l=new Float32Array(n*4);for(let c=0;c<n*4;c++)l[c]=o.getUint8(c)/255;return l}else throw new Error(`Unsupported WEIGHTS_0 component type: ${i.componentType}`)}function wr(s,t,e){const i=s.accessors[e];if(i.type!=="MAT4")throw new Error(`Expected MAT4, got ${i.type}`);if(i.componentType!==5126)throw new Error(`Expected FLOAT component type for MAT4, got ${i.componentType}`);const a=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),n=i.count,o=new DataView(t,a,n*64),l=new Float32Array(n*16);for(let c=0;c<n*16;c++)l[c]=o.getFloat32(c*4,!0);return l}function Rr(s,t,e){const i=s.accessors[e];if(i.type!=="SCALAR")throw new Error(`Expected SCALAR, got ${i.type}`);if(i.componentType!==5126)throw new Error(`Expected FLOAT component type for SCALAR, got ${i.componentType}`);const a=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),n=i.count,o=new DataView(t,a,n*4),l=new Float32Array(n);for(let c=0;c<n;c++)l[c]=o.getFloat32(c*4,!0);return l}function Br(s,t,e){const i=s.accessors[e],a={VEC3:3,VEC4:4}[i.type];if(!a)throw new Error(`Expected VEC3 or VEC4, got ${i.type}`);if(i.componentType!==5126)throw new Error(`Expected FLOAT component type, got ${i.componentType}`);const o=(s.bufferViews[i.bufferView].byteOffset||0)+(i.byteOffset||0),l=i.count,c=new DataView(t,o,l*a*4),d=new Float32Array(l*a);for(let S=0;S<l*a;S++)d[S]=c.getFloat32(S*4,!0);return d}function Tr(s,t,e){const i=s.skins[0],r=i.joints,a=wr(s,t,i.inverseBindMatrices),n=e.attributes.JOINTS_0!==void 0?_r(s,t,e.attributes.JOINTS_0):null,o=e.attributes.WEIGHTS_0!==void 0?Mr(s,t,e.attributes.WEIGHTS_0):null;if(!n||!o)throw new Error("Mesh missing JOINTS_0 or WEIGHTS_0 attributes");const l=s.nodes.map(d=>({translation:d.translation||[0,0,0],rotation:d.rotation||[0,0,0,1],scale:d.scale||[1,1,1],children:d.children||[],name:d.name||""})),c=[];if(s.animations&&s.animations.length>0)for(const d of s.animations){const S=[];let b=0;for(const h of d.channels){const v=d.samplers[h.sampler],C=Rr(s,t,v.input),z=Br(s,t,v.output),D=C[C.length-1];D>b&&(b=D),S.push({targetNode:h.target.node,targetPath:h.target.path,interpolation:v.interpolation||"LINEAR",timestamps:C,values:z})}c.push({name:d.name||`Animation ${c.length}`,duration:b,channels:S})}return{joints:r,inverseBindMatrices:a,jointIndices:n,jointWeights:o,nodes:l,animations:c}}async function oi(s){const t=new DataView(s);if(t.getUint32(0,!0)!==1179937895)throw new Error("Invalid GLB file: incorrect magic number");const i=t.getUint32(4,!0);if(i!==2)throw new Error(`Unsupported GLB version: ${i}`);const r=t.getUint32(8,!0);let a=12,n=null,o=null;for(;a<r;){const Z=t.getUint32(a,!0),T=t.getUint32(a+4,!0),G=s.slice(a+8,a+8+Z);if(T===1313821514){const H=new TextDecoder("utf-8").decode(G);n=JSON.parse(H)}else T===5130562&&(o=G);a+=8+Z}if(!n)throw new Error("GLB file missing JSON chunk");if(!n.materials||n.materials.length===0)return null;const l=n.materials[0];if(!l.pbrMetallicRoughness||l.pbrMetallicRoughness.baseColorTexture===void 0)return null;const c=l.pbrMetallicRoughness.baseColorTexture.index;if(!n.textures||!n.textures[c])return null;const S=n.textures[c].source;if(S===void 0||!n.images||!n.images[S])return null;const b=n.images[S],h=b.mimeType||"image/png";if(b.bufferView===void 0)return null;if(!o)throw new Error("GLB file missing BIN chunk (required for embedded textures)");const v=n.bufferViews[b.bufferView],C=v.byteOffset||0,z=v.byteLength,D=o.slice(C,C+z);return{imageBlob:new Blob([D],{type:h}),mimeType:h}}function Er(s,t,e,i){return i=i||[0,0,0],i[0]=s[0]+(t[0]-s[0])*e,i[1]=s[1]+(t[1]-s[1])*e,i[2]=s[2]+(t[2]-s[2])*e,i}function Ar(s,t,e,i){i=i||[0,0,0,0];let r=s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3],a=1;if(r<0&&(r=-r,a=-1),r>.9995){i[0]=s[0]+(a*t[0]-s[0])*e,i[1]=s[1]+(a*t[1]-s[1])*e,i[2]=s[2]+(a*t[2]-s[2])*e,i[3]=s[3]+(a*t[3]-s[3])*e;const d=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]);return d>1e-4?(i[0]/=d,i[1]/=d,i[2]/=d,i[3]/=d):(i[0]=0,i[1]=0,i[2]=0,i[3]=1),i}const n=Math.acos(r),o=Math.sin(n),l=Math.sin((1-e)*n)/o,c=Math.sin(e*n)/o;return i[0]=s[0]*l+a*t[0]*c,i[1]=s[1]*l+a*t[1]*c,i[2]=s[2]*l+a*t[2]*c,i[3]=s[3]*l+a*t[3]*c,i}function Cr(s,t){const e=s[0],i=s[1],r=s[2],a=s[3],n=e+e,o=i+i,l=r+r,c=e*n,d=e*o,S=e*l,b=i*o,h=i*l,v=r*l,C=a*n,z=a*o,D=a*l,_=t||new Float32Array(16);return _[0]=1-(b+v),_[1]=d+D,_[2]=S-z,_[3]=0,_[4]=d-D,_[5]=1-(c+v),_[6]=h+C,_[7]=0,_[8]=S+z,_[9]=h-C,_[10]=1-(c+b),_[11]=0,_[12]=0,_[13]=0,_[14]=0,_[15]=1,_}const Ur=new Float32Array(16);function Ir(s,t,e,i){const r=Cr(t,Ur),a=i||new Float32Array(16);return a[0]=r[0]*e[0],a[1]=r[1]*e[0],a[2]=r[2]*e[0],a[3]=0,a[4]=r[4]*e[1],a[5]=r[5]*e[1],a[6]=r[6]*e[1],a[7]=0,a[8]=r[8]*e[2],a[9]=r[9]*e[2],a[10]=r[10]*e[2],a[11]=0,a[12]=s[0],a[13]=s[1],a[14]=s[2],a[15]=1,a}function Ni(s,t,e){const i=e||new Float32Array(16);for(let r=0;r<4;r++)for(let a=0;a<4;a++)i[r*4+a]=s[0+a]*t[r*4+0]+s[4+a]*t[r*4+1]+s[8+a]*t[r*4+2]+s[12+a]*t[r*4+3];return i}class os{constructor(t){this.joints=t.joints,this.inverseBindMatrices=t.inverseBindMatrices,this.jointWeights=t.jointWeights,this.jointIndices=t.jointIndices,this.nodes=t.nodes,this.animations=t.animations,this.restPositions=null,this.restNormals=null,this.currentAnimIndex=0,this.currentTime=0,this.playing=!0,this.speed=1,this.loop=!0,this.jointLocalTransforms=new Array(this.nodes.length),this.jointGlobalTransforms=new Array(this.nodes.length),this.jointFinalMatrices=new Array(this.joints.length);for(let e=0;e<this.nodes.length;e++)this.jointLocalTransforms[e]=new Float32Array(16),this.jointGlobalTransforms[e]=new Float32Array(16);for(let e=0;e<this.joints.length;e++)this.jointFinalMatrices[e]=new Float32Array(16);this.skinnedPositions=null,this.skinnedNormals=null,this._gpuSkinningReady=!1,this._sV0=new Float64Array(4),this._sV1=new Float64Array(4),this._scrT=new Float64Array(3),this._scrR=new Float64Array(4),this._scrS=new Float64Array(3),this._buildTopologicalOrder(),this._parentMap=new Array(this.nodes.length).fill(-1);for(let e=0;e<this.nodes.length;e++)for(const i of this.nodes[e].children)this._parentMap[i]=e;this._invBindViews=new Array(this.joints.length);for(let e=0;e<this.joints.length;e++)this._invBindViews[e]=this.inverseBindMatrices.subarray(e*16,e*16+16)}setRestPose(t,e){this.restPositions=new Float32Array(t),this.restNormals=new Float32Array(e),this.skinnedPositions=new Float32Array(t.length),this.skinnedNormals=new Float32Array(e.length)}async initGPUSkinning(t,e,i){try{this._gpuDevice=t,this._gpuOutputBuffer=e;const r=this.restPositions.length/3,a=new Float32Array(r*8);for(let l=0;l<r;l++){const c=l*8,d=l*3,S=l*2;a[c]=this.restPositions[d],a[c+1]=this.restPositions[d+1],a[c+2]=this.restPositions[d+2],a[c+3]=this.restNormals[d],a[c+4]=this.restNormals[d+1],a[c+5]=this.restNormals[d+2],a[c+6]=i?i[S]:0,a[c+7]=i?i[S+1]:0}this._gpuRestDataBuffer=t.createBuffer({size:a.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_restData"}),t.queue.writeBuffer(this._gpuRestDataBuffer,0,a),this._gpuJointWeightsBuffer=t.createBuffer({size:this.jointWeights.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_jointWeights"}),t.queue.writeBuffer(this._gpuJointWeightsBuffer,0,this.jointWeights);const n=new Uint32Array(this.jointIndices.length);for(let l=0;l<this.jointIndices.length;l++)n[l]=this.jointIndices[l];this._gpuJointIndicesBuffer=t.createBuffer({size:n.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_jointIndices"}),t.queue.writeBuffer(this._gpuJointIndicesBuffer,0,n),this._gpuJointMatricesBuffer=t.createBuffer({size:this.joints.length*16*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"skinning_jointMatrices"}),this._gpuJointMatricesData=new Float32Array(this.joints.length*16);const o=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]});this._gpuSkinningPipeline=t.createComputePipeline({layout:t.createPipelineLayout({bindGroupLayouts:[o]}),compute:{module:t.createShaderModule({code:yr}),entryPoint:"main"}}),this._gpuSkinningBindGroup=t.createBindGroup({layout:o,entries:[{binding:0,resource:{buffer:this._gpuRestDataBuffer}},{binding:1,resource:{buffer:this._gpuJointWeightsBuffer}},{binding:2,resource:{buffer:this._gpuJointIndicesBuffer}},{binding:3,resource:{buffer:this._gpuJointMatricesBuffer}},{binding:4,resource:{buffer:this._gpuOutputBuffer}}]}),this._gpuVertexCount=r,this._gpuSkinningReady=!0,globalThis.__HZFX_DEBUG&&console.log(`GPU skinning initialized: ${r} vertices, ${this.joints.length} joints`)}catch(r){console.warn("GPU skinning init failed, using CPU fallback:",r),this._gpuSkinningReady=!1}}_applySkinningGPU(){for(let i=0;i<this.joints.length;i++)this._gpuJointMatricesData.set(this.jointFinalMatrices[i],i*16);this._gpuDevice.queue.writeBuffer(this._gpuJointMatricesBuffer,0,this._gpuJointMatricesData);const t=this._gpuDevice.createCommandEncoder({label:"SkinningComputeEncoder"}),e=t.beginComputePass({label:"SkinningComputePass"});e.setPipeline(this._gpuSkinningPipeline),e.setBindGroup(0,this._gpuSkinningBindGroup),e.dispatchWorkgroups(Math.ceil(this._gpuVertexCount/64),1,1),e.end(),this._gpuDevice.queue.submit([t.finish()])}update(t){if(!this.playing||this.animations.length===0)return{positions:this.skinnedPositions,normals:this.skinnedNormals,changed:!1};this.currentTime+=t*this.speed;const e=this.animations[this.currentAnimIndex];return this.loop?this.currentTime=this.currentTime%e.duration:this.currentTime>e.duration&&(this.currentTime=e.duration,this.playing=!1),this._computeLocalTransforms(this.currentTime),this._computeGlobalTransforms(),this._computeFinalMatrices(),this._gpuSkinningReady?(this._applySkinningGPU(),{gpuSkinned:!0,changed:!0}):(this._applySkinning(),{positions:this.skinnedPositions,normals:this.skinnedNormals,changed:!0})}getCurrentAnimation(){return this.animations[this.currentAnimIndex]}setAnimation(t){t>=0&&t<this.animations.length&&(this.currentAnimIndex=t,this.currentTime=0)}getAnimationNames(){return this.animations.map(t=>t.name)}_buildTopologicalOrder(){const t=new Set,e=[],i=a=>{if(t.has(a))return;t.add(a);const n=this.nodes[a];for(const o of n.children)i(o);e.push(a)},r=new Set;for(const a of this.nodes)for(const n of a.children)r.add(n);for(let a=0;a<this.nodes.length;a++)r.has(a)||i(a);this.topologicalOrder=e.reverse()}_sampleChannel(t,e,i){const{timestamps:r,values:a,interpolation:n,targetPath:o}=t;if(e<=r[0])return this._extractValue(a,0,o,i);if(e>=r[r.length-1])return this._extractValue(a,r.length-1,o,i);let l=0,c=r.length-1;for(;c-l>1;){const C=Math.floor((l+c)/2);r[C]<=e?l=C:c=C}const d=r[l],S=r[c],b=(e-d)/(S-d),h=this._extractValue(a,l,o,this._sV0),v=this._extractValue(a,c,o,this._sV1);return n==="STEP"?(i[0]=h[0],i[1]=h[1],i[2]=h[2],o==="rotation"&&(i[3]=h[3]),i):o==="rotation"?Ar(h,v,b,i):Er(h,v,b,i)}_extractValue(t,e,i,r){if(i==="rotation"){const a=e*4;r[0]=t[a],r[1]=t[a+1],r[2]=t[a+2],r[3]=t[a+3]}else{const a=e*3;r[0]=t[a],r[1]=t[a+1],r[2]=t[a+2]}return r}_computeLocalTransforms(t){const e=this.animations[this.currentAnimIndex];for(let i=0;i<this.nodes.length;i++){const r=this.nodes[i];let a=r.translation,n=r.rotation,o=r.scale;for(const l of e.channels)l.targetNode===i&&(l.targetPath==="translation"?a=this._sampleChannel(l,t,this._scrT):l.targetPath==="rotation"?n=this._sampleChannel(l,t,this._scrR):l.targetPath==="scale"&&(o=this._sampleChannel(l,t,this._scrS)));Ir(a,n,o,this.jointLocalTransforms[i])}}_computeGlobalTransforms(){const t=this._parentMap;for(const e of this.topologicalOrder){const i=t[e];i===-1?this.jointGlobalTransforms[e].set(this.jointLocalTransforms[e]):Ni(this.jointGlobalTransforms[i],this.jointLocalTransforms[e],this.jointGlobalTransforms[e])}}_computeFinalMatrices(){for(let t=0;t<this.joints.length;t++){const e=this.joints[t],i=this.jointGlobalTransforms[e];Ni(i,this._invBindViews[t],this.jointFinalMatrices[t])}}_applySkinning(){const t=this.restPositions.length/3,e=this.restPositions,i=this.restNormals,r=this.skinnedPositions,a=this.skinnedNormals,n=this.jointWeights,o=this.jointIndices,l=this.jointFinalMatrices;for(let c=0;c<t;c++){const d=c*3,S=c*4,b=e[d],h=e[d+1],v=e[d+2],C=i[d],z=i[d+1],D=i[d+2];let _=0,Z=0,T=0,G=0,F=0,H=0;for(let ae=0;ae<4;ae++){const re=n[S+ae];if(re===0)continue;const j=l[o[S+ae]];_+=(j[0]*b+j[4]*h+j[8]*v+j[12])*re,Z+=(j[1]*b+j[5]*h+j[9]*v+j[13])*re,T+=(j[2]*b+j[6]*h+j[10]*v+j[14])*re,G+=(j[0]*C+j[4]*z+j[8]*D)*re,F+=(j[1]*C+j[5]*z+j[9]*D)*re,H+=(j[2]*C+j[6]*z+j[10]*D)*re}const se=Math.sqrt(G*G+F*F+H*H);se>1e-4&&(a[d]=G/se,a[d+1]=F/se,a[d+2]=H/se),r[d]=_,r[d+1]=Z,r[d+2]=T}}}class ls{constructor({duration:t=0,loop:e=!1,playbackRate:i=1}={}){this.currentTime=0,this.duration=t,this.loop=e,this.playbackRate=i,this.paused=!1,this._justLooped=!1}tick(t){if(this.paused)return 0;const e=t*this.playbackRate;return this.currentTime+=e,this._justLooped=!1,this.loop&&this.duration>0&&isFinite(this.duration)&&this.currentTime>=this.duration&&(this.currentTime=0,this._justLooped=!0),e}get justLooped(){return this._justLooped}reset(){this.currentTime=0,this._justLooped=!1}seek(t){this.currentTime=Math.max(0,t||0),this._justLooped=!1}}const Yi={linear:s=>s,easeInQuad:s=>s*s,easeOutQuad:s=>1-(1-s)*(1-s),easeInOutQuad:s=>s<.5?2*s*s:1-Math.pow(-2*s+2,2)/2,easeInCubic:s=>s*s*s,easeOutCubic:s=>1-Math.pow(1-s,3),easeInOutCubic:s=>s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,easeInQuart:s=>s*s*s*s,easeOutQuart:s=>1-Math.pow(1-s,4),easeInOutQuart:s=>s<.5?8*s*s*s*s:1-Math.pow(-2*s+2,4)/2,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeOutElastic:s=>{if(s===0||s===1)return s;const t=2*Math.PI/3;return Math.pow(2,-10*s)*Math.sin((s*10-.75)*t)+1}};function zr(s,t,e,i){const r=3*s,a=3*(e-s)-r,n=1-r-a,o=3*t,l=3*(i-t)-o,c=1-o-l,d=h=>((n*h+a)*h+r)*h,S=h=>((c*h+l)*h+o)*h,b=h=>(3*n*h+2*a)*h+r;return h=>{if(h<=0)return 0;if(h>=1)return 1;let v=h;for(let C=0;C<8;C++){const z=d(v)-h;if(Math.abs(z)<1e-5)break;const D=b(v);if(Math.abs(D)<1e-6)break;v-=z/D}return S(v)}}function cs(s,t){return typeof s=="function"?s(t):Array.isArray(s)&&s.length===4?zr(s[0],s[1],s[2],s[3])(t):(Yi[s]||Yi.linear)(t)}function Dr(s,t){if(!Array.isArray(s)||s.length===0)return;if(s.length===1||t<=s[0].t)return s[0].v;const e=s[s.length-1];if(t>=e.t)return e.v;for(let i=0;i<s.length-1;i++){const r=s[i],a=s[i+1];if(t>=r.t&&t<=a.t){const n=a.t-r.t,o=n>0?(t-r.t)/n:0;return r.v+(a.v-r.v)*cs(r.ease,o)}}return e.v}function Gr(s,t,e){if(!Array.isArray(s)||s.length===0)return;const i=s.length,r=s[i-1];let a,n,o;if(i===1||t<=s[0].t)a=n=s[0].v,o=0;else if(t>=r.t)a=n=r.v,o=0;else{a=n=r.v,o=0;for(let S=0;S<i-1;S++){const b=s[S],h=s[S+1];if(t>=b.t&&t<=h.t){const v=h.t-b.t;a=b.v,n=h.v,o=cs(b.ease,v>0?(t-b.t)/v:0);break}}}const l=a[0]+(n[0]-a[0])*o,c=a[1]+(n[1]-a[1])*o,d=a[2]+(n[2]-a[2])*o;return e?(e[0]=l,e[1]=c,e[2]=d,e):[l,c,d]}const Fr=["gravityStrength","emissionRate","damping","dampingStrength","particleSize","particleSpeed","opacity","bloomIntensity","emissionPositionX","emissionPositionY","emissionPositionZ","emissionRotationX","emissionRotationY","emissionRotationZ","circleInnerRadius","circleOuterRadius","discRadius","annulusInnerRadius","annulusOuterRadius","arcStartAngle","arcEndAngle","arcInnerRadius","arcOuterRadius","squareSize","rectangleWidth","rectangleHeight","planeWidth","planeDepth","lineLength","polygonRadius","shapeStrokeWidth","shapeStrokeAmplitude","shapeStrokeFrequency","shapeStrokeSpeed"],Vr={square:0,circle:1,triangle:2,diamond:3,star:4,hexagon:5,ring:6,heart:7,cross:8,spark:9,leaf:10,capsule:11,crescent:12,line:13,"curved-line":14};function ji(s){const t=atob(s),e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e.buffer}class kt{constructor(t,e){this.device=t,this.config=e,this.MAX_PARTICLES=e.maxParticles||1e4,this.particleCount=e.particleCount||100,this.activeParticles=0,this.emitting=!1,this.currentEmissionTime=0,this.emissionAccumulator=0,this.destroyed=!1,this.particleData=new Float32Array(this.MAX_PARTICLES*8),this.particleVelocities=new Float32Array(this.MAX_PARTICLES*4),this.instanceBuffer=t.createBuffer({size:this.MAX_PARTICLES*8*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC,label:"particleInstanceBuffer"}),this.velocityBuffer=t.createBuffer({size:this.MAX_PARTICLES*4*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,label:"particleVelocityBuffer"}),this.trailBuffer=t.createBuffer({size:this.MAX_PARTICLES*4*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,label:"particleTrailBuffer"}),this._trailResetData=new Float32Array(this.MAX_PARTICLES*4),this.appearanceUniformBuffer=t.createBuffer({size:224,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"appearanceUniformBuffer"}),this.bloomIntensityBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"systemBloomIntensityBuffer"}),e.overrideXVelocity===void 0&&(e.overrideXVelocity=!1),e.overrideYVelocity===void 0&&(e.overrideYVelocity=!1),e.overrideZVelocity===void 0&&(e.overrideZVelocity=!1),e.xVelocity===void 0&&(e.xVelocity=0),e.yVelocity===void 0&&(e.yVelocity=0),e.zVelocity===void 0&&(e.zVelocity=0),e.textureEnabled===void 0&&(e.textureEnabled=!1),e.glbModelEnabled===void 0&&(e.glbModelEnabled=!1),e.textureType===void 0&&(e.textureType="image"),e.glbFileName===void 0&&(e.glbFileName=null),e.animationIndex===void 0&&(e.animationIndex=0),e.animationSpeed===void 0&&(e.animationSpeed=1),e.animationLoop===void 0&&(e.animationLoop=!0),e.useGlbTexture===void 0&&(e.useGlbTexture=!1),e.glbHasTexture===void 0&&(e.glbHasTexture=!1),e.particleShape===void 0&&(e.particleShape="square"),e.particleShapeRotation!==void 0&&(e.rotation=(e.rotation||0)+e.particleShapeRotation,delete e.particleShapeRotation),e.particleShapeRotationX===void 0&&(e.particleShapeRotationX=0),e.particleShapeRotationY===void 0&&(e.particleShapeRotationY=0),e.particleShapeRotationZ===void 0&&(e.particleShapeRotationZ=0),e.particleColor===void 0&&(e.particleColor=[1,1,1]),e.startColor===void 0&&(e.startColor=[1,0,0]),e.endColor===void 0&&(e.endColor=[0,0,1]),e.fadeEnabled===void 0&&(e.fadeEnabled=!0),e.colorTransitionEnabled===void 0&&(e.colorTransitionEnabled=!1),e.randomColorEnabled===void 0&&(e.randomColorEnabled=!1),e.randomColors===void 0&&(e.randomColors=[]),e.particleSize===void 0&&(e.particleSize=.1),e.particleSpeed===void 0&&(e.particleSpeed=1),e.opacity===void 0&&(e.opacity=1),e.aspectRatio===void 0&&(e.aspectRatio=1),e.rotation===void 0&&(e.rotation=0),e.rotationMode===void 0&&(e.rotationMode="fixed"),e.minRotation===void 0&&(e.minRotation=0),e.maxRotation===void 0&&(e.maxRotation=90),e.orientX===void 0&&(e.orientX=0),e.orientY===void 0&&(e.orientY=0),e.orientZ===void 0&&(e.orientZ=0),e.randomSize===void 0&&(e.randomSize=!1),e.minSize===void 0&&(e.minSize=.05),e.maxSize===void 0&&(e.maxSize=.15),e.randomSpeed===void 0&&(e.randomSpeed=!1),e.minSpeed===void 0&&(e.minSpeed=.1),e.maxSpeed===void 0&&(e.maxSpeed=1),e.fadeSizeEnabled===void 0&&(e.fadeSizeEnabled=!1),e.increaseSizeEnabled===void 0&&(e.increaseSizeEnabled=!1),e.sizeLifetimeSpeed===void 0&&(e.sizeLifetimeSpeed=1),e.bloomEnabled===void 0&&(e.bloomEnabled=!0),e.bloomIntensity===void 0&&(e.bloomIntensity=1),e.bloomColor===void 0&&(e.bloomColor=[1,1,1]),e.gravityEnabled===void 0&&(e.gravityEnabled=!1),e.gravityStrength===void 0&&(e.gravityStrength=2),e.dampingEnabled===void 0&&(e.dampingEnabled=!1),e.dampingStrength===void 0&&(e.dampingStrength=1),e.attractorEnabled===void 0&&(e.attractorEnabled=!1),e.attractorStrength===void 0&&(e.attractorStrength=1),e.attractorPosition===void 0&&(e.attractorPosition=[0,0,0]),e.attractorReverse===void 0&&(e.attractorReverse=!1),e.burstMode===void 0&&(e.burstMode=!1),e.emissionShape===void 0&&(e.emissionShape="cube"),e.lifetime===void 0&&(e.lifetime=5),e.emissionRate===void 0&&(e.emissionRate=10),e.startAt===void 0&&(e.startAt=0),e.emissionDuration===void 0&&(e.emissionDuration=10),e.emissionDurationInfinite===void 0&&(e.emissionDurationInfinite=!1),e.emissionDuration>300&&(e.emissionDurationInfinite=!0,e.emissionDuration=10),e.outerLength===void 0&&(e.outerLength=e.cubeLength??2),e.innerLength===void 0&&(e.innerLength=0),e.outerRadius===void 0&&(e.outerRadius=2),e.innerRadius===void 0&&(e.innerRadius=0),e.squareSize===void 0&&(e.squareSize=2),e.squareInnerSize===void 0&&(e.squareInnerSize=0),e.circleInnerRadius===void 0&&(e.circleInnerRadius=0),e.circleOuterRadius===void 0&&(e.circleOuterRadius=2),e.circleVelocityDirection===void 0&&(e.circleVelocityDirection="outward"),e.cylinderInnerRadius===void 0&&(e.cylinderInnerRadius=0),e.cylinderOuterRadius===void 0&&(e.cylinderOuterRadius=2),e.cylinderHeight===void 0&&(e.cylinderHeight=4),e.cylinderVelocityDirection===void 0&&(e.cylinderVelocityDirection="outward"),e.planeWidth===void 0&&(e.planeWidth=2),e.planeDepth===void 0&&(e.planeDepth=2),e.coneOuterRadius===void 0&&(e.coneOuterRadius=2),e.coneInnerRadius===void 0&&(e.coneInnerRadius=0),e.coneHeight===void 0&&(e.coneHeight=4),e.torusMajorRadius===void 0&&(e.torusMajorRadius=2),e.torusMinorRadius===void 0&&(e.torusMinorRadius=.5),e.lineLength===void 0&&(e.lineLength=4),e.hemisphereOuterRadius===void 0&&(e.hemisphereOuterRadius=2),e.hemisphereInnerRadius===void 0&&(e.hemisphereInnerRadius=0),e.discRadius===void 0&&(e.discRadius=2),e.annulusInnerRadius===void 0&&(e.annulusInnerRadius=1),e.annulusOuterRadius===void 0&&(e.annulusOuterRadius=2),e.capsuleRadius===void 0&&(e.capsuleRadius=.5),e.capsuleHeight===void 0&&(e.capsuleHeight=4),e.arcStartAngle===void 0&&(e.arcStartAngle=0),e.arcEndAngle===void 0&&(e.arcEndAngle=180),e.arcInnerRadius===void 0&&(e.arcInnerRadius=0),e.arcOuterRadius===void 0&&(e.arcOuterRadius=2),e.spiralTurns===void 0&&(e.spiralTurns=3),e.spiralRadiusStart===void 0&&(e.spiralRadiusStart=.5),e.spiralRadiusEnd===void 0&&(e.spiralRadiusEnd=2),e.spiralHeight===void 0&&(e.spiralHeight=4),e.frustumRadiusNear===void 0&&(e.frustumRadiusNear=.5),e.frustumRadiusFar===void 0&&(e.frustumRadiusFar=2),e.frustumHeight===void 0&&(e.frustumHeight=4),e.cubeSurfaceSize===void 0&&(e.cubeSurfaceSize=2),e.sphereSurfaceRadius===void 0&&(e.sphereSurfaceRadius=2),e.boxFrameSize===void 0&&(e.boxFrameSize=2),e.polygonSides===void 0&&(e.polygonSides=6),e.polygonRadius===void 0&&(e.polygonRadius=2),e.emissionRotationX===void 0&&(e.emissionRotationX=0),e.emissionRotationY===void 0&&(e.emissionRotationY=0),e.emissionRotationZ===void 0&&(e.emissionRotationZ=0),e.emissionPositionX===void 0&&(e.emissionPositionX=e.emissionTranslationX??0),e.emissionPositionY===void 0&&(e.emissionPositionY=e.emissionTranslationY??0),e.emissionPositionZ===void 0&&(e.emissionPositionZ=e.emissionTranslationZ??0),e.pulseEnabled===void 0&&(e.pulseEnabled=!1),e.pulseAmplitude===void 0&&(e.pulseAmplitude=.5),e.pulseFrequency===void 0&&(e.pulseFrequency=1),e.pulsePhaseRandom===void 0&&(e.pulsePhaseRandom=0),e.pulseOpacity===void 0&&(e.pulseOpacity=!1),e.confinementEnabled===void 0&&(e.confinementEnabled=!1),e.confinementShape===void 0&&(e.confinementShape="box"),e.confinementMode===void 0&&(e.confinementMode="bounce"),e.confinementSpace===void 0&&(e.confinementSpace="world"),e.confinementBoxHalfSize===void 0&&(e.confinementBoxHalfSize=[2,2,2]),e.confinementSphereRadius===void 0&&(e.confinementSphereRadius=3),e.confinementRestitution===void 0&&(e.confinementRestitution=.8),e.confinementFriction===void 0&&(e.confinementFriction=.1),e.softBoundaryEnabled===void 0&&(e.softBoundaryEnabled=!1),e.softBoundaryStrength===void 0&&(e.softBoundaryStrength=5),e.softBoundaryFalloff===void 0&&(e.softBoundaryFalloff=.5),e.depthWriteEnabled===void 0&&(e.depthWriteEnabled=!1),e.velocityStretchEnabled===void 0&&(e.velocityStretchEnabled=!1),e.velocityStretchFactor===void 0&&(e.velocityStretchFactor=1),e.blendMode===void 0&&(e.blendMode="normal"),e.noiseDistortEnabled===void 0&&(e.noiseDistortEnabled=!1),e.noiseTilingX===void 0&&(e.noiseTilingX=3),e.noiseTilingY===void 0&&(e.noiseTilingY=3),e.noiseSpeed===void 0&&(e.noiseSpeed=-1.5),e.noiseAmplitude===void 0&&(e.noiseAmplitude=.08),e.emissionTrailEnabled===void 0&&(e.emissionTrailEnabled=!1),e.emissionTrailDuration===void 0&&(e.emissionTrailDuration=1),e.emissionTrailWidth===void 0&&(e.emissionTrailWidth=.3),e.emissionTrailMinDistance===void 0&&(e.emissionTrailMinDistance=.05),e.emissionTrailMaxPoints===void 0&&(e.emissionTrailMaxPoints=256),e.emissionTrailSegments===void 0&&(e.emissionTrailSegments=8),e.emissionTrailMode===void 0&&(e.emissionTrailMode="ribbon"),e.emissionTrailShape===void 0&&(e.emissionTrailShape="straight"),e.emissionTrailShapeAmplitude===void 0&&(e.emissionTrailShapeAmplitude=.1),e.emissionTrailShapeFrequency===void 0&&(e.emissionTrailShapeFrequency=4),e.emissionTrailShapeSpeed===void 0&&(e.emissionTrailShapeSpeed=0),e.shapeStrokeEnabled===void 0&&(e.shapeStrokeEnabled=!1),e.shapeStrokeWidth===void 0&&(e.shapeStrokeWidth=.08),e.shapeStrokeSegments===void 0&&(e.shapeStrokeSegments=96),e.shapeStrokeShape===void 0&&(e.shapeStrokeShape="straight"),e.shapeStrokeAmplitude===void 0&&(e.shapeStrokeAmplitude=.08),e.shapeStrokeFrequency===void 0&&(e.shapeStrokeFrequency=10),e.shapeStrokeSpeed===void 0&&(e.shapeStrokeSpeed=0),e.shapeDisplay===void 0&&(e.shapeDisplay=!0),e.followSystemTranslation===void 0&&(e.followSystemTranslation=!0),e.followSystemId===void 0&&(e.followSystemId=null),this._newEmissions=[],this._emptyEmissions=[],this._pendingFollowEmissions=this._emptyEmissions,this.glbVertexBuffer=null,this.glbIndexBuffer=null,this.glbIndexCount=0,this.glbIndexFormat="uint16",this.glbMeshData=null,this.glbRawArrayBuffer=null,this.glbAnimator=null,this.glbAnimated=!1,this._glbInterleavedData=null,this._appearanceData=new Float32Array(56),this._bloomIntensityData=new Float32Array(16),this._simPosition=[0,0,0],this._simVelocity=[0,0,0],this._simRotMatrix=null,this._simRotX=0,this._simRotZ=0,this._emitSimRotY=0,this.emitter=new Ji(e),this.physics=new ss(t,this.MAX_PARTICLES),this.textureManager=new rs(t),e.gravityEnabled&&this.setGravity(e.gravityStrength||0),e.dampingEnabled&&this.physics.setDamping(e.dampingStrength||0),e.attractorEnabled&&e.attractorPosition&&this.setAttractor(e.attractorStrength||0,e.attractorPosition,e.attractorReverse),e.confinementEnabled&&this.setConfinement({enabled:!0,shape:e.confinementShape,mode:e.confinementMode,space:e.confinementSpace,boxSize:e.confinementBoxHalfSize,sphereRadius:e.confinementSphereRadius,restitution:e.confinementRestitution,friction:e.confinementFriction}),e.softBoundaryEnabled&&this.setSoftBoundary({enabled:!0,strength:e.softBoundaryStrength,falloff:e.softBoundaryFalloff}),this.particleTexture=this.textureManager.getDefaultTexture(),this.updateBloomIntensity(),this.updateAppearanceUniform(),this.frameCount=0,this.shouldReset=!1,this._scriptParticleData=new Float32Array(this.MAX_PARTICLES*8),this._scriptVelocityData=new Float32Array(this.MAX_PARTICLES*4),this._scriptReadbackPending=!1,this._scriptReadbackReady=!1,this._scriptFrame=0,this._scriptTime=0,this._scriptConfigRestored=!1,this._particleScript=null,e.script&&(this._particleScript=new ni(e.script,e,this.MAX_PARTICLES)),this.initComputePipeline(t)}async initComputePipeline(t){this.computeReady=await this.physics.initComputePipeline(this.instanceBuffer,this.velocityBuffer,this.trailBuffer)}setScript(t){this._particleScript&&(this._particleScript.destroy(),this._particleScript=null),this._scriptReadbackPending=!1,this._scriptReadbackReady=!1,this._scriptFrame=0,this._scriptTime=0,this._scriptConfigRestored=!1,t?(this.config.script=t,this._particleScript=new ni(t,this.config,this.MAX_PARTICLES),this._particleScript.snapshotConfig(this.config)):delete this.config.script}async setTexture(t){this.destroyed||(this.textureManager.destroyTexture(this.particleTexture),this.particleTexture=await this.textureManager.loadTexture(t),this.config.textureEnabled=!0,this.updateAppearanceUniform(),this.updateBuffers())}resetTexture(){this.destroyed||(this.textureManager.destroyTexture(this.particleTexture),this.particleTexture=this.textureManager.getDefaultTexture(),this.config.textureEnabled=!1,this.updateAppearanceUniform(),this.updateBuffers())}async setGLBModel(t){try{this.glbRawArrayBuffer=t;const e=await ns(t);this.glbMeshData=e,this.config.glbHasTexture=e.hasBaseColorTexture||!1;const i=new Float32Array(e.vertexCount*8);for(let r=0;r<e.vertexCount;r++){const a=r*8,n=r*3,o=r*2;i[a+0]=e.positions[n+0],i[a+1]=e.positions[n+1],i[a+2]=e.positions[n+2],i[a+3]=e.normals[n+0],i[a+4]=e.normals[n+1],i[a+5]=e.normals[n+2],e.texCoords?(i[a+6]=e.texCoords[o+0],i[a+7]=e.texCoords[o+1]):(i[a+6]=0,i[a+7]=0)}if(this.glbVertexBuffer&&this.glbVertexBuffer.destroy(),this.glbIndexBuffer&&this.glbIndexBuffer.destroy(),this.glbVertexBuffer=this.device.createBuffer({size:i.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE,label:"glbVertexBuffer"}),this.device.queue.writeBuffer(this.glbVertexBuffer,0,i),this.glbIndexBuffer=this.device.createBuffer({size:e.indices.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST,label:"glbIndexBuffer"}),this.device.queue.writeBuffer(this.glbIndexBuffer,0,e.indices),this.glbIndexCount=e.indexCount,this.glbIndexFormat=e.indices instanceof Uint32Array?"uint32":"uint16",this.config.glbModelEnabled=!0,this.config.textureType="glb",e.animationData){this.glbAnimator=new os(e.animationData),this.glbAnimator.setRestPose(e.positions,e.normals),this.glbAnimated=!0,this.config.glbAnimated=!0,this.glbAnimator.loop=this.config.animationLoop,this._glbInterleavedData=new Float32Array(e.vertexCount*8);try{await this.glbAnimator.initGPUSkinning(this.device,this.glbVertexBuffer,e.texCoords)}catch(r){console.warn("GPU skinning init failed, using CPU fallback:",r)}globalThis.__HZFX_DEBUG&&console.log(`GLB animated model loaded: ${e.animationData.animations.length} animations`)}else this.glbAnimator=null,this.glbAnimated=!1,this.config.glbAnimated=!1,this._glbInterleavedData=null;globalThis.__HZFX_DEBUG&&console.log(`GLB model loaded: ${e.vertexCount} vertices, ${e.indexCount} indices`)}catch(e){throw console.error("Failed to load GLB model:",e),e}}resetGLBModel(){this.glbVertexBuffer&&(this.glbVertexBuffer.destroy(),this.glbVertexBuffer=null),this.glbIndexBuffer&&(this.glbIndexBuffer.destroy(),this.glbIndexBuffer=null),this.glbIndexCount=0,this.glbIndexFormat="uint16",this.glbMeshData=null,this.glbRawArrayBuffer=null,this.glbAnimator=null,this.glbAnimated=!1,this.config.glbAnimated=!1,this._glbInterleavedData=null,this.config.glbFileName=null,this.config.glbHasTexture=!1,this.config.useGlbTexture=!1,this.config.glbModelEnabled=!1,this.config.textureType="image"}setSimulationTransform(t){if(t.position&&(this._simPosition[0]=t.position[0],this._simPosition[1]=t.position[1],this._simPosition[2]=t.position[2]),t.rotation){this._simRotX=t.rotation[0]||0,this._simRotZ=t.rotation[1]||0,this._simRotY=t.rotation[2]||0;const e=Math.cos(this._simRotX),i=Math.sin(this._simRotX),r=Math.cos(this._simRotZ),a=Math.sin(this._simRotZ),n=Math.cos(this._simRotY),o=Math.sin(this._simRotY);this._simRotMatrix=[n*r,-n*a*e+o*i,n*a*i+o*e,a,r*e,-r*i,-o*r,o*a*e+n*i,-o*a*i+n*e]}else this._simRotMatrix=null,this._simRotX=0,this._simRotZ=0,this._simRotY=0;t.velocity&&(this._simVelocity[0]=t.velocity[0],this._simVelocity[1]=t.velocity[1],this._simVelocity[2]=t.velocity[2])}clearSimulationTransform(){this._simPosition[0]=this._simPosition[1]=this._simPosition[2]=0,this._simVelocity[0]=this._simVelocity[1]=this._simVelocity[2]=0,this._simRotMatrix=null,this._simRotX=0,this._simRotZ=0}updateAnimatedGLBBuffer(){if(!this.glbAnimator||!this.glbAnimator.playing)return!1;if(this.glbAnimator._gpuSkinningReady)return!0;const t=this.glbAnimator.skinnedPositions,e=this.glbAnimator.skinnedNormals,i=this.glbMeshData.texCoords;for(let r=0;r<this.glbMeshData.vertexCount;r++){const a=r*8,n=r*3,o=r*2;this._glbInterleavedData[a]=t[n],this._glbInterleavedData[a+1]=t[n+1],this._glbInterleavedData[a+2]=t[n+2],this._glbInterleavedData[a+3]=e[n],this._glbInterleavedData[a+4]=e[n+1],this._glbInterleavedData[a+5]=e[n+2],i?(this._glbInterleavedData[a+6]=i[o],this._glbInterleavedData[a+7]=i[o+1]):(this._glbInterleavedData[a+6]=0,this._glbInterleavedData[a+7]=0)}return this.device.queue.writeBuffer(this.glbVertexBuffer,0,this._glbInterleavedData),!0}updateAppearanceUniform(){if(this.destroyed)return;let t=0;this.config.rotationMode==="random"?t=1:this.config.rotationMode==="velocity"?t=2:this.config.rotationMode==="oriented"?t=3:this.config.rotationMode==="cylindrical"&&(t=4);const e=Vr[this.config.particleShape]??0,i=this._appearanceData;i[0]=this.config.fadeEnabled?1:0,i[1]=this.config.randomColorEnabled?2:this.config.colorTransitionEnabled?1:0,i[2]=this.config.particleSize,i[3]=this.config.textureEnabled?1:0,i[4]=this.config.particleColor[0],i[5]=this.config.particleColor[1],i[6]=this.config.particleColor[2],i[7]=this.config.rotation||0,i[8]=this.config.startColor[0],i[9]=this.config.startColor[1],i[10]=this.config.startColor[2],i[11]=t,i[12]=this.config.endColor[0],i[13]=this.config.endColor[1],i[14]=this.config.endColor[2],i[15]=this.config.minRotation||0,i[16]=this.config.maxRotation||90,i[17]=this.config.aspectRatio||1,i[18]=this.config.randomSize?1:0,i[19]=this.config.minSize||.1,i[20]=this.config.maxSize||.5,i[21]=this.config.fadeSizeEnabled?1:0,i[22]=this.config.opacity!==void 0?this.config.opacity:1,i[23]=this.config.increaseSizeEnabled?1:0,i[24]=this.config.sizeLifetimeSpeed??1,i[25]=e,i[26]=0,i[27]=this.config.pulseEnabled?1:0,i[28]=this.config.pulseAmplitude??.5,i[29]=this.config.pulseFrequency??1,i[30]=this.config.pulsePhaseRandom??0,i[31]=this.config.pulseOpacity?1:0,i[32]=this.config.particleShapeRotationX||0,i[33]=this.config.particleShapeRotationY||0,i[34]=this.config.particleShapeRotationZ||0,i[35]=0;const r=this.config.followSystemTranslation??!0;i[36]=r?this._simPosition[0]:0,i[37]=r?this._simPosition[1]:0,i[38]=r?this._simPosition[2]:0,i[39]=0,i[40]=this._simRotX,i[41]=this._simRotZ,i[42]=this.config.velocityStretchEnabled?1:0,i[43]=this.config.velocityStretchFactor??1,i[44]=this.config.noiseDistortEnabled?1:0,i[45]=this.config.noiseTilingX??3,i[46]=this.config.noiseTilingY??3,i[47]=this.config.noiseSpeed??-1.5,i[48]=this.config.noiseAmplitude??.08,i[49]=r?this._simVelocity[0]:0,i[50]=r?this._simVelocity[1]:0,i[51]=r?this._simVelocity[2]:0,i[52]=this.config.orientX??0,i[53]=this.config.orientY??0,i[54]=this.config.orientZ??0,i[55]=0,this.device.queue.writeBuffer(this.appearanceUniformBuffer,0,i)}updateBloomIntensity(){const t=this._bloomIntensityData;t[0]=this.config.bloomIntensity||1;const e=this.config.bloomColor||[1,1,1];t[4]=e[0],t[5]=e[1],t[6]=e[2],this.device.queue.writeBuffer(this.bloomIntensityBuffer,0,t)}spawnParticles(t){if(this.activeParticles=0,this.currentEmissionTime=0,this.emissionAccumulator=0,this._newEmissions.length=0,this._pendingFollowEmissions=this._emptyEmissions,this._scriptFrame=0,this._scriptTime=0,this._scriptReadbackPending=!1,this._scriptReadbackReady=!1,this._scriptConfigRestored=!1,this._particleScript&&(this._particleScript._configSnapshot?(this._particleScript.restoreConfig(this.config),this.config.gravityEnabled&&this.setGravity(this.config.gravityStrength),this.config.dampingEnabled&&this.physics.setDamping(this.config.dampingStrength),this.config.attractorEnabled&&this.setAttractor(this.config.attractorStrength,this.config.attractorPosition,this.config.attractorReverse),this.updateAppearanceUniform(),this.updateBloomIntensity()):this._particleScript.snapshotConfig(this.config)),typeof t=="function"&&t(this),this.device.queue.writeBuffer(this.trailBuffer,0,this._trailResetData,0,this.MAX_PARTICLES*4),this.glbAnimator&&(this.glbAnimator.currentTime=0,this.glbAnimator.playing=!0),this.config.followSystemId){this.emitting=!0,this.particleCount=this.MAX_PARTICLES;return}if(this.config.burstMode){const e=this.config.particleCount;this.particleCount=e;let i=0;const r=500;for(let a=0;a<e;a++)if(this.emitParticle(),i++,i>=r||a===e-1){const n=a-i+1,o=n*8,l=n*4;this.device.queue.writeBuffer(this.instanceBuffer,o*4,this.particleData,o,i*8),this.device.queue.writeBuffer(this.velocityBuffer,l*4,this.particleVelocities,l,i*4),i=0}this.emitting=!1}else{this.emitting=!0;const e=this.config.lifetime||5,i=this.config.emissionDurationInfinite?e:Math.min(this.config.emissionDuration||10,e);this.particleCount=Math.min(Math.ceil((this.config.emissionRate||10)*i),this.MAX_PARTICLES)}}get effectiveEmissionDuration(){return this.config.emissionDurationInfinite?1/0:this.config.emissionDuration??10}_applySimTransformToParticle(t){this._emitSimRotY=this._simRotY||0;const e=t*8,i=t*4;if(this._simRotMatrix){const r=this._simRotMatrix,a=this.particleData[e],n=this.particleData[e+1],o=this.particleData[e+2],l=this.particleVelocities[i],c=this.particleVelocities[i+1],d=this.particleVelocities[i+2];this.particleData[e]=r[0]*a+r[1]*n+r[2]*o,this.particleData[e+1]=r[3]*a+r[4]*n+r[5]*o,this.particleData[e+2]=r[6]*a+r[7]*n+r[8]*o,this.particleVelocities[i]=r[0]*l+r[1]*c+r[2]*d,this.particleVelocities[i+1]=r[3]*l+r[4]*c+r[5]*d,this.particleVelocities[i+2]=r[6]*l+r[7]*c+r[8]*d}(this.config.followSystemTranslation??!0)||(this.particleData[e]+=this._simPosition[0],this.particleData[e+1]+=this._simPosition[1],this.particleData[e+2]+=this._simPosition[2])}emitParticle(){if(this.activeParticles>=this.particleCount)return!1;this.emitter.emitParticle(this.particleData,this.activeParticles,this.particleVelocities);const t=this.activeParticles*8,e=this.activeParticles*4;return this._applySimTransformToParticle(this.activeParticles),this._newEmissions.push(this.particleData[t],this.particleData[t+1],this.particleData[t+2],this.particleVelocities[e],this.particleVelocities[e+1],this.particleVelocities[e+2]),this.activeParticles++,!0}emitFollowerParticle(t,e,i){if(this.activeParticles>=this.particleCount)return!1;const r=this.activeParticles*8,a=t+(this.config.emissionPositionX||0),n=e+(this.config.emissionPositionY||0),o=i+(this.config.emissionPositionZ||0);this.particleData[r]=a,this.particleData[r+1]=n,this.particleData[r+2]=o;const l=this.activeParticles*4;return this.emitter.calculateVelocity(a,n,o,this.particleVelocities,l),this.emitter.setParticleColor(this.particleData,r),this.emitter.setParticleLifetime(this.particleData,r),this.activeParticles++,!0}updateParticles(t,e,i=0){const r=this.config.startAt||0,a=r>0&&i<r;if(this._particleScript&&this._scriptReadbackReady){this._scriptReadbackReady=!1,this._scriptTime+=t,this._scriptFrame++;const d=this.config.emissionDurationInfinite?1/0:(this.config.emissionDuration||0)+(this.config.lifetime||0);if(d>0&&this._scriptTime>=d&&!this._scriptConfigRestored)this._scriptConfigRestored=!0,this._particleScript._configSnapshot&&(this._particleScript.restoreConfig(this.config),this.updateAppearanceUniform(),this.updateBloomIntensity(),this.config.gravityEnabled&&this.setGravity(this.config.gravityStrength),this.config.dampingEnabled&&this.physics.setDamping(this.config.dampingStrength),this.config.attractorEnabled&&this.setAttractor(this.config.attractorStrength,this.config.attractorPosition,this.config.attractorReverse));else if(!this._scriptConfigRestored){const S=d>0?Math.ceil(d/.016666666666666666):0,{configDirty:b,particlesDirty:h}=this._particleScript.execute(t,this._scriptTime,this._scriptFrame,S,this._scriptParticleData,this._scriptVelocityData,this.activeParticles);h&&this.activeParticles>0&&(this.device.queue.writeBuffer(this.instanceBuffer,0,this._scriptParticleData,0,this.activeParticles*8),this.device.queue.writeBuffer(this.velocityBuffer,0,this._scriptVelocityData,0,this.activeParticles*4)),b&&(this.updateAppearanceUniform(),this.updateBloomIntensity(),this.config.gravityEnabled&&this.setGravity(this.config.gravityStrength),this.config.dampingEnabled&&this.physics.setDamping(this.config.dampingStrength),this.config.attractorEnabled&&this.setAttractor(this.config.attractorStrength,this.config.attractorPosition,this.config.attractorReverse))}}this.physics.physicsAccumulator+=t;const n=performance.now()/1e3,l=n-this.physics.lastUpdateTime>1/this.physics.minUpdatesPerSecond,c=this.activeParticles;if(!a&&!this.emitting&&!this.config.burstMode&&!this.config.followSystemId&&this.currentEmissionTime<this.effectiveEmissionDuration&&(this.emitting=!0),!a&&this.emitting)if(this.currentEmissionTime+=t,this.currentEmissionTime<this.effectiveEmissionDuration){const d=this.activeParticles;let S=!1;if(this.config.followSystemId){if(this._pendingFollowEmissions.length>0){const b=this._pendingFollowEmissions.length/6;for(let h=0;h<b;h++){const v=h*6;if(this.emitFollowerParticle(this._pendingFollowEmissions[v],this._pendingFollowEmissions[v+1],this._pendingFollowEmissions[v+2]))S=!0;else break}}}else{let b=0;const h=Math.max(0,this.config.emissionRate||0);this.activeParticles<this.particleCount&&h>0?(this.emissionAccumulator+=h*t,b=Math.floor(this.emissionAccumulator+1e-9),b>0&&(this.emissionAccumulator-=b)):this.activeParticles>=this.particleCount&&(this.emissionAccumulator=0);for(let v=0;v<b;v++)if(this.emitParticle())S=!0;else{this.emissionAccumulator=0;break}}if(S){const b=this.activeParticles-d,h=d*8,v=d*4;this.device.queue.writeBuffer(this.instanceBuffer,h*4,this.particleData,h,b*8),this.device.queue.writeBuffer(this.velocityBuffer,v*4,this.particleVelocities,v,b*4)}}else this.emitting=!1,this.currentEmissionTime=this.config.emissionDuration;for(;this.physics.physicsAccumulator>=this.physics.fixedDeltaTime;)this.physics.updatePhysics(this.physics.fixedDeltaTime,c,this.config,this.instanceBuffer,this.velocityBuffer,e),this.physics.physicsAccumulator-=this.physics.fixedDeltaTime,this.physics.physicsClock+=this.physics.fixedDeltaTime;l&&c>0&&(this.physics.updatePhysics(this.physics.fixedDeltaTime,c,this.config,this.instanceBuffer,this.velocityBuffer,e),this.physics.lastUpdateTime=n),this.frameCount++,(this.activeParticles>=this.particleCount||this.frameCount%300===0)&&this.readbackAndProcessParticles(),this._particleScript&&this.activeParticles>0&&!this._scriptReadbackPending&&(this._scriptReadbackPending=!0,this.physics.readbackForScript(this.activeParticles,this._scriptParticleData,this._scriptVelocityData,this.instanceBuffer,this.velocityBuffer).then(d=>{this._scriptReadbackPending=!1,d.shouldUpdate&&(this._scriptReadbackReady=!0)}).catch(()=>{this._scriptReadbackPending=!1}))}async readbackAndProcessParticles(){if(!(this.activeParticles<=0))try{if(!(await this.physics.readbackAndProcessParticles(this.activeParticles,this.particleData,this.particleVelocities,this.instanceBuffer,this.velocityBuffer)).shouldUpdate)return;let e=0,i=!1;for(let r=0;r<this.activeParticles;r++){const a=this.particleData[r*8+6],n=this.particleData[r*8+7];if(a>=n){if(this.emitting&&this.currentEmissionTime<this.effectiveEmissionDuration&&e<this.particleCount){this.respawnParticle(r,e),e++,i=!0;continue}continue}if(e!==r){const o=r*8,l=e*8;this.particleData.copyWithin(l,o,o+8);const c=r*4,d=e*4;this.particleVelocities.copyWithin(d,c,c+4),i=!0}e++}(e!==this.activeParticles||i)&&(this.activeParticles=e,this.device.queue.writeBuffer(this.instanceBuffer,0,this.particleData,0,this.activeParticles*8),this.device.queue.writeBuffer(this.velocityBuffer,0,this.particleVelocities,0,this.activeParticles*4))}catch(t){t&&t.name==="AbortError"||console.error("Error reading back particle data:",t)}}respawnParticle(t,e){!this.emitting||this.currentEmissionTime>=this.effectiveEmissionDuration||this.config.followSystemId||(this.emitter.emitParticle(this.particleData,e,this.particleVelocities),this._applySimTransformToParticle(e))}updateBuffers(){this.destroyed||!this.particleData||this.activeParticles>0&&this.device.queue.writeBuffer(this.instanceBuffer,0,this.particleData,0,this.activeParticles*8)}updateParticleColors(){if(!(this.destroyed||!this.particleData)){for(let t=0;t<this.activeParticles;t++){const e=t*8;if(this.config.randomColorEnabled&&this.config.randomColors.length>0){const i=this.config.randomColors,r=i[Math.floor(Math.random()*i.length)];this.particleData[e+3]=r[0],this.particleData[e+4]=r[1],this.particleData[e+5]=r[2]}else this.config.colorTransitionEnabled?(this.particleData[e+3]=this.config.startColor[0],this.particleData[e+4]=this.config.startColor[1],this.particleData[e+5]=this.config.startColor[2]):(this.particleData[e+3]=this.config.particleColor[0],this.particleData[e+4]=this.config.particleColor[1],this.particleData[e+5]=this.config.particleColor[2])}this.activeParticles>0&&this.device.queue.writeBuffer(this.instanceBuffer,0,this.particleData,0,this.activeParticles*8)}}updateParticleVelocities(){for(let t=0;t<this.activeParticles;t++){const e=t*8,i=t*4,r=this.particleData[e],a=this.particleData[e+1],n=this.particleData[e+2],o=this.particleVelocities[i],l=this.particleVelocities[i+1],c=this.particleVelocities[i+2],d=Math.sqrt(o*o+l*l+c*c);if(d>.001){const S=this.config.particleSpeed*2;this.particleVelocities[i]=o/d*S,this.particleVelocities[i+1]=l/d*S,this.particleVelocities[i+2]=c/d*S}else{const S=Math.sqrt(r*r+a*a+n*n);if(S>.001){const b=this.config.particleSpeed*2;this.particleVelocities[i]=r/S*b,this.particleVelocities[i+1]=a/S*b,this.particleVelocities[i+2]=n/S*b}else this.particleVelocities[i]=0,this.particleVelocities[i+1]=this.config.particleSpeed*2,this.particleVelocities[i+2]=0}}this.activeParticles>0&&this.device.queue.writeBuffer(this.velocityBuffer,0,this.particleVelocities,0,this.activeParticles*4)}async readbackForRendering(t,e){return this.physics.readbackForRendering(this.activeParticles,t,e,this.instanceBuffer,this.velocityBuffer)}destroy(){this.destroyed=!0,this.instanceBuffer.destroy(),this.velocityBuffer.destroy(),this.trailBuffer.destroy(),this.appearanceUniformBuffer.destroy(),this.bloomIntensityBuffer.destroy(),this.physics.destroy(),this.glbVertexBuffer&&(this.glbVertexBuffer.destroy(),this.glbVertexBuffer=null),this.glbIndexBuffer&&(this.glbIndexBuffer.destroy(),this.glbIndexBuffer=null),this.textureManager.destroyTexture(this.particleTexture),this._particleScript&&(this._particleScript.destroy(),this._particleScript=null),this.glbAnimator=null,this.glbMeshData=null,this.glbRawArrayBuffer=null,this.particleData=null,this.particleVelocities=null,this._scriptParticleData=null,this._scriptVelocityData=null}setGravity(t){this.physics.setGravity(t)}setAttractor(t,e,i=this.config.attractorReverse){this.config.attractorStrength=t,this.config.attractorPosition=e,this.config.attractorReverse=!!i,this.physics.setAttractor(t,e,i)}setConfinement(t){const e=t.center||this.config.confinementCenter||[0,0,0],i=t.space==="local"?[this.config.emissionPositionX||0,this.config.emissionPositionY||0,this.config.emissionPositionZ||0]:[0,0,0],r=[i[0]+(e[0]||0),i[1]+(e[1]||0),i[2]+(e[2]||0)];this.physics.setConfinement({...t,center:r})}setSoftBoundary(t){this.physics.setSoftBoundary(t)}}class us{constructor(t){this.device=t,this.particleSystems=[],this.activeSystemIndex=0,this.systemCounter=1,this.onSystemCreated=null,this.loop=void 0,this.clock=new ls({loop:!!this.loop}),this.ready=!0}createParticleSystem(t={}){const e=this.systemCounter++,i=t.name||`System ${e+1}`,r={...t,name:i,id:e},a=new kt(this.device,r);return this.particleSystems.push({system:a,config:r}),this.particleSystems.length===1&&(this.activeSystemIndex=0),this.onSystemCreated&&typeof this.onSystemCreated=="function"&&this.onSystemCreated(e,r),e}getActiveSystem(){return this.particleSystems.length===0?null:this.particleSystems[this.activeSystemIndex].system}getActiveConfig(){return this.particleSystems.length===0?null:this.particleSystems[this.activeSystemIndex].config}setActiveSystem(t){return t>=0&&t<this.particleSystems.length?(this.activeSystemIndex=t,!0):!1}getSystemById(t){return this.particleSystems.find(({config:e})=>e.id===t)||null}destroy(){for(const{system:t}of this.particleSystems)t.destroy();this.particleSystems=[],this.activeSystemIndex=0}removeSystem(t){if(t>=0&&t<this.particleSystems.length){const e=this.particleSystems[t].config;this.particleSystems[t].system.destroy(),this.particleSystems.splice(t,1);const i=e.id;for(const{config:r}of this.particleSystems)r.followSystemId===i&&(r.followSystemId=null);return this.particleSystems.length===0?this.activeSystemIndex=0:t<=this.activeSystemIndex&&(this.activeSystemIndex=Math.max(0,this.activeSystemIndex-1)),!0}return!1}respawnAllSystems(){var t;(t=this.clock)==null||t.reset();for(const{system:e,config:i}of this.particleSystems)e.spawnParticles(()=>this._applyKeyframesToSystem(e,i,0))}getTotalDuration(){let t=0;for(const{config:e}of this.particleSystems){if(e.emissionDurationInfinite)return 1/0;const i=e.lifetime||5,r=(e.burstMode||e.oneOnlyMode?i:(e.emissionDuration||10)+i)+(e.startAt||0);r>t&&(t=r)}return t||1}updateAllSystems(t){const e=this.device.createCommandEncoder({label:"BatchedPhysicsEncoder"});let i=!1;const r=this.clock?this.clock.currentTime:0,a=this.clock?this.clock.duration:0;if(this.clock&&a>0&&isFinite(a)){const n=Math.min(1,this.clock.currentTime/a);for(const{system:o,config:l}of this.particleSystems)this._applyKeyframesToSystem(o,l,n)}for(const{system:n,config:o}of this.particleSystems){if(o.hidden||o.followSystemId)continue;const l=n.activeParticles>0;n.updateParticles(t,e,r),(l||n.activeParticles>0)&&(i=!0)}for(const{system:n,config:o}of this.particleSystems){if(o.hidden||!o.followSystemId)continue;const l=this.getSystemById(o.followSystemId);l&&(n._pendingFollowEmissions=l.system._newEmissions);const c=n.activeParticles>0;n.updateParticles(t,e,r),(c||n.activeParticles>0)&&(i=!0)}i&&this.device.queue.submit([e.finish()]);for(const{system:n}of this.particleSystems)n._newEmissions.length=0,n._pendingFollowEmissions=n._emptyEmissions}getSystemsList(){return this.particleSystems.map(({config:t},e)=>({name:t.name,id:t.id,index:e,isActive:e===this.activeSystemIndex,hidden:t.hidden||!1}))}duplicateActiveSystem(){if(this.particleSystems.length===0)return-1;const t=this.getActiveConfig(),e=JSON.parse(JSON.stringify(t));return e.name=`${t.name} (Copy)`,e.onAppearanceChange=null,e.onColorChange=null,e.onSizeChange=null,e.onSpeedChange=null,e.onPhysicsChange=null,e.onBloomIntensityChange=null,e.onRespawn=null,e.getActiveSystem=null,delete e.id,this.createParticleSystem(e)}async replaceSystems(t){var e;if(!t||!t.systems||!Array.isArray(t.systems))return console.error("Invalid scene data provided"),!1;this.ready=!1;try{this.particleSystems=[],this.systemCounter=1;for(const r of t.systems){const a=this.systemCounter++,n={...r,id:a},o=new kt(this.device,n);this.particleSystems.push({system:o,config:n})}const i={};t.systems.forEach((r,a)=>{i[r.id]=this.particleSystems[a].config.id});for(const{config:r}of this.particleSystems)r.followSystemId&&i[r.followSystemId]!==void 0&&(r.followSystemId=i[r.followSystemId]);t.activeSystemIndex!==void 0&&t.activeSystemIndex>=0&&t.activeSystemIndex<this.particleSystems.length?this.activeSystemIndex=t.activeSystemIndex:this.activeSystemIndex=0,this.loop=t.loop;for(const{system:r,config:a}of this.particleSystems)if(a.glbModelEnabled)try{let n=null;if(a.glbModelData)n=ji(a.glbModelData);else if(a.glbFileName){const o=await fetch(`/${a.glbFileName}`);o.ok?n=await o.arrayBuffer():console.warn(`GLB file not found: ${a.glbFileName}`)}if(n){if(await r.setGLBModel(n),a.animationIndex!==void 0&&r.glbAnimator&&r.glbAnimator.setAnimation(a.animationIndex),a.animationSpeed!==void 0&&r.glbAnimator&&(r.glbAnimator.speed=a.animationSpeed),a.animationLoop!==void 0&&r.glbAnimator&&(r.glbAnimator.loop=a.animationLoop),a.useGlbTexture&&(a.textureEnabled=!0),a.useGlbTexture&&((e=r.glbMeshData)!=null&&e.hasBaseColorTexture))try{const o=await oi(n);if(o){const l=await createImageBitmap(o.imageBlob);await r.setTexture(l),globalThis.__HZFX_DEBUG&&console.log(`GLB embedded texture restored for ${a.name}`)}}catch(o){console.warn(`Failed to restore GLB texture for ${a.name}:`,o),a.useGlbTexture=!1}}else a.glbModelEnabled=!1}catch(n){console.warn(`Failed to load GLB for ${a.name}:`,n),a.glbModelEnabled=!1}for(const{system:r,config:a}of this.particleSystems)if(a.textureEnabled&&!a.glbModelEnabled&&a.textureImageData)try{const n=new Image;await new Promise((l,c)=>{n.onload=l,n.onerror=c,n.src=a.textureImageData});const o=await createImageBitmap(n);await r.setTexture(o)}catch(n){console.warn(`Failed to restore texture for ${a.name}:`,n),a.textureEnabled=!1}for(const{system:r,config:a}of this.particleSystems)r.updateAppearanceUniform();return this.respawnAllSystems(),!0}catch(i){return console.error("Error replacing systems:",i),!1}finally{this.ready=!0}}async addSystems(t,e=[0,0,0]){var r;if(!t||!t.systems||!Array.isArray(t.systems))return console.error("Invalid scene data provided"),!1;this.ready=!1;const i=[];try{for(const o of t.systems){const l=this.systemCounter++;i.push(l);const c={...o,id:l,emissionPositionX:(o.emissionPositionX||0)+e[0],emissionPositionY:(o.emissionPositionY||0)+e[1],emissionPositionZ:(o.emissionPositionZ||0)+e[2]};o.attractorEnabled&&o.attractorPosition&&(c.attractorPosition=[o.attractorPosition[0]+e[0],o.attractorPosition[1]+e[1],o.attractorPosition[2]+e[2]]),o.confinementEnabled&&o.confinementSpace==="world"&&Array.isArray(o.confinementCenter)&&(c.confinementCenter=[(o.confinementCenter[0]||0)+e[0],(o.confinementCenter[1]||0)+e[1],(o.confinementCenter[2]||0)+e[2]]);const d=new kt(this.device,c);this.particleSystems.push({system:d,config:c}),this.onSystemCreated&&typeof this.onSystemCreated=="function"&&this.onSystemCreated(l,c)}const a=this.particleSystems.length-t.systems.length,n={};t.systems.forEach((o,l)=>{n[o.id]=this.particleSystems[a+l].config.id});for(let o=a;o<this.particleSystems.length;o++){const{config:l}=this.particleSystems[o];l.followSystemId&&n[l.followSystemId]!==void 0&&(l.followSystemId=n[l.followSystemId])}for(const{system:o,config:l}of this.particleSystems)if(l.glbModelEnabled&&!o.glbMeshData)try{let c=null;if(l.glbModelData)c=ji(l.glbModelData);else if(l.glbFileName){const d=await fetch(`/${l.glbFileName}`);d.ok?c=await d.arrayBuffer():console.warn(`GLB file not found: ${l.glbFileName}`)}if(c){if(await o.setGLBModel(c),l.animationIndex!==void 0&&o.glbAnimator&&o.glbAnimator.setAnimation(l.animationIndex),l.animationSpeed!==void 0&&o.glbAnimator&&(o.glbAnimator.speed=l.animationSpeed),l.animationLoop!==void 0&&o.glbAnimator&&(o.glbAnimator.loop=l.animationLoop),l.useGlbTexture&&(l.textureEnabled=!0),l.useGlbTexture&&((r=o.glbMeshData)!=null&&r.hasBaseColorTexture))try{const d=await oi(c);if(d){const S=await createImageBitmap(d.imageBlob);await o.setTexture(S),globalThis.__HZFX_DEBUG&&console.log(`GLB embedded texture restored for ${l.name}`)}}catch(d){console.warn(`Failed to restore GLB texture for ${l.name}:`,d),l.useGlbTexture=!1}}else l.glbModelEnabled=!1}catch(c){console.warn(`Failed to load GLB for ${l.name}:`,c),l.glbModelEnabled=!1}for(const{system:o,config:l}of this.particleSystems)if(l.textureEnabled&&!l.glbModelEnabled&&l.textureImageData&&!o._textureRestored)try{const c=new Image;await new Promise((S,b)=>{c.onload=S,c.onerror=b,c.src=l.textureImageData});const d=await createImageBitmap(c);await o.setTexture(d),o._textureRestored=!0}catch(c){console.warn(`Failed to restore texture for ${l.name}:`,c),l.textureEnabled=!1}return i}catch(a){return console.error("Error adding systems:",a),!1}finally{this.ready=!0}}_applyKeyframesToSystem(t,e,i){const r=e.keyframes;if(!r||e.keyframesEnabled===!1)return;let a=!1,n=!1,o=!1,l=!1,c=!1;for(const d of Fr){const S=r[d];if(!S||!S.length)continue;const b=Dr(S,i);if(b!==void 0){if(d==="damping"){e.dampingStrength=b,l=!0;continue}e[d]=b,(d==="particleSize"||d==="opacity")&&(a=!0),d==="bloomIntensity"&&(n=!0),d==="gravityStrength"&&(o=!0),d==="dampingStrength"&&(l=!0),(d==="attractorStrength"||d==="attractorReverse")&&(c=!0)}}if(r.particleColor&&r.particleColor.length){const d=e.particleColor,S=d&&typeof d.length=="number"&&d.length>=3?d:void 0,b=Gr(r.particleColor,i,S);b&&(e.particleColor=b,a=!0)}a&&t.updateAppearanceUniform(),n&&t.updateBloomIntensity(),o&&e.gravityEnabled&&t.setGravity(e.gravityStrength),l&&e.dampingEnabled&&t.physics.setDamping(e.dampingStrength),c&&e.attractorEnabled&&e.attractorPosition&&t.setAttractor(e.attractorStrength,e.attractorPosition,e.attractorReverse)}}async function ds(s){if(!s)throw new Error("canvas is required for initWebGPU()");if(!navigator.gpu)throw new Error("WebGPU not supported on this browser.");const t=s.getContext("webgpu"),i=await(await navigator.gpu.requestAdapter()).requestDevice(),r=navigator.gpu.getPreferredCanvasFormat();return t.configure({device:i,format:r,alphaMode:"premultiplied"}),{device:i,context:t,format:r,canvas:s}}const Xe="rgba16float",qi=.5,fs=(s,t)=>[Math.max(1,Math.round(s*qi)),Math.max(1,Math.round(t*qi))];function li(s,t,e,i){const r=s.createTexture({size:[e,i],format:Xe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),[a,n]=fs(e,i),o=s.createTexture({size:[a,n],format:Xe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),l=s.createTexture({size:[a,n],format:Xe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1});return{sceneTexture:r,bloomTexA:o,bloomTexB:l}}function ci(s,t,e){return s.createTexture({size:[t,e],format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT})}function pt(s,t,e){const i=s.createBuffer({size:t.byteLength,usage:e,mappedAtCreation:!0});return new t.constructor(i.getMappedRange()).set(t),i.unmap(),i}const ps=`
880
898
  struct Uniforms {
881
899
  transform: mat4x4<f32>,
882
900
  cameraPosition: vec3<f32>,
@@ -938,7 +956,7 @@ return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles,
938
956
 
939
957
  return finalColor;
940
958
  }
941
- `,fs=`
959
+ `,hs=`
942
960
  struct Uniforms {
943
961
  transform: mat4x4<f32>,
944
962
  cameraPosition: vec3<f32>,
@@ -1174,7 +1192,7 @@ return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles,
1174
1192
 
1175
1193
  return finalColor;
1176
1194
  }
1177
- `;function ps(s){const t=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),e=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),i=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),r=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]});return{particleBindGroupLayout:t,bloomBindGroupLayout:e,compositeBindGroupLayout:i,object3dBindGroupLayout:r}}function hs(s,t,e,i={}){const{depthCompare:r}=i,n=r||"less",{particleBindGroupLayout:a,bloomBindGroupLayout:o,compositeBindGroupLayout:c,object3dBindGroupLayout:l}=e,d=s.createPipelineLayout({bindGroupLayouts:[a]}),S=s.createPipelineLayout({bindGroupLayouts:[o]}),b=s.createPipelineLayout({bindGroupLayouts:[c]}),p=s.createShaderModule({code:Ji}),v=s.createShaderModule({code:Ki}),E=s.createShaderModule({code:Qi}),I=s.createShaderModule({code:es}),z=s.createShaderModule({code:ds}),_=s.createShaderModule({code:fs}),W=Nt=>s.createRenderPipeline({layout:d,vertex:{module:p,entryPoint:"vs_main",buffers:[{arrayStride:12,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]},{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x3"},{shaderLocation:2,offset:12,format:"float32x3"},{shaderLocation:3,offset:24,format:"float32x2"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:4,offset:0,format:"float32x3"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:5,offset:0,format:"float32x3"}]}]},fragment:{module:p,entryPoint:"fs_main",targets:[{format:ke,blend:Nt}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{depthWriteEnabled:!1,depthCompare:n,format:"depth24plus"}}),T=W({color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),G=W({color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),F=s.createRenderPipeline({layout:d,vertex:{module:p,entryPoint:"vs_main",buffers:[{arrayStride:12,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]},{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x3"},{shaderLocation:2,offset:12,format:"float32x3"},{shaderLocation:3,offset:24,format:"float32x2"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:4,offset:0,format:"float32x3"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:5,offset:0,format:"float32x3"}]}]},fragment:{module:p,entryPoint:"fs_main",targets:[{format:ke,writeMask:0}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{depthWriteEnabled:!0,depthCompare:"always",format:"depth24plus"}}),Z=s.createRenderPipeline({layout:S,vertex:{module:v,entryPoint:"vs_main"},fragment:{module:v,entryPoint:"fs_main",targets:[{format:ke}]},primitive:{topology:"triangle-list"}}),re=s.createRenderPipeline({layout:b,vertex:{module:E,entryPoint:"vs_main"},fragment:{module:E,entryPoint:"fs_main",targets:[{format:ke,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),ae=s.createRenderPipeline({layout:b,vertex:{module:I,entryPoint:"vs_main"},fragment:{module:I,entryPoint:"fs_main",targets:[{format:ke,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),ne=s.createShaderModule({code:pr}),q=s.createRenderPipeline({layout:b,vertex:{module:ne,entryPoint:"vs_main"},fragment:{module:ne,entryPoint:"fs_main",targets:[{format:t,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),tt=s.createPipelineLayout({bindGroupLayouts:[l]}),xt=s.createRenderPipeline({layout:tt,vertex:{module:z,entryPoint:"vs_main",buffers:[{arrayStride:24,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"}]}]},fragment:{module:z,entryPoint:"fs_main",targets:[{format:ke,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list",cullMode:"back"},depthStencil:{depthWriteEnabled:!0,depthCompare:n,format:"depth24plus"}}),Xe=s.createRenderPipeline({layout:d,vertex:{module:_,entryPoint:"vs_main",buffers:[{arrayStride:32,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]},{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:3,offset:0,format:"float32x3"},{shaderLocation:4,offset:12,format:"float32x3"},{shaderLocation:5,offset:24,format:"float32x2"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:6,offset:0,format:"float32x3"}]}]},fragment:{module:_,entryPoint:"fs_main",targets:[{format:ke,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list",cullMode:"back"},depthStencil:{depthWriteEnabled:!0,depthCompare:n,format:"depth24plus"}});return{particlePipeline:T,particleAdditivePipeline:G,particleDepthWritePipeline:F,blurPipeline:Z,compositePipeline:re,directRenderPipeline:ae,finalCompositePipeline:q,object3dPipeline:xt,glbMeshPipeline:Xe}}function Xt(s,t,e,i){const{uniformBuffer:r,appearanceUniformBuffer:n,horizontalBlurUniformBuffer:a,verticalBlurUniformBuffer:o,bloomIntensityBuffer:c}=e,{sceneTexture:l,bloomTexA:d,bloomTexB:S}=i,b=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:n}}]}),p=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:l.createView()},{binding:2,resource:{buffer:a}}]}),v=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:d.createView()},{binding:2,resource:{buffer:o}}]}),E=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:l.createView()},{binding:2,resource:S.createView()},{binding:3,resource:{buffer:c}}]}),I=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:l.createView()},{binding:2,resource:S.createView()},{binding:3,resource:{buffer:c}}]});return{particleBindGroup:b,horizontalBlurBindGroup:p,verticalBlurBindGroup:v,compositeBindGroup:E,directRenderBindGroup:I}}function ms(s){return s.createSampler({magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",maxAnisotropy:16})}function ys(){const s=new Float32Array([-.5,-.5,.5,0,0,1,.5,-.5,.5,0,0,1,.5,.5,.5,0,0,1,-.5,.5,.5,0,0,1,.5,-.5,-.5,0,0,-1,-.5,-.5,-.5,0,0,-1,-.5,.5,-.5,0,0,-1,.5,.5,-.5,0,0,-1,-.5,.5,.5,0,1,0,.5,.5,.5,0,1,0,.5,.5,-.5,0,1,0,-.5,.5,-.5,0,1,0,-.5,-.5,-.5,0,-1,0,.5,-.5,-.5,0,-1,0,.5,-.5,.5,0,-1,0,-.5,-.5,.5,0,-1,0,.5,-.5,.5,1,0,0,.5,-.5,-.5,1,0,0,.5,.5,-.5,1,0,0,.5,.5,.5,1,0,0,-.5,-.5,-.5,-1,0,0,-.5,-.5,.5,-1,0,0,-.5,.5,.5,-1,0,0,-.5,.5,-.5,-1,0,0]),t=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]);return{vertices:s,indices:t}}function gs(s=16,t=16){const e=[],i=[];for(let r=0;r<=s;r++){const n=r*Math.PI/s,a=Math.sin(n),o=Math.cos(n);for(let c=0;c<=t;c++){const l=c*2*Math.PI/t,d=Math.sin(l),b=Math.cos(l)*a,p=o,v=d*a;e.push(b*.5,p*.5,v*.5),e.push(b,p,v)}}for(let r=0;r<s;r++)for(let n=0;n<t;n++){const a=r*(t+1)+n,o=a+t+1;i.push(a),i.push(o),i.push(a+1),i.push(o),i.push(o+1),i.push(a+1)}return{vertices:new Float32Array(e),indices:new Uint16Array(i)}}class Dr{constructor(t,e,i,r,n){this.id=t,this.type=e,this.position=i,this.scale=r,this.color=n,this.rotation=[0,0,0]}getModelMatrix(){const{position:t,scale:e,rotation:i}=this,r=this.createTranslationMatrix(t),n=this.createRotationMatrixX(i[0]),a=this.createRotationMatrixY(i[1]),o=this.createRotationMatrixZ(i[2]),c=this.createScaleMatrix(e);let l=r;return l=this.multiplyMatrices(l,o),l=this.multiplyMatrices(l,a),l=this.multiplyMatrices(l,n),l=this.multiplyMatrices(l,c),l}getNormalMatrix(){return this.getModelMatrix()}createTranslationMatrix([t,e,i]){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,t,e,i,1])}createScaleMatrix([t,e,i]){return new Float32Array([t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1])}createRotationMatrixX(t){const e=Math.cos(t),i=Math.sin(t);return new Float32Array([1,0,0,0,0,e,i,0,0,-i,e,0,0,0,0,1])}createRotationMatrixY(t){const e=Math.cos(t),i=Math.sin(t);return new Float32Array([e,0,-i,0,0,1,0,0,i,0,e,0,0,0,0,1])}createRotationMatrixZ(t){const e=Math.cos(t),i=Math.sin(t);return new Float32Array([e,i,0,0,-i,e,0,0,0,0,1,0,0,0,0,1])}multiplyMatrices(t,e){const i=new Float32Array(16);for(let r=0;r<4;r++)for(let n=0;n<4;n++){let a=0;for(let o=0;o<4;o++)a+=t[r*4+o]*e[o*4+n];i[r*4+n]=a}return i}}class Vr{constructor(t){this.device=t,this.objects=[],this.nextId=0,this.initializeGeometry(),this.onObjectAdded=null,this.onObjectRemoved=null,this.onObjectUpdated=null}initializeGeometry(){const t=ys(),e=gs(16,16);this.cubeVertexBuffer=pt(this.device,t.vertices,GPUBufferUsage.VERTEX),this.cubeIndexBuffer=pt(this.device,t.indices,GPUBufferUsage.INDEX),this.cubeIndexCount=t.indices.length,this.sphereVertexBuffer=pt(this.device,e.vertices,GPUBufferUsage.VERTEX),this.sphereIndexBuffer=pt(this.device,e.indices,GPUBufferUsage.INDEX),this.sphereIndexCount=e.indices.length}addObject(t,e=[0,0,0],i=[1,1,1],r=[1,1,1,1]){const n=new Dr(this.nextId++,t,e,i,r);return n.uniformBuffer=this.device.createBuffer({size:192,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.objects.push(n),this.onObjectAdded&&this.onObjectAdded(n),n}removeObject(t){const e=this.objects.findIndex(i=>i.id===t);e!==-1&&(this.objects[e].uniformBuffer.destroy(),this.objects.splice(e,1),this.onObjectRemoved&&this.onObjectRemoved(t))}updateObjectPosition(t,e){const i=this.objects.find(r=>r.id===t);i&&(i.position=e,this.onObjectUpdated&&this.onObjectUpdated(i))}updateObjectScale(t,e){const i=this.objects.find(r=>r.id===t);i&&(i.scale=e,this.onObjectUpdated&&this.onObjectUpdated(i))}updateObjectColor(t,e){const i=this.objects.find(r=>r.id===t);i&&(i.color=e,this.onObjectUpdated&&this.onObjectUpdated(i))}getAllObjects(){return this.objects}getObject(t){return this.objects.find(e=>e.id===t)}updateObjectUniforms(t){const e=t.getModelMatrix(),i=t.getNormalMatrix(),r=new Float32Array(t.color);this.device.queue.writeBuffer(t.uniformBuffer,0,e),this.device.queue.writeBuffer(t.uniformBuffer,64,i),this.device.queue.writeBuffer(t.uniformBuffer,128,r)}renderObjects(t,e,i,r){for(const n of this.objects){this.updateObjectUniforms(n);const a=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:n.uniformBuffer}}]});let o,c,l;if(n.type==="cube")o=this.cubeVertexBuffer,c=this.cubeIndexBuffer,l=this.cubeIndexCount;else if(n.type==="sphere")o=this.sphereVertexBuffer,c=this.sphereIndexBuffer,l=this.sphereIndexCount;else continue;t.setPipeline(e),t.setBindGroup(0,a),t.setVertexBuffer(0,o),t.setIndexBuffer(c,"uint16"),t.drawIndexed(l)}}}function Or(s){const t=parseInt(s.slice(1,3),16)/255,e=parseInt(s.slice(3,5),16)/255,i=parseInt(s.slice(5,7),16)/255;return[t,e,i]}function Lr(s){if(!s)return"#ffffff";const t=Math.round(s[0]*255).toString(16).padStart(2,"0"),e=Math.round(s[1]*255).toString(16).padStart(2,"0"),i=Math.round(s[2]*255).toString(16).padStart(2,"0");return`#${t}${e}${i}`}function kr(s,t,e){const i=qi([s[0]-t[0],s[1]-t[1],s[2]-t[2]]),r=qi(Hi(e,i)),n=Hi(i,r);return new Float32Array([r[0],n[0],i[0],0,r[1],n[1],i[1],0,r[2],n[2],i[2],0,-ri(r,s),-ri(n,s),-ri(i,s),1])}function Xr(s,t=Math.PI/4){const r=1/Math.tan(t/2);return new Float32Array([r*s,0,0,0,0,r,0,0,0,0,(100+.1)/(.1-100),-1,0,0,200*.1/(.1-100),0])}function qi(s){const t=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]);return[s[0]/t,s[1]/t,s[2]/t]}function Hi(s,t){return[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]]}function ri(s,t){return s[0]*t[0]+s[1]*t[1]+s[2]*t[2]}function bs(s,t){const e=new Float32Array(16);for(let i=0;i<4;i++)for(let r=0;r<4;r++){let n=0;for(let a=0;a<4;a++)n+=s[i+a*4]*t[a+r*4];e[i+r*4]=n}return e}const ui=1481005640,Ss=1,xs=1313821514,vs=5130562,Et="$hzfxAsset",Ps=s=>typeof atob=="function"?Uint8Array.from(atob(s),t=>t.charCodeAt(0)):new Uint8Array(Buffer.from(s,"base64")),Zi=s=>{if(typeof btoa=="function"){let t="";for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}return Buffer.from(s).toString("base64")};function Nr(s){const t=s.indexOf(","),e=s.slice(5,t),i=e.split(";")[0]||"application/octet-stream",r=s.slice(t+1),a=/;base64/i.test(e)?Ps(r):new TextEncoder().encode(decodeURIComponent(r));return{mime:i,bytes:a}}function Wi(s){return(4-s%4)%4}async function _s(s,t={}){const{textureFormat:e="keep",quality:i=.85}=t,r=[],n=[];let a=0;const o=(G,F,Z)=>{const re=a,ae=G.length;r.push({offset:re,length:ae,mime:F,kind:Z}),n.push(G),a+=ae;const ne=Wi(ae);return ne&&(n.push(new Uint8Array(ne)),a+=ne),r.length-1},c=e==="webp"&&typeof OffscreenCanvas<"u"&&typeof createImageBitmap=="function",l=[];for(const G of s.systems||[]){const F={...G};if(typeof F.textureImageData=="string"&&F.textureImageData.startsWith("data:")){let{mime:Z,bytes:re}=Nr(F.textureImageData);if(c&&Z!=="image/webp")try{const ae=await createImageBitmap(new Blob([re],{type:Z})),ne=new OffscreenCanvas(ae.width,ae.height);ne.getContext("2d").drawImage(ae,0,0);const q=await ne.convertToBlob({type:"image/webp",quality:i}),tt=new Uint8Array(await q.arrayBuffer());tt.length<re.length&&(re=tt,Z="image/webp")}catch{}F.textureImageData={[Et]:o(re,Z,"texture")}}if(typeof F.glbModelData=="string"&&F.glbModelData.length>0){const Z=Ps(F.glbModelData);F.glbModelData={[Et]:o(Z,"model/gltf-binary","glb")}}l.push(F)}const d={...s,systems:l,assets:r},S=new TextEncoder().encode(JSON.stringify(d)),b=Wi(S.length),p=new Uint8Array(a);let v=0;for(const G of n)p.set(G,v),v+=G.length;const E=S.length+b,I=20+E+8+a,z=new ArrayBuffer(I),_=new DataView(z),W=new Uint8Array(z);let T=0;_.setUint32(T,ui,!0),T+=4,_.setUint32(T,Ss,!0),T+=4,_.setUint32(T,I,!0),T+=4,_.setUint32(T,E,!0),T+=4,_.setUint32(T,xs,!0),T+=4,W.set(S,T),T+=S.length;for(let G=0;G<b;G++)W[T++]=32;return _.setUint32(T,a,!0),T+=4,_.setUint32(T,vs,!0),T+=4,W.set(p,T),T+=a,z}function di(s){return!s||s.byteLength<12?!1:new DataView(s).getUint32(0,!0)===ui}function fi(s){const t=new DataView(s);if(t.getUint32(0,!0)!==ui)throw new Error("[unpackHZFX] bad magic — not an .hzfx file");const e=t.getUint32(4,!0);if(e!==Ss)throw new Error(`[unpackHZFX] unsupported version ${e}`);let i=12,r=null,n=-1;const a=new Uint8Array(s);for(;i+8<=s.byteLength;){const b=t.getUint32(i,!0);i+=4;const p=t.getUint32(i,!0);i+=4,p===xs?r=JSON.parse(new TextDecoder().decode(a.subarray(i,i+b))):p===vs&&(n=i),i+=b}if(!r)throw new Error("[unpackHZFX] missing JSON chunk");const o=r.assets||[],c=b=>{const p=o[b];return!p||n<0?null:{...p,bytes:a.subarray(n+p.offset,n+p.offset+p.length)}},l=b=>b&&typeof b=="object"&&typeof b[Et]=="number",d=(r.systems||[]).map(b=>{const p={...b};if(l(p.textureImageData)){const v=c(p.textureImageData[Et]);p.textureImageData=v?`data:${v.mime};base64,${Zi(v.bytes)}`:void 0}if(l(p.glbModelData)){const v=c(p.glbModelData[Et]);p.glbModelData=v?Zi(v.bytes):void 0}return p}),S={...r,systems:d};return delete S.assets,S}function Yr(s){const t=new Uint8Array(s);let e="";for(let i=0;i<t.byteLength;i++)e+=String.fromCharCode(t[i]);return btoa(e)}function Ms(s){return{name:s.name,id:s.id,particleCount:s.particleCount,lifetime:s.lifetime,emissionRate:s.emissionRate,emissionDuration:s.emissionDuration,emissionDurationInfinite:s.emissionDurationInfinite||!1,startAt:s.startAt||0,keyframes:s.keyframes||null,keyframesEnabled:s.keyframesEnabled!==!1,particleSize:s.particleSize,particleSpeed:s.particleSpeed,emissionShape:s.emissionShape,outerLength:s.outerLength??s.cubeLength,innerLength:s.innerLength,outerRadius:s.outerRadius,innerRadius:s.innerRadius,squareSize:s.squareSize,squareInnerSize:s.squareInnerSize,circleInnerRadius:s.circleInnerRadius,circleOuterRadius:s.circleOuterRadius,fadeEnabled:s.fadeEnabled,colorTransitionEnabled:s.colorTransitionEnabled,particleColor:s.particleColor,startColor:s.startColor,endColor:s.endColor,randomColorEnabled:s.randomColorEnabled||!1,randomColors:s.randomColors||[],particleShape:s.particleShape||"square",particleShapeRotationX:s.particleShapeRotationX||0,particleShapeRotationY:s.particleShapeRotationY||0,particleShapeRotationZ:s.particleShapeRotationZ||0,pulseEnabled:s.pulseEnabled||!1,pulseAmplitude:s.pulseAmplitude??.5,pulseFrequency:s.pulseFrequency??1,pulsePhaseRandom:s.pulsePhaseRandom??0,pulseOpacity:s.pulseOpacity||!1,bloomEnabled:s.bloomEnabled,bloomIntensity:s.bloomIntensity,bloomColor:s.bloomColor,depthWriteEnabled:s.depthWriteEnabled||!1,burstMode:s.burstMode,gravityEnabled:s.gravityEnabled,gravityStrength:s.gravityStrength,dampingEnabled:s.dampingEnabled,dampingStrength:s.dampingStrength,attractorEnabled:s.attractorEnabled,attractorStrength:s.attractorStrength,attractorReverse:s.attractorReverse??!1,attractorPosition:s.attractorPosition,emissionRotationX:s.emissionRotationX,emissionRotationY:s.emissionRotationY,emissionRotationZ:s.emissionRotationZ,orientToDirection:s.orientToDirection??!1,emissionPositionX:s.emissionPositionX,emissionPositionY:s.emissionPositionY,emissionPositionZ:s.emissionPositionZ,rotation:s.rotation,rotationMode:s.rotationMode,minRotation:s.minRotation,maxRotation:s.maxRotation,orientX:s.orientX,orientY:s.orientY,orientZ:s.orientZ,overrideXVelocity:s.overrideXVelocity,overrideYVelocity:s.overrideYVelocity,overrideZVelocity:s.overrideZVelocity,xVelocity:s.xVelocity,yVelocity:s.yVelocity,zVelocity:s.zVelocity,circleVelocityDirection:s.circleVelocityDirection,cylinderVelocityDirection:s.cylinderVelocityDirection,cylinderInnerRadius:s.cylinderInnerRadius,cylinderOuterRadius:s.cylinderOuterRadius,cylinderHeight:s.cylinderHeight,planeWidth:s.planeWidth,planeDepth:s.planeDepth,rectangleWidth:s.rectangleWidth,rectangleHeight:s.rectangleHeight,coneOuterRadius:s.coneOuterRadius,coneInnerRadius:s.coneInnerRadius,coneHeight:s.coneHeight,torusMajorRadius:s.torusMajorRadius,torusMinorRadius:s.torusMinorRadius,lineLength:s.lineLength,hemisphereOuterRadius:s.hemisphereOuterRadius,hemisphereInnerRadius:s.hemisphereInnerRadius,discRadius:s.discRadius,annulusInnerRadius:s.annulusInnerRadius,annulusOuterRadius:s.annulusOuterRadius,capsuleRadius:s.capsuleRadius,capsuleHeight:s.capsuleHeight,arcStartAngle:s.arcStartAngle,arcEndAngle:s.arcEndAngle,arcInnerRadius:s.arcInnerRadius,arcOuterRadius:s.arcOuterRadius,spiralTurns:s.spiralTurns,spiralRadiusStart:s.spiralRadiusStart,spiralRadiusEnd:s.spiralRadiusEnd,spiralHeight:s.spiralHeight,frustumRadiusNear:s.frustumRadiusNear,frustumRadiusFar:s.frustumRadiusFar,frustumHeight:s.frustumHeight,cubeSurfaceSize:s.cubeSurfaceSize,sphereSurfaceRadius:s.sphereSurfaceRadius,boxFrameSize:s.boxFrameSize,polygonSides:s.polygonSides,polygonRadius:s.polygonRadius,aspectRatio:s.aspectRatio,randomSize:s.randomSize,minSize:s.minSize,maxSize:s.maxSize,fadeSizeEnabled:s.fadeSizeEnabled,increaseSizeEnabled:s.increaseSizeEnabled,sizeLifetimeSpeed:s.sizeLifetimeSpeed,opacity:s.opacity,randomSpeed:s.randomSpeed,minSpeed:s.minSpeed,maxSpeed:s.maxSpeed,oneOnlyMode:s.oneOnlyMode,confinementEnabled:s.confinementEnabled||!1,confinementShape:s.confinementShape||"box",confinementMode:s.confinementMode||"bounce",confinementSpace:s.confinementSpace||"world",confinementBoxHalfSize:s.confinementBoxHalfSize||[2,2,2],confinementSphereRadius:s.confinementSphereRadius??3,confinementRestitution:s.confinementRestitution??.8,confinementFriction:s.confinementFriction??.1,confinementCenter:s.confinementCenter,softBoundaryEnabled:s.softBoundaryEnabled||!1,softBoundaryStrength:s.softBoundaryStrength??5,softBoundaryFalloff:s.softBoundaryFalloff??.5,followSystemId:s.followSystemId||null,followSystemTranslation:s.followSystemTranslation??!0,hidden:s.hidden||!1,emissionTrailEnabled:s.emissionTrailEnabled||!1,emissionTrailDuration:s.emissionTrailDuration??1,emissionTrailWidth:s.emissionTrailWidth??.5,emissionTrailMinDistance:s.emissionTrailMinDistance??.05,emissionTrailMaxPoints:s.emissionTrailMaxPoints??100,emissionTrailSegments:s.emissionTrailSegments??8,emissionTrailMode:s.emissionTrailMode??"ribbon",emissionTrailShape:s.emissionTrailShape??"straight",emissionTrailShapeAmplitude:s.emissionTrailShapeAmplitude??.1,emissionTrailShapeFrequency:s.emissionTrailShapeFrequency??4,emissionTrailShapeSpeed:s.emissionTrailShapeSpeed??0,shapeStrokeEnabled:s.shapeStrokeEnabled||!1,shapeStrokeWidth:s.shapeStrokeWidth??.08,shapeStrokeSegments:s.shapeStrokeSegments??96,shapeStrokeShape:s.shapeStrokeShape??"straight",shapeStrokeAmplitude:s.shapeStrokeAmplitude??.08,shapeStrokeFrequency:s.shapeStrokeFrequency??10,shapeStrokeSpeed:s.shapeStrokeSpeed??0,shapeDisplay:s.shapeDisplay??!0,blendMode:s.blendMode??"normal",noiseDistortEnabled:s.noiseDistortEnabled||!1,noiseTilingX:s.noiseTilingX??3,noiseTilingY:s.noiseTilingY??3,noiseSpeed:s.noiseSpeed??-1.5,noiseAmplitude:s.noiseAmplitude??.08,velocityStretchEnabled:s.velocityStretchEnabled||!1,velocityStretchFactor:s.velocityStretchFactor??1,textureEnabled:s.textureEnabled||!1,textureType:s.textureType,textureFileName:s.textureFileName,imageDescription:s.imageDescription,glbModelEnabled:s.glbModelEnabled||!1,glbFileName:s.glbFileName,glbHasTexture:s.glbHasTexture||!1,useGlbTexture:s.useGlbTexture||!1,glbAnimated:s.glbAnimated||!1,animationIndex:s.animationIndex,animationSpeed:s.animationSpeed,animationLoop:s.animationLoop,glbDescription:s.glbDescription,script:s.script||void 0,displayUnit:s.displayUnit||"m"}}async function jr(s,t,e="hzfx"){if(!s||!s.particleSystems||s.particleSystems.length===0){alert("No particle systems to save.");return}try{const i={version:"1.0",timestamp:new Date().toISOString(),systems:s.particleSystems.map(({config:d,system:S})=>({...Ms(d),textureImageData:d.textureEnabled&&!d.glbModelEnabled&&d.textureImageData?d.textureImageData:void 0,glbModelData:d.glbModelEnabled&&S.glbRawArrayBuffer?Yr(S.glbRawArrayBuffer):void 0})),activeSystemIndex:s.activeSystemIndex,loop:s.loop||!1},r=e==="json"?"json":"hzfx";let n;if(r==="hzfx"){const d=await _s(i,{textureFormat:"webp"});n=new Blob([d],{type:"application/octet-stream"})}else n=new Blob([JSON.stringify(i,null,2)],{type:"application/json"});let a;if(t)a=t;else{const d=new Date;a=`particle-scene_${`${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,"0")}-${d.getDate().toString().padStart(2,"0")}_${d.getHours().toString().padStart(2,"0")}${d.getMinutes().toString().padStart(2,"0")}`}`}const o=`${a}.${r}`,c=URL.createObjectURL(n),l=document.createElement("a");l.href=c,l.download=o,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(c)}catch(i){console.error("Error saving scene:",i),alert("Error saving scene. See console for details.")}}function qr(s){return new Promise((t,e)=>{try{const i=s.target.files[0];if(!i){e(new Error("No file selected"));return}const r=new FileReader;r.onload=n=>{try{const a=n.target.result;let o;if(di(a)?o=fi(a):o=JSON.parse(new TextDecoder().decode(a)),!Array.isArray(o.systems)||o.systems.length===0)throw new Error("No valid particle systems found in the file");t({systems:o.systems.slice(),activeSystemIndex:o.activeSystemIndex||0})}catch(a){console.error("Error loading scene:",a),alert("Error loading scene: "+a.message),e(a)}s.target.value=""},r.onerror=()=>{alert("Failed to read the file"),e(new Error("Failed to read the file")),s.target.value=""},r.readAsArrayBuffer(i)}catch(i){console.error("Error in loadScene:",i),e(i)}})}async function Hr(s){if(!s||typeof s!="string")throw new Error("[fetchPreset] url must be a non-empty string");const t=await fetch(s);if(!t.ok)throw new Error(`[fetchPreset] HTTP ${t.status}: ${t.statusText}`);const e=await t.arrayBuffer();let i;if(di(e)?i=fi(e):i=JSON.parse(new TextDecoder().decode(e)),!Array.isArray(i.systems)||i.systems.length===0)throw new Error('[fetchPreset] Invalid preset: "systems" must be a non-empty array');return{version:i.version,systems:i.systems,activeSystemIndex:i.activeSystemIndex??0}}const Zr=s=>`
1195
+ `;function ms(s){const t=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),e=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),i=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),r=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]});return{particleBindGroupLayout:t,bloomBindGroupLayout:e,compositeBindGroupLayout:i,object3dBindGroupLayout:r}}function ys(s,t,e,i={}){const{depthCompare:r}=i,a=r||"less",{particleBindGroupLayout:n,bloomBindGroupLayout:o,compositeBindGroupLayout:l,object3dBindGroupLayout:c}=e,d=s.createPipelineLayout({bindGroupLayouts:[n]}),S=s.createPipelineLayout({bindGroupLayouts:[o]}),b=s.createPipelineLayout({bindGroupLayouts:[l]}),h=s.createShaderModule({code:Ki}),v=s.createShaderModule({code:Qi}),C=s.createShaderModule({code:es}),z=s.createShaderModule({code:ts}),D=s.createShaderModule({code:ps}),_=s.createShaderModule({code:hs}),Z=Nt=>s.createRenderPipeline({layout:d,vertex:{module:h,entryPoint:"vs_main",buffers:[{arrayStride:12,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]},{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x3"},{shaderLocation:2,offset:12,format:"float32x3"},{shaderLocation:3,offset:24,format:"float32x2"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:4,offset:0,format:"float32x3"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:5,offset:0,format:"float32x3"}]}]},fragment:{module:h,entryPoint:"fs_main",targets:[{format:Xe,blend:Nt}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{depthWriteEnabled:!1,depthCompare:a,format:"depth24plus"}}),T=Z({color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),G=Z({color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),F=s.createRenderPipeline({layout:d,vertex:{module:h,entryPoint:"vs_main",buffers:[{arrayStride:12,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]},{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x3"},{shaderLocation:2,offset:12,format:"float32x3"},{shaderLocation:3,offset:24,format:"float32x2"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:4,offset:0,format:"float32x3"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:5,offset:0,format:"float32x3"}]}]},fragment:{module:h,entryPoint:"fs_main",targets:[{format:Xe,writeMask:0}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{depthWriteEnabled:!0,depthCompare:"always",format:"depth24plus"}}),H=s.createRenderPipeline({layout:S,vertex:{module:v,entryPoint:"vs_main"},fragment:{module:v,entryPoint:"fs_main",targets:[{format:Xe}]},primitive:{topology:"triangle-list"}}),se=s.createRenderPipeline({layout:b,vertex:{module:C,entryPoint:"vs_main"},fragment:{module:C,entryPoint:"fs_main",targets:[{format:Xe,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),ae=s.createRenderPipeline({layout:b,vertex:{module:z,entryPoint:"vs_main"},fragment:{module:z,entryPoint:"fs_main",targets:[{format:Xe,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),re=s.createShaderModule({code:mr}),j=s.createRenderPipeline({layout:b,vertex:{module:re,entryPoint:"vs_main"},fragment:{module:re,entryPoint:"fs_main",targets:[{format:t,blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),tt=s.createPipelineLayout({bindGroupLayouts:[c]}),xt=s.createRenderPipeline({layout:tt,vertex:{module:D,entryPoint:"vs_main",buffers:[{arrayStride:24,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"}]}]},fragment:{module:D,entryPoint:"fs_main",targets:[{format:Xe,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list",cullMode:"back"},depthStencil:{depthWriteEnabled:!0,depthCompare:a,format:"depth24plus"}}),nt=s.createRenderPipeline({layout:d,vertex:{module:_,entryPoint:"vs_main",buffers:[{arrayStride:32,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]},{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:3,offset:0,format:"float32x3"},{shaderLocation:4,offset:12,format:"float32x3"},{shaderLocation:5,offset:24,format:"float32x2"}]},{arrayStride:16,stepMode:"instance",attributes:[{shaderLocation:6,offset:0,format:"float32x3"}]}]},fragment:{module:_,entryPoint:"fs_main",targets:[{format:Xe,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list",cullMode:"back"},depthStencil:{depthWriteEnabled:!0,depthCompare:a,format:"depth24plus"}});return{particlePipeline:T,particleAdditivePipeline:G,particleDepthWritePipeline:F,blurPipeline:H,compositePipeline:se,directRenderPipeline:ae,finalCompositePipeline:j,object3dPipeline:xt,glbMeshPipeline:nt}}function Xt(s,t,e,i){const{uniformBuffer:r,appearanceUniformBuffer:a,horizontalBlurUniformBuffer:n,verticalBlurUniformBuffer:o,bloomIntensityBuffer:l}=e,{sceneTexture:c,bloomTexA:d,bloomTexB:S}=i,b=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:a}}]}),h=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:c.createView()},{binding:2,resource:{buffer:n}}]}),v=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:d.createView()},{binding:2,resource:{buffer:o}}]}),C=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:c.createView()},{binding:2,resource:S.createView()},{binding:3,resource:{buffer:l}}]}),z=s.createBindGroup({layout:s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),entries:[{binding:0,resource:t},{binding:1,resource:c.createView()},{binding:2,resource:S.createView()},{binding:3,resource:{buffer:l}}]});return{particleBindGroup:b,horizontalBlurBindGroup:h,verticalBlurBindGroup:v,compositeBindGroup:C,directRenderBindGroup:z}}function gs(s){return s.createSampler({magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",maxAnisotropy:16})}function bs(){const s=new Float32Array([-.5,-.5,.5,0,0,1,.5,-.5,.5,0,0,1,.5,.5,.5,0,0,1,-.5,.5,.5,0,0,1,.5,-.5,-.5,0,0,-1,-.5,-.5,-.5,0,0,-1,-.5,.5,-.5,0,0,-1,.5,.5,-.5,0,0,-1,-.5,.5,.5,0,1,0,.5,.5,.5,0,1,0,.5,.5,-.5,0,1,0,-.5,.5,-.5,0,1,0,-.5,-.5,-.5,0,-1,0,.5,-.5,-.5,0,-1,0,.5,-.5,.5,0,-1,0,-.5,-.5,.5,0,-1,0,.5,-.5,.5,1,0,0,.5,-.5,-.5,1,0,0,.5,.5,-.5,1,0,0,.5,.5,.5,1,0,0,-.5,-.5,-.5,-1,0,0,-.5,-.5,.5,-1,0,0,-.5,.5,.5,-1,0,0,-.5,.5,-.5,-1,0,0]),t=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]);return{vertices:s,indices:t}}function Ss(s=16,t=16){const e=[],i=[];for(let r=0;r<=s;r++){const a=r*Math.PI/s,n=Math.sin(a),o=Math.cos(a);for(let l=0;l<=t;l++){const c=l*2*Math.PI/t,d=Math.sin(c),b=Math.cos(c)*n,h=o,v=d*n;e.push(b*.5,h*.5,v*.5),e.push(b,h,v)}}for(let r=0;r<s;r++)for(let a=0;a<t;a++){const n=r*(t+1)+a,o=n+t+1;i.push(n),i.push(o),i.push(n+1),i.push(o),i.push(o+1),i.push(n+1)}return{vertices:new Float32Array(e),indices:new Uint16Array(i)}}class Or{constructor(t,e,i,r,a){this.id=t,this.type=e,this.position=i,this.scale=r,this.color=a,this.rotation=[0,0,0]}getModelMatrix(){const{position:t,scale:e,rotation:i}=this,r=this.createTranslationMatrix(t),a=this.createRotationMatrixX(i[0]),n=this.createRotationMatrixY(i[1]),o=this.createRotationMatrixZ(i[2]),l=this.createScaleMatrix(e);let c=r;return c=this.multiplyMatrices(c,o),c=this.multiplyMatrices(c,n),c=this.multiplyMatrices(c,a),c=this.multiplyMatrices(c,l),c}getNormalMatrix(){return this.getModelMatrix()}createTranslationMatrix([t,e,i]){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,t,e,i,1])}createScaleMatrix([t,e,i]){return new Float32Array([t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1])}createRotationMatrixX(t){const e=Math.cos(t),i=Math.sin(t);return new Float32Array([1,0,0,0,0,e,i,0,0,-i,e,0,0,0,0,1])}createRotationMatrixY(t){const e=Math.cos(t),i=Math.sin(t);return new Float32Array([e,0,-i,0,0,1,0,0,i,0,e,0,0,0,0,1])}createRotationMatrixZ(t){const e=Math.cos(t),i=Math.sin(t);return new Float32Array([e,i,0,0,-i,e,0,0,0,0,1,0,0,0,0,1])}multiplyMatrices(t,e){const i=new Float32Array(16);for(let r=0;r<4;r++)for(let a=0;a<4;a++){let n=0;for(let o=0;o<4;o++)n+=t[r*4+o]*e[o*4+a];i[r*4+a]=n}return i}}class Lr{constructor(t){this.device=t,this.objects=[],this.nextId=0,this.initializeGeometry(),this.onObjectAdded=null,this.onObjectRemoved=null,this.onObjectUpdated=null}initializeGeometry(){const t=bs(),e=Ss(16,16);this.cubeVertexBuffer=pt(this.device,t.vertices,GPUBufferUsage.VERTEX),this.cubeIndexBuffer=pt(this.device,t.indices,GPUBufferUsage.INDEX),this.cubeIndexCount=t.indices.length,this.sphereVertexBuffer=pt(this.device,e.vertices,GPUBufferUsage.VERTEX),this.sphereIndexBuffer=pt(this.device,e.indices,GPUBufferUsage.INDEX),this.sphereIndexCount=e.indices.length}addObject(t,e=[0,0,0],i=[1,1,1],r=[1,1,1,1]){const a=new Or(this.nextId++,t,e,i,r);return a.uniformBuffer=this.device.createBuffer({size:192,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.objects.push(a),this.onObjectAdded&&this.onObjectAdded(a),a}removeObject(t){const e=this.objects.findIndex(i=>i.id===t);e!==-1&&(this.objects[e].uniformBuffer.destroy(),this.objects.splice(e,1),this.onObjectRemoved&&this.onObjectRemoved(t))}updateObjectPosition(t,e){const i=this.objects.find(r=>r.id===t);i&&(i.position=e,this.onObjectUpdated&&this.onObjectUpdated(i))}updateObjectScale(t,e){const i=this.objects.find(r=>r.id===t);i&&(i.scale=e,this.onObjectUpdated&&this.onObjectUpdated(i))}updateObjectColor(t,e){const i=this.objects.find(r=>r.id===t);i&&(i.color=e,this.onObjectUpdated&&this.onObjectUpdated(i))}getAllObjects(){return this.objects}getObject(t){return this.objects.find(e=>e.id===t)}updateObjectUniforms(t){const e=t.getModelMatrix(),i=t.getNormalMatrix(),r=new Float32Array(t.color);this.device.queue.writeBuffer(t.uniformBuffer,0,e),this.device.queue.writeBuffer(t.uniformBuffer,64,i),this.device.queue.writeBuffer(t.uniformBuffer,128,r)}renderObjects(t,e,i,r){for(const a of this.objects){this.updateObjectUniforms(a);const n=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:a.uniformBuffer}}]});let o,l,c;if(a.type==="cube")o=this.cubeVertexBuffer,l=this.cubeIndexBuffer,c=this.cubeIndexCount;else if(a.type==="sphere")o=this.sphereVertexBuffer,l=this.sphereIndexBuffer,c=this.sphereIndexCount;else continue;t.setPipeline(e),t.setBindGroup(0,n),t.setVertexBuffer(0,o),t.setIndexBuffer(l,"uint16"),t.drawIndexed(c)}}}function kr(s){const t=parseInt(s.slice(1,3),16)/255,e=parseInt(s.slice(3,5),16)/255,i=parseInt(s.slice(5,7),16)/255;return[t,e,i]}function Xr(s){if(!s)return"#ffffff";const t=Math.round(s[0]*255).toString(16).padStart(2,"0"),e=Math.round(s[1]*255).toString(16).padStart(2,"0"),i=Math.round(s[2]*255).toString(16).padStart(2,"0");return`#${t}${e}${i}`}function Nr(s,t,e){const i=Hi([s[0]-t[0],s[1]-t[1],s[2]-t[2]]),r=Hi(Zi(e,i)),a=Zi(i,r);return new Float32Array([r[0],a[0],i[0],0,r[1],a[1],i[1],0,r[2],a[2],i[2],0,-ri(r,s),-ri(a,s),-ri(i,s),1])}function Yr(s,t=Math.PI/4){const r=1/Math.tan(t/2);return new Float32Array([r*s,0,0,0,0,r,0,0,0,0,(100+.1)/(.1-100),-1,0,0,200*.1/(.1-100),0])}function Hi(s){const t=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]);return[s[0]/t,s[1]/t,s[2]/t]}function Zi(s,t){return[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]]}function ri(s,t){return s[0]*t[0]+s[1]*t[1]+s[2]*t[2]}function xs(s,t){const e=new Float32Array(16);for(let i=0;i<4;i++)for(let r=0;r<4;r++){let a=0;for(let n=0;n<4;n++)a+=s[i+n*4]*t[n+r*4];e[i+r*4]=a}return e}const ui=1481005640,vs=1,Ps=1313821514,_s=5130562,At="$hzfxAsset",Ms=s=>typeof atob=="function"?Uint8Array.from(atob(s),t=>t.charCodeAt(0)):new Uint8Array(Buffer.from(s,"base64")),Wi=s=>{if(typeof btoa=="function"){let t="";for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}return Buffer.from(s).toString("base64")};function jr(s){const t=s.indexOf(","),e=s.slice(5,t),i=e.split(";")[0]||"application/octet-stream",r=s.slice(t+1),n=/;base64/i.test(e)?Ms(r):new TextEncoder().encode(decodeURIComponent(r));return{mime:i,bytes:n}}function $i(s){return(4-s%4)%4}async function ws(s,t={}){const{textureFormat:e="keep",quality:i=.85}=t,r=[],a=[];let n=0;const o=(G,F,H)=>{const se=n,ae=G.length;r.push({offset:se,length:ae,mime:F,kind:H}),a.push(G),n+=ae;const re=$i(ae);return re&&(a.push(new Uint8Array(re)),n+=re),r.length-1},l=e==="webp"&&typeof OffscreenCanvas<"u"&&typeof createImageBitmap=="function",c=[];for(const G of s.systems||[]){const F={...G};if(typeof F.textureImageData=="string"&&F.textureImageData.startsWith("data:")){let{mime:H,bytes:se}=jr(F.textureImageData);if(l&&H!=="image/webp")try{const ae=await createImageBitmap(new Blob([se],{type:H})),re=new OffscreenCanvas(ae.width,ae.height);re.getContext("2d").drawImage(ae,0,0);const j=await re.convertToBlob({type:"image/webp",quality:i}),tt=new Uint8Array(await j.arrayBuffer());tt.length<se.length&&(se=tt,H="image/webp")}catch{}F.textureImageData={[At]:o(se,H,"texture")}}if(typeof F.glbModelData=="string"&&F.glbModelData.length>0){const H=Ms(F.glbModelData);F.glbModelData={[At]:o(H,"model/gltf-binary","glb")}}c.push(F)}const d={...s,systems:c,assets:r},S=new TextEncoder().encode(JSON.stringify(d)),b=$i(S.length),h=new Uint8Array(n);let v=0;for(const G of a)h.set(G,v),v+=G.length;const C=S.length+b,z=20+C+8+n,D=new ArrayBuffer(z),_=new DataView(D),Z=new Uint8Array(D);let T=0;_.setUint32(T,ui,!0),T+=4,_.setUint32(T,vs,!0),T+=4,_.setUint32(T,z,!0),T+=4,_.setUint32(T,C,!0),T+=4,_.setUint32(T,Ps,!0),T+=4,Z.set(S,T),T+=S.length;for(let G=0;G<b;G++)Z[T++]=32;return _.setUint32(T,n,!0),T+=4,_.setUint32(T,_s,!0),T+=4,Z.set(h,T),T+=n,D}function di(s){return!s||s.byteLength<12?!1:new DataView(s).getUint32(0,!0)===ui}function fi(s){const t=new DataView(s);if(t.getUint32(0,!0)!==ui)throw new Error("[unpackHZFX] bad magic — not an .hzfx file");const e=t.getUint32(4,!0);if(e!==vs)throw new Error(`[unpackHZFX] unsupported version ${e}`);let i=12,r=null,a=-1;const n=new Uint8Array(s);for(;i+8<=s.byteLength;){const b=t.getUint32(i,!0);i+=4;const h=t.getUint32(i,!0);i+=4,h===Ps?r=JSON.parse(new TextDecoder().decode(n.subarray(i,i+b))):h===_s&&(a=i),i+=b}if(!r)throw new Error("[unpackHZFX] missing JSON chunk");const o=r.assets||[],l=b=>{const h=o[b];return!h||a<0?null:{...h,bytes:n.subarray(a+h.offset,a+h.offset+h.length)}},c=b=>b&&typeof b=="object"&&typeof b[At]=="number",d=(r.systems||[]).map(b=>{const h={...b};if(c(h.textureImageData)){const v=l(h.textureImageData[At]);h.textureImageData=v?`data:${v.mime};base64,${Wi(v.bytes)}`:void 0}if(c(h.glbModelData)){const v=l(h.glbModelData[At]);h.glbModelData=v?Wi(v.bytes):void 0}return h}),S={...r,systems:d};return delete S.assets,S}function qr(s){const t=new Uint8Array(s);let e="";for(let i=0;i<t.byteLength;i++)e+=String.fromCharCode(t[i]);return btoa(e)}function Rs(s){return{name:s.name,id:s.id,particleCount:s.particleCount,lifetime:s.lifetime,emissionRate:s.emissionRate,emissionDuration:s.emissionDuration,emissionDurationInfinite:s.emissionDurationInfinite||!1,startAt:s.startAt||0,keyframes:s.keyframes||null,keyframesEnabled:s.keyframesEnabled!==!1,particleSize:s.particleSize,particleSpeed:s.particleSpeed,emissionShape:s.emissionShape,outerLength:s.outerLength??s.cubeLength,innerLength:s.innerLength,outerRadius:s.outerRadius,innerRadius:s.innerRadius,squareSize:s.squareSize,squareInnerSize:s.squareInnerSize,circleInnerRadius:s.circleInnerRadius,circleOuterRadius:s.circleOuterRadius,fadeEnabled:s.fadeEnabled,colorTransitionEnabled:s.colorTransitionEnabled,particleColor:s.particleColor,startColor:s.startColor,endColor:s.endColor,randomColorEnabled:s.randomColorEnabled||!1,randomColors:s.randomColors||[],particleShape:s.particleShape||"square",particleShapeRotationX:s.particleShapeRotationX||0,particleShapeRotationY:s.particleShapeRotationY||0,particleShapeRotationZ:s.particleShapeRotationZ||0,pulseEnabled:s.pulseEnabled||!1,pulseAmplitude:s.pulseAmplitude??.5,pulseFrequency:s.pulseFrequency??1,pulsePhaseRandom:s.pulsePhaseRandom??0,pulseOpacity:s.pulseOpacity||!1,bloomEnabled:s.bloomEnabled,bloomIntensity:s.bloomIntensity,bloomColor:s.bloomColor,depthWriteEnabled:s.depthWriteEnabled||!1,burstMode:s.burstMode,gravityEnabled:s.gravityEnabled,gravityStrength:s.gravityStrength,dampingEnabled:s.dampingEnabled,dampingStrength:s.dampingStrength,attractorEnabled:s.attractorEnabled,attractorStrength:s.attractorStrength,attractorReverse:s.attractorReverse??!1,attractorPosition:s.attractorPosition,emissionRotationX:s.emissionRotationX,emissionRotationY:s.emissionRotationY,emissionRotationZ:s.emissionRotationZ,orientToDirection:s.orientToDirection??!1,emissionPositionX:s.emissionPositionX,emissionPositionY:s.emissionPositionY,emissionPositionZ:s.emissionPositionZ,rotation:s.rotation,rotationMode:s.rotationMode,minRotation:s.minRotation,maxRotation:s.maxRotation,orientX:s.orientX,orientY:s.orientY,orientZ:s.orientZ,overrideXVelocity:s.overrideXVelocity,overrideYVelocity:s.overrideYVelocity,overrideZVelocity:s.overrideZVelocity,xVelocity:s.xVelocity,yVelocity:s.yVelocity,zVelocity:s.zVelocity,circleVelocityDirection:s.circleVelocityDirection,cylinderVelocityDirection:s.cylinderVelocityDirection,cylinderInnerRadius:s.cylinderInnerRadius,cylinderOuterRadius:s.cylinderOuterRadius,cylinderHeight:s.cylinderHeight,planeWidth:s.planeWidth,planeDepth:s.planeDepth,rectangleWidth:s.rectangleWidth,rectangleHeight:s.rectangleHeight,coneOuterRadius:s.coneOuterRadius,coneInnerRadius:s.coneInnerRadius,coneHeight:s.coneHeight,torusMajorRadius:s.torusMajorRadius,torusMinorRadius:s.torusMinorRadius,lineLength:s.lineLength,hemisphereOuterRadius:s.hemisphereOuterRadius,hemisphereInnerRadius:s.hemisphereInnerRadius,discRadius:s.discRadius,annulusInnerRadius:s.annulusInnerRadius,annulusOuterRadius:s.annulusOuterRadius,capsuleRadius:s.capsuleRadius,capsuleHeight:s.capsuleHeight,arcStartAngle:s.arcStartAngle,arcEndAngle:s.arcEndAngle,arcInnerRadius:s.arcInnerRadius,arcOuterRadius:s.arcOuterRadius,spiralTurns:s.spiralTurns,spiralRadiusStart:s.spiralRadiusStart,spiralRadiusEnd:s.spiralRadiusEnd,spiralHeight:s.spiralHeight,frustumRadiusNear:s.frustumRadiusNear,frustumRadiusFar:s.frustumRadiusFar,frustumHeight:s.frustumHeight,cubeSurfaceSize:s.cubeSurfaceSize,sphereSurfaceRadius:s.sphereSurfaceRadius,boxFrameSize:s.boxFrameSize,polygonSides:s.polygonSides,polygonRadius:s.polygonRadius,aspectRatio:s.aspectRatio,randomSize:s.randomSize,minSize:s.minSize,maxSize:s.maxSize,fadeSizeEnabled:s.fadeSizeEnabled,increaseSizeEnabled:s.increaseSizeEnabled,sizeLifetimeSpeed:s.sizeLifetimeSpeed,opacity:s.opacity,randomSpeed:s.randomSpeed,minSpeed:s.minSpeed,maxSpeed:s.maxSpeed,oneOnlyMode:s.oneOnlyMode,confinementEnabled:s.confinementEnabled||!1,confinementShape:s.confinementShape||"box",confinementMode:s.confinementMode||"bounce",confinementSpace:s.confinementSpace||"world",confinementBoxHalfSize:s.confinementBoxHalfSize||[2,2,2],confinementSphereRadius:s.confinementSphereRadius??3,confinementRestitution:s.confinementRestitution??.8,confinementFriction:s.confinementFriction??.1,confinementCenter:s.confinementCenter,softBoundaryEnabled:s.softBoundaryEnabled||!1,softBoundaryStrength:s.softBoundaryStrength??5,softBoundaryFalloff:s.softBoundaryFalloff??.5,followSystemId:s.followSystemId||null,followSystemTranslation:s.followSystemTranslation??!0,hidden:s.hidden||!1,emissionTrailEnabled:s.emissionTrailEnabled||!1,emissionTrailDuration:s.emissionTrailDuration??1,emissionTrailWidth:s.emissionTrailWidth??.5,emissionTrailMinDistance:s.emissionTrailMinDistance??.05,emissionTrailMaxPoints:s.emissionTrailMaxPoints??100,emissionTrailSegments:s.emissionTrailSegments??8,emissionTrailMode:s.emissionTrailMode??"ribbon",emissionTrailShape:s.emissionTrailShape??"straight",emissionTrailShapeAmplitude:s.emissionTrailShapeAmplitude??.1,emissionTrailShapeFrequency:s.emissionTrailShapeFrequency??4,emissionTrailShapeSpeed:s.emissionTrailShapeSpeed??0,shapeStrokeEnabled:s.shapeStrokeEnabled||!1,shapeStrokeWidth:s.shapeStrokeWidth??.08,shapeStrokeSegments:s.shapeStrokeSegments??96,shapeStrokeShape:s.shapeStrokeShape??"straight",shapeStrokeAmplitude:s.shapeStrokeAmplitude??.08,shapeStrokeFrequency:s.shapeStrokeFrequency??10,shapeStrokeSpeed:s.shapeStrokeSpeed??0,shapeDisplay:s.shapeDisplay??!0,blendMode:s.blendMode??"normal",noiseDistortEnabled:s.noiseDistortEnabled||!1,noiseTilingX:s.noiseTilingX??3,noiseTilingY:s.noiseTilingY??3,noiseSpeed:s.noiseSpeed??-1.5,noiseAmplitude:s.noiseAmplitude??.08,velocityStretchEnabled:s.velocityStretchEnabled||!1,velocityStretchFactor:s.velocityStretchFactor??1,textureEnabled:s.textureEnabled||!1,textureType:s.textureType,textureFileName:s.textureFileName,imageDescription:s.imageDescription,glbModelEnabled:s.glbModelEnabled||!1,glbFileName:s.glbFileName,glbHasTexture:s.glbHasTexture||!1,useGlbTexture:s.useGlbTexture||!1,glbAnimated:s.glbAnimated||!1,animationIndex:s.animationIndex,animationSpeed:s.animationSpeed,animationLoop:s.animationLoop,glbDescription:s.glbDescription,script:s.script||void 0,displayUnit:s.displayUnit||"m"}}async function Hr(s,t,e="hzfx"){if(!s||!s.particleSystems||s.particleSystems.length===0){alert("No particle systems to save.");return}try{const i={version:"1.0",timestamp:new Date().toISOString(),systems:s.particleSystems.map(({config:d,system:S})=>({...Rs(d),textureImageData:d.textureEnabled&&!d.glbModelEnabled&&d.textureImageData?d.textureImageData:void 0,glbModelData:d.glbModelEnabled&&S.glbRawArrayBuffer?qr(S.glbRawArrayBuffer):void 0})),activeSystemIndex:s.activeSystemIndex,loop:s.loop||!1},r=e==="json"?"json":"hzfx";let a;if(r==="hzfx"){const d=await ws(i,{textureFormat:"webp"});a=new Blob([d],{type:"application/octet-stream"})}else a=new Blob([JSON.stringify(i,null,2)],{type:"application/json"});let n;if(t)n=t;else{const d=new Date;n=`particle-scene_${`${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,"0")}-${d.getDate().toString().padStart(2,"0")}_${d.getHours().toString().padStart(2,"0")}${d.getMinutes().toString().padStart(2,"0")}`}`}const o=`${n}.${r}`,l=URL.createObjectURL(a),c=document.createElement("a");c.href=l,c.download=o,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(l)}catch(i){console.error("Error saving scene:",i),alert("Error saving scene. See console for details.")}}function Zr(s){return new Promise((t,e)=>{try{const i=s.target.files[0];if(!i){e(new Error("No file selected"));return}const r=new FileReader;r.onload=a=>{try{const n=a.target.result;let o;if(di(n)?o=fi(n):o=JSON.parse(new TextDecoder().decode(n)),!Array.isArray(o.systems)||o.systems.length===0)throw new Error("No valid particle systems found in the file");t({systems:o.systems.slice(),activeSystemIndex:o.activeSystemIndex||0})}catch(n){console.error("Error loading scene:",n),alert("Error loading scene: "+n.message),e(n)}s.target.value=""},r.onerror=()=>{alert("Failed to read the file"),e(new Error("Failed to read the file")),s.target.value=""},r.readAsArrayBuffer(i)}catch(i){console.error("Error in loadScene:",i),e(i)}})}async function Wr(s){if(!s||typeof s!="string")throw new Error("[fetchPreset] url must be a non-empty string");const t=await fetch(s);if(!t.ok)throw new Error(`[fetchPreset] HTTP ${t.status}: ${t.statusText}`);const e=await t.arrayBuffer();let i;if(di(e)?i=fi(e):i=JSON.parse(new TextDecoder().decode(e)),!Array.isArray(i.systems)||i.systems.length===0)throw new Error('[fetchPreset] Invalid preset: "systems" must be a non-empty array');return{version:i.version,systems:i.systems,activeSystemIndex:i.activeSystemIndex??0}}const $r=s=>`
1178
1196
  @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
1179
1197
  var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(-1.0, 1.0), vec2f(3.0, 1.0));
1180
1198
  return vec4f(p[i], 0.0, 1.0);
@@ -1183,14 +1201,14 @@ return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles,
1183
1201
  @fragment fn fs(@builtin(position) pos: vec4f) -> @builtin(frag_depth) f32 {
1184
1202
  return textureLoad(src, vec2i(pos.xy), 0);
1185
1203
  }
1186
- `;async function Wr(s,t={}){const{getSceneDepth:e=null,autoRespawn:i=!0}=t;let r,n,a;const o=!!(s&&s.device&&s.context);o?({device:r,context:n,canvas:a}=s,a||(a=n.canvas)):(a=s,{device:r,context:n}=await us(a));const c=navigator.gpu.getPreferredCanvasFormat(),l=t.manager||new cs(r),d={layouts:{},pipelines:{}};function S(u){const f=u?"ms":"ss";if(!d.pipelines[f]){const m=r.createShaderModule({code:Zr(u)}),g=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",multisampled:u}}]});d.layouts[f]=g,d.pipelines[f]=r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:[g]}),vertex:{module:m,entryPoint:"vs"},fragment:{module:m,entryPoint:"fs",targets:[]},primitive:{topology:"triangle-list"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"always"}})}return{pipeline:d.pipelines[f],layout:d.layouts[f]}}const b={bloomSourceTextures:{},bloomCompositeTextures:{},combinedTexture:null,getBloomSourceTexture(u,f,m){return this.bloomSourceTextures[u]||(this.bloomSourceTextures[u]=r.createTexture({size:[f,m],format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING})),this.bloomSourceTextures[u]},getBloomCompositeTexture(u,f,m){return this.bloomCompositeTextures[u]||(this.bloomCompositeTextures[u]=r.createTexture({size:[f,m],format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING})),this.bloomCompositeTextures[u]},getCombinedTexture(u,f){return this.combinedTexture||(this.combinedTexture=r.createTexture({size:[u,f],format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING})),this.combinedTexture},resizeTextures(){Object.values(this.bloomSourceTextures).forEach(u=>u==null?void 0:u.destroy()),Object.values(this.bloomCompositeTextures).forEach(u=>u==null?void 0:u.destroy()),this.combinedTexture&&this.combinedTexture.destroy(),this.bloomSourceTextures={},this.bloomCompositeTextures={},this.combinedTexture=null}},p={systemBindGroups:{},systemBloomHorizontalBindGroups:{},secondHorizontalBindGroups:{},systemBloomCompositeBindGroups:{},combinedBloomCompositeBindGroups:{},combinedInitialBindGroup:null,finalBindGroup:null,textureStates:{},textureRefs:{},clear(){this.systemBindGroups={},this.systemBloomHorizontalBindGroups={},this.secondHorizontalBindGroups={},this.systemBloomCompositeBindGroups={},this.combinedBloomCompositeBindGroups={},this.combinedInitialBindGroup=null,this.finalBindGroup=null,this.textureStates={},this.textureRefs={}}},v=r.createBuffer({size:96,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),E=r.createBuffer({size:208,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),I=r.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),z=r.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),_=r.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),W=pt(r,new Uint16Array([0,1,2,0,2,3]),GPUBufferUsage.INDEX),T={},G=()=>pt(r,new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST);l.onSystemCreated=u=>{T[u]||(T[u]=G())};const F=4e4,Z=new Float32Array(F*8),re=new Float32Array(F*4),ae=new Float32Array(F*4),ne=r.createBuffer({size:F*8*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),q=r.createBuffer({size:F*4*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),tt=r.createBuffer({size:F*4*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),xt=new Map,Xe=new Map,Nt=8,_e=[];function pi(u){for(const f of _e)if(f.ids.has(u))return f;return null}function ws(u,f){if(!u.pos)return;u.hist.push({t:f,x:u.pos[0],y:u.pos[1],z:u.pos[2]});const m=f-Nt;for(;u.hist.length>2&&u.hist[0].t<m;)u.hist.shift()}function hi(u,f,m){const g=u.hist;if(g.length===0){const R=u.pos;return R&&(m[0]=R[0],m[1]=R[1],m[2]=R[2]),m}let y;if(f>=g[g.length-1].t)return y=g[g.length-1],m[0]=y.x,m[1]=y.y,m[2]=y.z,m;if(f<=g[0].t)return y=g[0],m[0]=y.x,m[1]=y.y,m[2]=y.z,m;for(let R=g.length-1;R>0;R--)if(g[R-1].t<=f){const P=g[R-1],M=g[R],x=(f-P.t)/Math.max(1e-6,M.t-P.t);return m[0]=P.x+(M.x-P.x)*x,m[1]=P.y+(M.y-P.y)*x,m[2]=P.z+(M.z-P.z)*x,m}return y=g[0],m[0]=y.x,m[1]=y.y,m[2]=y.z,m}const ht=Math.PI*2,oe=new Array(257),le=new Array(257),ce=new Array(257),Yt=new Array(257),jt=new Array(257),qt=new Array(257);new Array(257),new Array(257),new Array(257);const Ee=[0,0,0];function Bs(u){const f=u.emissionRotationX||0,m=u.emissionRotationY||0,g=u.emissionRotationZ||0;if(!f&&!m&&!g)return null;const y=f*Math.PI/180,R=m*Math.PI/180,P=g*Math.PI/180,M=Math.cos(y),x=Math.sin(y),B=Math.cos(R),h=Math.sin(R),w=Math.cos(P),C=Math.sin(P);return[B*w,x*h*w-M*C,M*h*w+x*C,B*C,x*h*C+M*w,M*h*C-x*w,-h,x*B,M*B]}function Ut(u,f,m,g,y){return y[0]=u[0]*f+u[1]*m+u[2]*g,y[1]=u[3]*f+u[4]*m+u[5]*g,y[2]=u[6]*f+u[7]*m+u[8]*g,y}function Rs(u,f,m,g,y,R,P){let M=u,x=f,B=m;g&&(Ut(g,M,x,B,P),M=P[0],x=P[1],B=P[2]),M+=R.emissionPositionX||0,x+=R.emissionPositionY||0,B+=R.emissionPositionZ||0,y._simRotMatrix&&(Ut(y._simRotMatrix,M,x,B,P),M=P[0],x=P[1],B=P[2]);const h=y._simPosition;return P[0]=M+(h?h[0]:0),P[1]=x+(h?h[1]:0),P[2]=B+(h?h[2]:0),P}function Ts(u,f,m,g,y,R){let P=u,M=f,x=m;return g&&(Ut(g,P,M,x,R),P=R[0],M=R[1],x=R[2]),y._simRotMatrix&&(Ut(y._simRotMatrix,P,M,x,R),P=R[0],M=R[1],x=R[2]),R[0]=P,R[1]=M,R[2]=x,R}function Ht(u,f,m,g,y){const R=f*2,P=m*2,M=2*(R+P);let x=(u%1+1)%1*M,B=0,h=0;return x<R?(B=-f+x,h=m):(x-=R)<P?(B=f,h=m-x):(x-=P)<R?(B=f-x,h=-m):(x-=R,B=-f,h=-m+x),g==="xz"?(y[0]=B,y[1]=0,y[2]=h):(y[0]=B,y[1]=h,y[2]=0),y}function As(u){const f=u.emissionShape,m=Math.max(1,Math.min(256,Math.floor(u.shapeStrokeSegments??96)));let g=0,y=!1,R=[0,0,1];const P=Ee;if(f==="circle"){y=!0,g=Math.max(3,m),R=[0,0,1];const M=u.circleOuterRadius??2;for(let x=0;x<g;x++){const B=x/g*ht;oe[x]=Math.cos(B)*M,le[x]=Math.sin(B)*M,ce[x]=0}}else if(f==="disc"){y=!0,g=Math.max(3,m),R=[0,1,0];const M=u.discRadius??2;for(let x=0;x<g;x++){const B=x/g*ht;oe[x]=Math.cos(B)*M,le[x]=0,ce[x]=Math.sin(B)*M}}else if(f==="annulus"){y=!0,g=Math.max(3,m),R=[0,1,0];const M=u.annulusInnerRadius??1,x=u.annulusOuterRadius??2,B=M+(x-M)*.5;for(let h=0;h<g;h++){const w=h/g*ht;oe[h]=Math.cos(w)*B,le[h]=0,ce[h]=Math.sin(w)*B}}else if(f==="arc"){y=!1,g=Math.max(2,m+1),R=[0,0,1];const M=u.arcInnerRadius??0,x=u.arcOuterRadius??2,B=M>0?M+(x-M)*.5:x,h=(u.arcStartAngle??0)*Math.PI/180,w=(u.arcEndAngle??180)*Math.PI/180;for(let C=0;C<g;C++){const H=g>1?C/(g-1):0,O=h+(w-h)*H;oe[C]=Math.cos(O)*B,le[C]=Math.sin(O)*B,ce[C]=0}}else if(f==="square"){y=!0,g=Math.max(4,m),R=[0,0,1];const M=u.squareSize??2;for(let x=0;x<g;x++)Ht(x/g,M,M,"xy",P),oe[x]=P[0],le[x]=P[1],ce[x]=P[2]}else if(f==="rectangle"){y=!0,g=Math.max(4,m),R=[0,0,1];const M=(u.rectangleWidth??2)*.5,x=(u.rectangleHeight??2)*.5;for(let B=0;B<g;B++)Ht(B/g,M,x,"xy",P),oe[B]=P[0],le[B]=P[1],ce[B]=P[2]}else if(f==="plain"){y=!0,g=Math.max(4,m),R=[0,1,0];const M=(u.planeWidth??2)*.5,x=(u.planeDepth??2)*.5;for(let B=0;B<g;B++)Ht(B/g,M,x,"xz",P),oe[B]=P[0],le[B]=P[1],ce[B]=P[2]}else if(f==="line"){y=!1,g=Math.max(2,m+1),R=[0,0,1];const M=u.lineLength??4;for(let x=0;x<g;x++){const B=g>1?x/(g-1):0;oe[x]=0,le[x]=(B-.5)*M,ce[x]=0}}else if(f==="polygon"){y=!0,g=Math.max(3,m),R=[0,0,1];const M=Math.max(3,Math.floor(u.polygonSides??6)),x=u.polygonRadius??2;for(let B=0;B<g;B++){const h=B/g*M,w=Math.floor(h),C=h-w,H=w/M*ht,O=(w+1)/M*ht,L=Math.cos(H)*x,N=Math.sin(H)*x,V=Math.cos(O)*x,xe=Math.sin(O)*x;oe[B]=L+(V-L)*C,le[B]=N+(xe-N)*C,ce[B]=0}}else g=0;return{count:g,closed:y,planeNormal:R}}function Es(u,f,m){if(!m.shapeStrokeEnabled||m.hidden)return u;const{count:g,closed:y,planeNormal:R}=As(m);if(g<2)return u;const P=Bs(m),M=Math.max(1e-4,m.shapeStrokeWidth??.08),x=Math.max(0,m.opacity??1);if(x<=0)return u;Ts(R[0],R[1],R[2],P,f,Ee);let B=Math.hypot(Ee[0],Ee[1],Ee[2])||1;const h=Ee[0]/B,w=Ee[1]/B,C=Ee[2]/B;for(let U=0;U<g;U++)Rs(oe[U],le[U],ce[U],P,f,m,Ee),oe[U]=Ee[0],le[U]=Ee[1],ce[U]=Ee[2];const H=m.shapeStrokeShape??"straight";if(H!=="straight"){const U=m.shapeStrokeAmplitude??.08,Q=m.shapeStrokeFrequency??10,Ie=m.shapeStrokeSpeed??0;for(let $=0;$<g;$++){const pe=$===0?y?g-1:0:$-1,te=$===g-1?y?0:g-1:$+1,ye=oe[te]-oe[pe],J=le[te]-le[pe],ee=ce[te]-ce[pe],K=w*ee-C*J,ie=C*ye-h*ee,ue=h*J-w*ye,ge=Math.hypot(K,ie,ue)||1,ve=K/ge,de=ie/ge,He=ue/ge,Me=y?$/g:$/Math.max(1,g-1),be=ht*Q*Me+Ie*Ve;let he=0,me=0;H==="zigzag"?he=U*Math.sign(Math.sin(be)||1):H==="sine"?he=U*Math.sin(be):H==="spiral"&&(he=U*Math.sin(be),me=U*Math.cos(be)),oe[$]+=ve*he+h*me,le[$]+=de*he+w*me,ce[$]+=He*he+C*me}}const O=y?g:g-1,L=m.bloomIntensity||1,N=m.startColor??m.particleColor??[1,1,1],V=m.endColor??N,xe=m.particleColor??N,ct=m.randomColorEnabled&&Array.isArray(m.randomColors)&&m.randomColors.length>0?m.randomColors[0]:null,Se=M*.5,_t=Math.max(M*4,1e-4),je=(m.shapeStrokeSpeed??0)*Ve;let it=0;for(let U=0;U<O;U++){const Q=y?(U+1)%g:U+1;it+=Math.hypot(oe[Q]-oe[U],le[Q]-le[U],ce[Q]-ce[U])}const ti=y?Math.max(1,Math.round(it/_t)):Math.max(it/_t,1e-6),Mt=it>1e-6?ti/it:0;let qe=0,wt=!1,ut=0,Ue=0,dt=0;for(let U=0;U<g;U++){const Q=U===0?y?g-1:0:U-1,Ie=U===g-1?y?0:g-1:U+1;let $=oe[Ie]-oe[Q],pe=le[Ie]-le[Q],te=ce[Ie]-ce[Q];const ye=Math.hypot($,pe,te)||1;$/=ye,pe/=ye,te/=ye;let J=w*te-C*pe,ee=C*$-h*te,K=h*pe-w*$,ie=Math.hypot(J,ee,K);if(ie<1e-5){const ue=D.right[0],ge=D.right[1],ve=D.right[2],de=ue*$+ge*pe+ve*te;J=ue-de*$,ee=ge-de*pe,K=ve-de*te,ie=Math.hypot(J,ee,K)}if(ie<1e-5){const ue=D.up[0],ge=D.up[1],ve=D.up[2],de=ue*$+ge*pe+ve*te;J=ue-de*$,ee=ge-de*pe,K=ve-de*te,ie=Math.hypot(J,ee,K)||1}J/=ie,ee/=ie,K/=ie,wt&&ut*J+Ue*ee+dt*K<0&&(J=-J,ee=-ee,K=-K),Yt[U]=J,jt[U]=ee,qt[U]=K,ut=J,Ue=ee,dt=K,wt=!0}for(let U=0;U<O&&!(u+54>Ce.length);U++){const Q=y?(U+1)%g:U+1,Ie=oe[U],$=le[U],pe=ce[U],te=oe[Q],ye=le[Q],J=ce[Q];let ee=te-Ie,K=ye-$,ie=J-pe;const ue=Math.hypot(ee,K,ie)||1;ee/=ue,K/=ue,ie/=ue;const ge=y?U/g:U/Math.max(1,g-1),ve=y?Q/g:Q/Math.max(1,g-1),de=qe*Mt+je,He=(qe+ue)*Mt+je;let Me,be,he,me,we,Be;ct?(Me=me=ct[0],be=we=ct[1],he=Be=ct[2]):m.colorTransitionEnabled?(Me=N[0]+(V[0]-N[0])*ge,be=N[1]+(V[1]-N[1])*ge,he=N[2]+(V[2]-N[2])*ge,me=N[0]+(V[0]-N[0])*ve,we=N[1]+(V[1]-N[1])*ve,Be=N[2]+(V[2]-N[2])*ve):(Me=me=xe[0],be=we=xe[1],he=Be=xe[2]),Me=Math.min(1,Me*L),be=Math.min(1,be*L),he=Math.min(1,he*L),me=Math.min(1,me*L),we=Math.min(1,we*L),Be=Math.min(1,Be*L);const Bt=Yt[U],bt=jt[U],Oe=qt[U],Le=Yt[Q],ze=jt[Q],Rt=qt[Q],Ot=Ie+Bt*Se,Lt=$+bt*Se,Tt=pe+Oe*Se,Re=Ie-Bt*Se,Te=$-bt*Se,Ae=pe-Oe*Se,st=te+Le*Se,rt=ye+ze*Se,At=J+Rt*Se,Ze=te-Le*Se,We=ye-ze*Se,$e=J-Rt*Se,ft=(A,X,fe,Y,k,j,se,Je,Ke)=>{Ce[u++]=A,Ce[u++]=X,Ce[u++]=fe,Ce[u++]=Y,Ce[u++]=k,Ce[u++]=j,Ce[u++]=se,Ce[u++]=Je,Ce[u++]=Ke};ft(Ot,Lt,Tt,Me,be,he,x,de,0),ft(Re,Te,Ae,Me,be,he,x,de,1),ft(st,rt,At,me,we,Be,x,He,0),ft(Re,Te,Ae,Me,be,he,x,de,1),ft(Ze,We,$e,me,we,Be,x,He,1),ft(st,rt,At,me,we,Be,x,He,0),qe+=ue}return u}const Cs=.41421356;function Us(){xt.clear(),Xe.clear();let u=0,f=0,m=0;D.position[0],D.position[1],D.position[2];for(const{system:g,config:y}of l.particleSystems){if(y.hidden)continue;if(y.emissionTrailEnabled&&!y.glbModelEnabled){g.readbackAndProcessParticles();const P=g.particleData,M=g.particleVelocities,x=g.activeParticles;if(P&&M&&x>0){const B=y.emissionTrailMode==="particles",h=u,w=y.emissionTrailDuration??1,C=y.opacity??1,H=y.particleSize??.5,O=y.bloomIntensity||1,L=Math.max(1,Math.min(64,y.emissionTrailSegments??8)),N=y.emissionTrailShape||"straight",V=y.followSystemTranslation??!0,xe=g._simPosition,ct=V&&xe?xe[0]:0,Se=V&&xe?xe[1]:0,_t=V&&xe?xe[2]:0,je=g._simVelocity,it=je?je[0]:0,ti=je?je[1]:0,Mt=je?je[2]:0,qe=pi(y.id),wt=!!(V&&qe&&qe.hist&&qe.hist.length>1);for(let ut=0;ut<x;ut++){const Ue=ut*8,dt=P[Ue],U=P[Ue+1],Q=P[Ue+2],Ie=dt+ct,$=U+Se,pe=Q+_t;let te=P[Ue+3],ye=P[Ue+4],J=P[Ue+5];const ee=P[Ue+6],K=P[Ue+7];if(ee>=K||K<=0)continue;const ie=ee/K;if(y.colorTransitionEnabled){const A=y.startColor??[1,0,0],X=y.endColor??[0,0,1];te=A[0]+(X[0]-A[0])*ie,ye=A[1]+(X[1]-A[1])*ie,J=A[2]+(X[2]-A[2])*ie}te=Math.min(1,te*O),ye=Math.min(1,ye*O),J=Math.min(1,J*O);let ue=H;if(y.randomSize){const A=Math.sin(K*54321.67)*43758.5453%1,X=A<0?A+1:A;ue=(y.minSize??.1)+((y.maxSize??.5)-(y.minSize??.1))*X}if(y.fadeSizeEnabled){const A=Math.max(.01,Math.min(10,y.sizeLifetimeSpeed??1));ue*=1-Math.pow(ie,1/A)}if(y.increaseSizeEnabled){const A=Math.max(.01,Math.min(10,y.sizeLifetimeSpeed??1));ue*=1+Math.pow(ie,1/A)}if(ue<=0||ie>.9)continue;const ge=Math.min((.9-ie)*(1/.2),1),ve=.75*ue*Cs*ge;let de=C;if(y.fadeEnabled&&(de*=Math.max(0,1-ie)),de*=ge,de<.01)continue;const He=ut*4,Me=M[He],be=M[He+1],he=M[He+2],me=Me+it,we=be+ti,Be=he+Mt,Bt=Math.sqrt(me*me+we*we+Be*Be);if(Bt<.001)continue;const bt=1/Bt,Oe=me*bt,Le=we*bt,ze=Be*bt,Rt=D.right[0],Ot=D.right[1],Lt=D.right[2];let Tt=Rt*Oe+Ot*Le+Lt*ze,Re=Rt-Tt*Oe,Te=Ot-Tt*Le,Ae=Lt-Tt*ze,st=Math.sqrt(Re*Re+Te*Te+Ae*Ae);if(st<.2){const A=D.up[0],X=D.up[1],fe=D.up[2],Y=A*Oe+X*Le+fe*ze;Re=A-Y*Oe,Te=X-Y*Le,Ae=fe-Y*ze,st=Math.sqrt(Re*Re+Te*Te+Ae*Ae)||1}Re/=st,Te/=st,Ae/=st;const rt=Math.min(w,ee);if(rt<.001)continue;const At=y.gravityEnabled&&y.gravityStrength||0,Ze=Ys,We=js,$e=qs;if(y.orientToDirection&&y.burstMode&&wt){const A=g._emitSimRotY||0,X=Hs,fe=Zs,Y=Ws;for(let k=0;k<=L;k++){const j=hi(qe,Ve-k/L*rt,Ti);X[k]=j[0],fe[k]=j[1],Y[k]=j[2]}for(let k=0;k<=L;k++){const j=k>0?k-1:0,se=k<L?k+1:L;let Je=X[j]-X[se],Ke=Y[j]-Y[se];const nt=(Math.hypot(Je,Ke)>1e-5?Math.atan2(Je,Ke):Math.atan2(it,Mt))-A,Ge=Math.cos(nt),Fe=Math.sin(nt),et=k/L*rt,ii=-.5*At*et*et;Ze[k]=Ge*dt+Fe*Q+X[k],We[k]=U+ii+fe[k],$e[k]=-Fe*dt+Ge*Q+Y[k]}}else for(let A=0;A<=L;A++){const X=A/L*rt,fe=-.5*At*X*X;if(wt){const Y=hi(qe,Ve-X,Ti);Ze[A]=dt-Me*X+Y[0],We[A]=U-be*X+fe+Y[1],$e[A]=Q-he*X+Y[2]}else Ze[A]=Ie-me*X,We[A]=$-we*X+fe,$e[A]=pe-Be*X}if(N!=="straight"){const A=y.emissionTrailShapeAmplitude??.1,X=y.emissionTrailShapeFrequency??4,fe=y.emissionTrailShapeSpeed??0;let Y=-ze,k=0,j=Oe,se=Math.sqrt(Y*Y+j*j);se<1e-6&&(Y=0,k=ze,j=-Le,se=Math.sqrt(Y*Y+k*k+j*j)||1),Y/=se,k/=se,j/=se;const Je=Le*j-ze*k,Ke=ze*Y-Oe*j,Qe=Oe*k-Le*Y;for(let Pe=1;Pe<=L;Pe++){const nt=Pe/L*rt,Ge=2*Math.PI*X*(Ve-nt)+fe*Ve;let Fe=0,et=0;N==="zigzag"?Fe=A*Math.sign(Math.sin(Ge)):N==="sine"?Fe=A*Math.sin(Ge):N==="spiral"&&(Fe=A*Math.sin(Ge),et=A*Math.cos(Ge)),Ze[Pe]+=Y*Fe+Je*et,We[Pe]+=k*Fe+Ke*et,$e[Pe]+=j*Fe+Qe*et}}if(B)for(let A=1;A<=L&&u<F;A++){const X=A/L,fe=Ze[A]-ct,Y=We[A]-Se,k=$e[A]-_t,j=u*8,se=u*4;Z[j]=fe,Z[j+1]=Y,Z[j+2]=k,Z[j+3]=te,Z[j+4]=ye,Z[j+5]=J,Z[j+6]=ee+(K-ee)*X,Z[j+7]=K,re[se]=0,re[se+1]=0,re[se+2]=0,re[se+3]=0,ae[se]=fe,ae[se+1]=Y,ae[se+2]=k,ae[se+3]=0,u++}else for(let A=0;A<L&&!(f+42>Ye.length);A++){const X=A/L,fe=(A+1)/L,Y=Ze[A],k=We[A],j=$e[A],se=Ze[A+1],Je=We[A+1],Ke=$e[A+1],Qe=ve*(1-X),Pe=ve*(1-fe),nt=de*(1-X)*(1-X),Ge=de*(1-fe)*(1-fe),Fe=Y+Re*Qe,et=k+Te*Qe,ii=j+Ae*Qe,Fi=Y-Re*Qe,Di=k-Te*Qe,Vi=j-Ae*Qe,Oi=se+Re*Pe,Li=Je+Te*Pe,ki=Ke+Ae*Pe,ar=se-Re*Pe,or=Je-Te*Pe,lr=Ke-Ae*Pe,St=(cr,ur,dr,fr)=>{Ye[f++]=cr,Ye[f++]=ur,Ye[f++]=dr,Ye[f++]=te,Ye[f++]=ye,Ye[f++]=J,Ye[f++]=fr};St(Fe,et,ii,nt),St(Fi,Di,Vi,nt),St(Oi,Li,ki,Ge),St(Fi,Di,Vi,nt),St(ar,or,lr,Ge),St(Oi,Li,ki,Ge)}}B&&u>h&&xt.set(y.id,{first:h,count:u-h})}}const R=m;m=Es(m,g,y),m>R&&Xe.set(y.id,{first:R/9,count:(m-R)/9})}u>0&&(r.queue.writeBuffer(ne,0,Z,0,u*8),r.queue.writeBuffer(q,0,re,0,u*4),r.queue.writeBuffer(tt,0,ae,0,u*4)),vt=f/7,vt>0&&r.queue.writeBuffer(Zt,0,Ye,0,f),Mi=m/9,Mi>0&&r.queue.writeBuffer(Wt,0,Ce,0,m)}const mi=()=>{r.queue.writeBuffer(I,0,new Float32Array([1,0,a.width,a.height,0,0,0,0])),r.queue.writeBuffer(z,0,new Float32Array([0,1,a.width,a.height,0,0,0,0]))};mi();const yi=new Float32Array(16).fill(0);yi[0]=1,r.queue.writeBuffer(_,0,yi);const De=ms(r),Ne=ps(r),{particlePipeline:Is,particleAdditivePipeline:zs,particleDepthWritePipeline:Gs,blurPipeline:It,compositePipeline:Fs,directRenderPipeline:gi,finalCompositePipeline:Ds,glbMeshPipeline:Vs}=hs(r,c,Ne),bi=r.createShaderModule({code:`
1204
+ `;async function Jr(s,t={}){const{getSceneDepth:e=null,autoRespawn:i=!0}=t;let r,a,n;const o=!!(s&&s.device&&s.context);o?({device:r,context:a,canvas:n}=s,n||(n=a.canvas)):(n=s,{device:r,context:a}=await ds(n));const l=navigator.gpu.getPreferredCanvasFormat(),c=t.manager||new us(r),d={layouts:{},pipelines:{}};function S(u){const f=u?"ms":"ss";if(!d.pipelines[f]){const y=r.createShaderModule({code:$r(u)}),p=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",multisampled:u}}]});d.layouts[f]=p,d.pipelines[f]=r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:[p]}),vertex:{module:y,entryPoint:"vs"},fragment:{module:y,entryPoint:"fs",targets:[]},primitive:{topology:"triangle-list"},depthStencil:{format:"depth24plus",depthWriteEnabled:!0,depthCompare:"always"}})}return{pipeline:d.pipelines[f],layout:d.layouts[f]}}const b={bloomSourceTextures:{},bloomCompositeTextures:{},combinedTexture:null,getBloomSourceTexture(u,f,y){const p=u;return this.bloomSourceTextures[p]||(this.bloomSourceTextures[p]=r.createTexture({size:[f,y],format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING})),this.bloomSourceTextures[p]},getBloomCompositeTexture(u,f,y){const p=u;return this.bloomCompositeTextures[p]||(this.bloomCompositeTextures[p]=r.createTexture({size:[f,y],format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING})),this.bloomCompositeTextures[p]},getCombinedTexture(u,f){return this.combinedTexture||(this.combinedTexture=r.createTexture({size:[u,f],format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING})),this.combinedTexture},resizeTextures(){Object.values(this.bloomSourceTextures).forEach(u=>u==null?void 0:u.destroy()),Object.values(this.bloomCompositeTextures).forEach(u=>u==null?void 0:u.destroy()),this.combinedTexture&&this.combinedTexture.destroy(),this.bloomSourceTextures={},this.bloomCompositeTextures={},this.combinedTexture=null}},h={systemBindGroups:{},systemBloomHorizontalBindGroups:{},secondHorizontalBindGroups:{},systemBloomCompositeBindGroups:{},combinedBloomCompositeBindGroups:{},combinedInitialBindGroup:null,finalBindGroup:null,textureStates:{},textureRefs:{},clear(){this.systemBindGroups={},this.systemBloomHorizontalBindGroups={},this.secondHorizontalBindGroups={},this.systemBloomCompositeBindGroups={},this.combinedBloomCompositeBindGroups={},this.combinedInitialBindGroup=null,this.finalBindGroup=null,this.textureStates={},this.textureRefs={}}},v=r.createBuffer({size:96,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),C=r.createBuffer({size:208,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),z=r.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),D=r.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),_=r.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),Z=pt(r,new Uint16Array([0,1,2,0,2,3]),GPUBufferUsage.INDEX),T={},G=()=>pt(r,new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST);c.onSystemCreated=u=>{T[u]||(T[u]=G())};const F=4e4,H=new Float32Array(F*8),se=new Float32Array(F*4),ae=new Float32Array(F*4),re=r.createBuffer({size:F*8*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),j=r.createBuffer({size:F*4*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),tt=r.createBuffer({size:F*4*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),xt=new Map,nt=new Map,Nt=8,_e=[];function pi(u){for(const f of _e)if(f.ids.has(u))return f;return null}function Bs(u,f){if(!u.pos)return;u.hist.push({t:f,x:u.pos[0],y:u.pos[1],z:u.pos[2]});const y=f-Nt;for(;u.hist.length>2&&u.hist[0].t<y;)u.hist.shift()}function hi(u,f,y){const p=u.hist;if(p.length===0){const w=u.pos;return w&&(y[0]=w[0],y[1]=w[1],y[2]=w[2]),y}let g;if(f>=p[p.length-1].t)return g=p[p.length-1],y[0]=g.x,y[1]=g.y,y[2]=g.z,y;if(f<=p[0].t)return g=p[0],y[0]=g.x,y[1]=g.y,y[2]=g.z,y;for(let w=p.length-1;w>0;w--)if(p[w-1].t<=f){const P=p[w-1],R=p[w],x=(f-P.t)/Math.max(1e-6,R.t-P.t);return y[0]=P.x+(R.x-P.x)*x,y[1]=P.y+(R.y-P.y)*x,y[2]=P.z+(R.z-P.z)*x,y}return g=p[0],y[0]=g.x,y[1]=g.y,y[2]=g.z,y}const ht=Math.PI*2,ne=new Array(257),oe=new Array(257),le=new Array(257),Yt=new Array(257),jt=new Array(257),qt=new Array(257);new Array(257),new Array(257),new Array(257);const Ae=[0,0,0];function Ts(u){const f=u.emissionRotationX||0,y=u.emissionRotationY||0,p=u.emissionRotationZ||0;if(!f&&!y&&!p)return null;const g=f*Math.PI/180,w=y*Math.PI/180,P=p*Math.PI/180,R=Math.cos(g),x=Math.sin(g),B=Math.cos(w),m=Math.sin(w),M=Math.cos(P),E=Math.sin(P);return[B*M,x*m*M-R*E,R*m*M+x*E,B*E,x*m*E+R*M,R*m*E-x*M,-m,x*B,R*B]}function Ut(u,f,y,p,g){return g[0]=u[0]*f+u[1]*y+u[2]*p,g[1]=u[3]*f+u[4]*y+u[5]*p,g[2]=u[6]*f+u[7]*y+u[8]*p,g}function Es(u,f,y,p,g,w,P){let R=u,x=f,B=y;p&&(Ut(p,R,x,B,P),R=P[0],x=P[1],B=P[2]),R+=w.emissionPositionX||0,x+=w.emissionPositionY||0,B+=w.emissionPositionZ||0,g._simRotMatrix&&(Ut(g._simRotMatrix,R,x,B,P),R=P[0],x=P[1],B=P[2]);const m=g._simPosition;return P[0]=R+(m?m[0]:0),P[1]=x+(m?m[1]:0),P[2]=B+(m?m[2]:0),P}function As(u,f,y,p,g,w){let P=u,R=f,x=y;return p&&(Ut(p,P,R,x,w),P=w[0],R=w[1],x=w[2]),g._simRotMatrix&&(Ut(g._simRotMatrix,P,R,x,w),P=w[0],R=w[1],x=w[2]),w[0]=P,w[1]=R,w[2]=x,w}function Ht(u,f,y,p,g){const w=f*2,P=y*2,R=2*(w+P);let x=(u%1+1)%1*R,B=0,m=0;return x<w?(B=-f+x,m=y):(x-=w)<P?(B=f,m=y-x):(x-=P)<w?(B=f-x,m=-y):(x-=w,B=-f,m=-y+x),p==="xz"?(g[0]=B,g[1]=0,g[2]=m):(g[0]=B,g[1]=m,g[2]=0),g}function Cs(u){const f=u.emissionShape,y=Math.max(1,Math.min(256,Math.floor(u.shapeStrokeSegments??96)));let p=0,g=!1,w=[0,0,1];const P=Ae;if(f==="circle"){g=!0,p=Math.max(3,y),w=[0,0,1];const R=u.circleOuterRadius??2;for(let x=0;x<p;x++){const B=x/p*ht;ne[x]=Math.cos(B)*R,oe[x]=Math.sin(B)*R,le[x]=0}}else if(f==="disc"){g=!0,p=Math.max(3,y),w=[0,1,0];const R=u.discRadius??2;for(let x=0;x<p;x++){const B=x/p*ht;ne[x]=Math.cos(B)*R,oe[x]=0,le[x]=Math.sin(B)*R}}else if(f==="annulus"){g=!0,p=Math.max(3,y),w=[0,1,0];const R=u.annulusInnerRadius??1,x=u.annulusOuterRadius??2,B=R+(x-R)*.5;for(let m=0;m<p;m++){const M=m/p*ht;ne[m]=Math.cos(M)*B,oe[m]=0,le[m]=Math.sin(M)*B}}else if(f==="arc"){g=!1,p=Math.max(2,y+1),w=[0,0,1];const R=u.arcInnerRadius??0,x=u.arcOuterRadius??2,B=R>0?R+(x-R)*.5:x,m=(u.arcStartAngle??0)*Math.PI/180,M=(u.arcEndAngle??180)*Math.PI/180;for(let E=0;E<p;E++){const q=p>1?E/(p-1):0,X=m+(M-m)*q;ne[E]=Math.cos(X)*B,oe[E]=Math.sin(X)*B,le[E]=0}}else if(f==="square"){g=!0,p=Math.max(4,y),w=[0,0,1];const R=u.squareSize??2;for(let x=0;x<p;x++)Ht(x/p,R,R,"xy",P),ne[x]=P[0],oe[x]=P[1],le[x]=P[2]}else if(f==="rectangle"){g=!0,p=Math.max(4,y),w=[0,0,1];const R=(u.rectangleWidth??2)*.5,x=(u.rectangleHeight??2)*.5;for(let B=0;B<p;B++)Ht(B/p,R,x,"xy",P),ne[B]=P[0],oe[B]=P[1],le[B]=P[2]}else if(f==="plain"){g=!0,p=Math.max(4,y),w=[0,1,0];const R=(u.planeWidth??2)*.5,x=(u.planeDepth??2)*.5;for(let B=0;B<p;B++)Ht(B/p,R,x,"xz",P),ne[B]=P[0],oe[B]=P[1],le[B]=P[2]}else if(f==="line"){g=!1,p=Math.max(2,y+1),w=[0,0,1];const R=u.lineLength??4;for(let x=0;x<p;x++){const B=p>1?x/(p-1):0;ne[x]=0,oe[x]=(B-.5)*R,le[x]=0}}else if(f==="polygon"){g=!0,p=Math.max(3,y),w=[0,0,1];const R=Math.max(3,Math.floor(u.polygonSides??6)),x=u.polygonRadius??2;for(let B=0;B<p;B++){const m=B/p*R,M=Math.floor(m),E=m-M,q=M/R*ht,X=(M+1)/R*ht,O=Math.cos(q)*x,U=Math.sin(q)*x,be=Math.cos(X)*x,Se=Math.sin(X)*x;ne[B]=O+(be-O)*E,oe[B]=U+(Se-U)*E,le[B]=0}}else p=0;return{count:p,closed:g,planeNormal:w}}function Us(u,f,y){if(!y.shapeStrokeEnabled||y.hidden)return u;const{count:p,closed:g,planeNormal:w}=Cs(y);if(p<2)return u;const P=Ts(y),R=Math.max(1e-4,y.shapeStrokeWidth??.08),x=Math.max(0,y.opacity??1);if(x<=0)return u;As(w[0],w[1],w[2],P,f,Ae);let B=Math.hypot(Ae[0],Ae[1],Ae[2])||1;const m=Ae[0]/B,M=Ae[1]/B,E=Ae[2]/B;for(let I=0;I<p;I++)Es(ne[I],oe[I],le[I],P,f,y,Ae),ne[I]=Ae[0],oe[I]=Ae[1],le[I]=Ae[2];const q=y.shapeStrokeShape??"straight";if(q!=="straight"){const I=y.shapeStrokeAmplitude??.08,K=y.shapeStrokeFrequency??10,Ie=y.shapeStrokeSpeed??0;for(let W=0;W<p;W++){const fe=W===0?g?p-1:0:W-1,ee=W===p-1?g?0:p-1:W+1,me=ne[ee]-ne[fe],$=oe[ee]-oe[fe],Q=le[ee]-le[fe],J=M*Q-E*$,te=E*me-m*Q,ce=m*$-M*me,ye=Math.hypot(J,te,ce)||1,ve=J/ye,ue=te/ye,He=ce/ye,Me=g?W/p:W/Math.max(1,p-1),ge=ht*K*Me+Ie*Ve;let pe=0,he=0;q==="zigzag"?pe=I*Math.sign(Math.sin(ge)||1):q==="sine"?pe=I*Math.sin(ge):q==="spiral"&&(pe=I*Math.sin(ge),he=I*Math.cos(ge)),ne[W]+=ve*pe+m*he,oe[W]+=ue*pe+M*he,le[W]+=He*pe+E*he}}const X=g?p:p-1,O=y.bloomIntensity||1,U=y.startColor??y.particleColor??[1,1,1],be=y.endColor??U,Se=y.particleColor??U,Oe=y.randomColorEnabled&&Array.isArray(y.randomColors)&&y.randomColors.length>0?y.randomColors[0]:null,xe=R*.5,_t=Math.max(R*4,1e-4),je=(y.shapeStrokeSpeed??0)*Ve;let it=0;for(let I=0;I<X;I++){const K=g?(I+1)%p:I+1;it+=Math.hypot(ne[K]-ne[I],oe[K]-oe[I],le[K]-le[I])}const ti=g?Math.max(1,Math.round(it/_t)):Math.max(it/_t,1e-6),Mt=it>1e-6?ti/it:0;let qe=0,wt=!1,ut=0,Ue=0,dt=0;for(let I=0;I<p;I++){const K=I===0?g?p-1:0:I-1,Ie=I===p-1?g?0:p-1:I+1;let W=ne[Ie]-ne[K],fe=oe[Ie]-oe[K],ee=le[Ie]-le[K];const me=Math.hypot(W,fe,ee)||1;W/=me,fe/=me,ee/=me;let $=M*ee-E*fe,Q=E*W-m*ee,J=m*fe-M*W,te=Math.hypot($,Q,J);if(te<1e-5){const ce=V.right[0],ye=V.right[1],ve=V.right[2],ue=ce*W+ye*fe+ve*ee;$=ce-ue*W,Q=ye-ue*fe,J=ve-ue*ee,te=Math.hypot($,Q,J)}if(te<1e-5){const ce=V.up[0],ye=V.up[1],ve=V.up[2],ue=ce*W+ye*fe+ve*ee;$=ce-ue*W,Q=ye-ue*fe,J=ve-ue*ee,te=Math.hypot($,Q,J)||1}$/=te,Q/=te,J/=te,wt&&ut*$+Ue*Q+dt*J<0&&($=-$,Q=-Q,J=-J),Yt[I]=$,jt[I]=Q,qt[I]=J,ut=$,Ue=Q,dt=J,wt=!0}for(let I=0;I<X&&!(u+54>Ce.length);I++){const K=g?(I+1)%p:I+1,Ie=ne[I],W=oe[I],fe=le[I],ee=ne[K],me=oe[K],$=le[K];let Q=ee-Ie,J=me-W,te=$-fe;const ce=Math.hypot(Q,J,te)||1;Q/=ce,J/=ce,te/=ce;const ye=g?I/p:I/Math.max(1,p-1),ve=g?K/p:K/Math.max(1,p-1),ue=qe*Mt+je,He=(qe+ce)*Mt+je;let Me,ge,pe,he,we,Re;Oe?(Me=he=Oe[0],ge=we=Oe[1],pe=Re=Oe[2]):y.colorTransitionEnabled?(Me=U[0]+(be[0]-U[0])*ye,ge=U[1]+(be[1]-U[1])*ye,pe=U[2]+(be[2]-U[2])*ye,he=U[0]+(be[0]-U[0])*ve,we=U[1]+(be[1]-U[1])*ve,Re=U[2]+(be[2]-U[2])*ve):(Me=he=Se[0],ge=we=Se[1],pe=Re=Se[2]),Me=Math.min(1,Me*O),ge=Math.min(1,ge*O),pe=Math.min(1,pe*O),he=Math.min(1,he*O),we=Math.min(1,we*O),Re=Math.min(1,Re*O);const Rt=Yt[I],bt=jt[I],Le=qt[I],ke=Yt[K],ze=jt[K],Bt=qt[K],Ot=Ie+Rt*xe,Lt=W+bt*xe,Tt=fe+Le*xe,Be=Ie-Rt*xe,Te=W-bt*xe,Ee=fe-Le*xe,st=ee+ke*xe,rt=me+ze*xe,Et=$+Bt*xe,Ze=ee-ke*xe,We=me-ze*xe,$e=$-Bt*xe,ft=(A,k,de,N,L,Y,ie,Je,Ke)=>{Ce[u++]=A,Ce[u++]=k,Ce[u++]=de,Ce[u++]=N,Ce[u++]=L,Ce[u++]=Y,Ce[u++]=ie,Ce[u++]=Je,Ce[u++]=Ke};ft(Ot,Lt,Tt,Me,ge,pe,x,ue,0),ft(Be,Te,Ee,Me,ge,pe,x,ue,1),ft(st,rt,Et,he,we,Re,x,He,0),ft(Be,Te,Ee,Me,ge,pe,x,ue,1),ft(Ze,We,$e,he,we,Re,x,He,1),ft(st,rt,Et,he,we,Re,x,He,0),qe+=ce}return u}const Is=.41421356;function zs(){xt.clear(),nt.clear();let u=0,f=0,y=0;V.position[0],V.position[1],V.position[2];for(const{system:p,config:g}of c.particleSystems){if(g.hidden)continue;if(g.emissionTrailEnabled&&!g.glbModelEnabled){p.readbackAndProcessParticles();const P=p.particleData,R=p.particleVelocities,x=p.activeParticles;if(P&&R&&x>0){const B=g.emissionTrailMode==="particles",m=u,M=g.emissionTrailDuration??1,E=g.opacity??1,q=g.particleSize??.5,X=g.bloomIntensity||1,O=Math.max(1,Math.min(64,g.emissionTrailSegments??8)),U=g.emissionTrailShape||"straight",be=g.followSystemTranslation??!0,Se=p._simPosition,Oe=be&&Se?Se[0]:0,xe=be&&Se?Se[1]:0,_t=be&&Se?Se[2]:0,je=p._simVelocity,it=je?je[0]:0,ti=je?je[1]:0,Mt=je?je[2]:0,qe=pi(g.id),wt=!!(be&&qe&&qe.hist&&qe.hist.length>1);for(let ut=0;ut<x;ut++){const Ue=ut*8,dt=P[Ue],I=P[Ue+1],K=P[Ue+2],Ie=dt+Oe,W=I+xe,fe=K+_t;let ee=P[Ue+3],me=P[Ue+4],$=P[Ue+5];const Q=P[Ue+6],J=P[Ue+7];if(Q>=J||J<=0)continue;const te=Q/J;if(g.colorTransitionEnabled){const A=g.startColor??[1,0,0],k=g.endColor??[0,0,1];ee=A[0]+(k[0]-A[0])*te,me=A[1]+(k[1]-A[1])*te,$=A[2]+(k[2]-A[2])*te}ee=Math.min(1,ee*X),me=Math.min(1,me*X),$=Math.min(1,$*X);let ce=q;if(g.randomSize){const A=Math.sin(J*54321.67)*43758.5453%1,k=A<0?A+1:A;ce=(g.minSize??.1)+((g.maxSize??.5)-(g.minSize??.1))*k}if(g.fadeSizeEnabled){const A=Math.max(.01,Math.min(10,g.sizeLifetimeSpeed??1));ce*=1-Math.pow(te,1/A)}if(g.increaseSizeEnabled){const A=Math.max(.01,Math.min(10,g.sizeLifetimeSpeed??1));ce*=1+Math.pow(te,1/A)}if(ce<=0||te>.9)continue;const ye=Math.min((.9-te)*(1/.2),1),ve=.75*ce*Is*ye;let ue=E;if(g.fadeEnabled&&(ue*=Math.max(0,1-te)),ue*=ye,ue<.01)continue;const He=ut*4,Me=R[He],ge=R[He+1],pe=R[He+2],he=Me+it,we=ge+ti,Re=pe+Mt,Rt=Math.sqrt(he*he+we*we+Re*Re);if(Rt<.001)continue;const bt=1/Rt,Le=he*bt,ke=we*bt,ze=Re*bt,Bt=V.right[0],Ot=V.right[1],Lt=V.right[2];let Tt=Bt*Le+Ot*ke+Lt*ze,Be=Bt-Tt*Le,Te=Ot-Tt*ke,Ee=Lt-Tt*ze,st=Math.sqrt(Be*Be+Te*Te+Ee*Ee);if(st<.2){const A=V.up[0],k=V.up[1],de=V.up[2],N=A*Le+k*ke+de*ze;Be=A-N*Le,Te=k-N*ke,Ee=de-N*ze,st=Math.sqrt(Be*Be+Te*Te+Ee*Ee)||1}Be/=st,Te/=st,Ee/=st;const rt=Math.min(M,Q);if(rt<.001)continue;const Et=g.gravityEnabled&&g.gravityStrength||0,Ze=qs,We=Hs,$e=Zs;if(g.orientToDirection&&g.burstMode&&wt){const A=p._emitSimRotY||0,k=Ws,de=$s,N=Js;for(let L=0;L<=O;L++){const Y=hi(qe,Ve-L/O*rt,Ti);k[L]=Y[0],de[L]=Y[1],N[L]=Y[2]}for(let L=0;L<=O;L++){const Y=L>0?L-1:0,ie=L<O?L+1:O;let Je=k[Y]-k[ie],Ke=N[Y]-N[ie];const at=(Math.hypot(Je,Ke)>1e-5?Math.atan2(Je,Ke):Math.atan2(it,Mt))-A,De=Math.cos(at),Ge=Math.sin(at),et=L/O*rt,ii=-.5*Et*et*et;Ze[L]=De*dt+Ge*K+k[L],We[L]=I+ii+de[L],$e[L]=-Ge*dt+De*K+N[L]}}else for(let A=0;A<=O;A++){const k=A/O*rt,de=-.5*Et*k*k;if(wt){const N=hi(qe,Ve-k,Ti);Ze[A]=dt-Me*k+N[0],We[A]=I-ge*k+de+N[1],$e[A]=K-pe*k+N[2]}else Ze[A]=Ie-he*k,We[A]=W-we*k+de,$e[A]=fe-Re*k}if(U!=="straight"){const A=g.emissionTrailShapeAmplitude??.1,k=g.emissionTrailShapeFrequency??4,de=g.emissionTrailShapeSpeed??0;let N=-ze,L=0,Y=Le,ie=Math.sqrt(N*N+Y*Y);ie<1e-6&&(N=0,L=ze,Y=-ke,ie=Math.sqrt(N*N+L*L+Y*Y)||1),N/=ie,L/=ie,Y/=ie;const Je=ke*Y-ze*L,Ke=ze*N-Le*Y,Qe=Le*L-ke*N;for(let Pe=1;Pe<=O;Pe++){const at=Pe/O*rt,De=2*Math.PI*k*(Ve-at)+de*Ve;let Ge=0,et=0;U==="zigzag"?Ge=A*Math.sign(Math.sin(De)):U==="sine"?Ge=A*Math.sin(De):U==="spiral"&&(Ge=A*Math.sin(De),et=A*Math.cos(De)),Ze[Pe]+=N*Ge+Je*et,We[Pe]+=L*Ge+Ke*et,$e[Pe]+=Y*Ge+Qe*et}}if(B)for(let A=1;A<=O&&u<F;A++){const k=A/O,de=Ze[A]-Oe,N=We[A]-xe,L=$e[A]-_t,Y=u*8,ie=u*4;H[Y]=de,H[Y+1]=N,H[Y+2]=L,H[Y+3]=ee,H[Y+4]=me,H[Y+5]=$,H[Y+6]=Q+(J-Q)*k,H[Y+7]=J,se[ie]=0,se[ie+1]=0,se[ie+2]=0,se[ie+3]=0,ae[ie]=de,ae[ie+1]=N,ae[ie+2]=L,ae[ie+3]=0,u++}else for(let A=0;A<O&&!(f+42>Ye.length);A++){const k=A/O,de=(A+1)/O,N=Ze[A],L=We[A],Y=$e[A],ie=Ze[A+1],Je=We[A+1],Ke=$e[A+1],Qe=ve*(1-k),Pe=ve*(1-de),at=ue*(1-k)*(1-k),De=ue*(1-de)*(1-de),Ge=N+Be*Qe,et=L+Te*Qe,ii=Y+Ee*Qe,Gi=N-Be*Qe,Fi=L-Te*Qe,Vi=Y-Ee*Qe,Oi=ie+Be*Pe,Li=Je+Te*Pe,ki=Ke+Ee*Pe,lr=ie-Be*Pe,cr=Je-Te*Pe,ur=Ke-Ee*Pe,St=(dr,fr,pr,hr)=>{Ye[f++]=dr,Ye[f++]=fr,Ye[f++]=pr,Ye[f++]=ee,Ye[f++]=me,Ye[f++]=$,Ye[f++]=hr};St(Ge,et,ii,at),St(Gi,Fi,Vi,at),St(Oi,Li,ki,De),St(Gi,Fi,Vi,at),St(lr,cr,ur,De),St(Oi,Li,ki,De)}}B&&u>m&&xt.set(g.id,{first:m,count:u-m})}}const w=y;y=Us(y,p,g),y>w&&nt.set(g.id,{first:w/9,count:(y-w)/9})}u>0&&(r.queue.writeBuffer(re,0,H,0,u*8),r.queue.writeBuffer(j,0,se,0,u*4),r.queue.writeBuffer(tt,0,ae,0,u*4)),vt=f/7,vt>0&&r.queue.writeBuffer(Zt,0,Ye,0,f),Mi=y/9,Mi>0&&r.queue.writeBuffer(Wt,0,Ce,0,y)}const mi=()=>{const[u,f]=fs(n.width,n.height);r.queue.writeBuffer(z,0,new Float32Array([1,0,u,f,0,0,0,0])),r.queue.writeBuffer(D,0,new Float32Array([0,1,u,f,0,0,0,0]))};mi();const yi=new Float32Array(16).fill(0);yi[0]=1,r.queue.writeBuffer(_,0,yi);const Fe=gs(r),Ne=ms(r),{particlePipeline:Ds,particleAdditivePipeline:Gs,particleDepthWritePipeline:Fs,blurPipeline:It,compositePipeline:Vs,directRenderPipeline:gi,finalCompositePipeline:Os,glbMeshPipeline:Ls}=ys(r,l,Ne),bi=r.createShaderModule({code:`
1187
1205
  struct U { mvp: mat4x4<f32> };
1188
1206
  @group(0) @binding(0) var<uniform> u: U;
1189
1207
  struct VIn { @location(0) pos: vec3<f32>, @location(1) col: vec4<f32> };
1190
1208
  struct VOut { @builtin(position) pos: vec4<f32>, @location(0) col: vec4<f32> };
1191
1209
  @vertex fn vs(v: VIn) -> VOut { var o: VOut; o.pos = u.mvp * vec4<f32>(v.pos, 1.0); o.col = v.col; return o; }
1192
1210
  @fragment fn fs(i: VOut) -> @location(0) vec4<f32> { return i.col; }
1193
- `}),Si=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),Os=r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:[Si]}),vertex:{module:bi,entryPoint:"vs",buffers:[{arrayStride:28,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x4"}]}]},fragment:{module:bi,entryPoint:"fs",targets:[{format:"rgba16float",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"}}}]},primitive:{topology:"triangle-list"},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"less-equal"}}),xi=512*64*6,Ye=new Float32Array(xi*7),Zt=r.createBuffer({size:xi*7*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,label:"ribbonBuffer"}),Ls=r.createBindGroup({layout:Si,entries:[{binding:0,resource:{buffer:v}}]});let vt=0;const vi=r.createShaderModule({code:`
1211
+ `}),Si=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),ks=r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:[Si]}),vertex:{module:bi,entryPoint:"vs",buffers:[{arrayStride:28,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x4"}]}]},fragment:{module:bi,entryPoint:"fs",targets:[{format:"rgba16float",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"}}}]},primitive:{topology:"triangle-list"},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"less-equal"}}),xi=512*64*6,Ye=new Float32Array(xi*7),Zt=r.createBuffer({size:xi*7*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,label:"ribbonBuffer"}),Xs=r.createBindGroup({layout:Si,entries:[{binding:0,resource:{buffer:v}}]});let vt=0;const vi=r.createShaderModule({code:`
1194
1212
  struct Uniforms {
1195
1213
  transform: mat4x4<f32>,
1196
1214
  cameraPosition: vec3<f32>,
@@ -1268,8 +1286,20 @@ return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles,
1268
1286
  @location(3) noiseOffset: vec2<f32>,
1269
1287
  };
1270
1288
 
1289
+ // Hachage SANS TRANSCENDANTAL (Dave Hoskins) — jumeau de celui de modules/shaders.js.
1290
+ //
1291
+ // ⚠️ IL Y EN A DEUX EXEMPLAIRES DANS CETTE BIBLIOTHÈQUE, et je ne m'en suis aperçu qu'en cherchant
1292
+ // pourquoi le premier correctif ne changeait rien au bundle : ce shader-ci est INLINE dans
1293
+ // l'overlay, l'autre vit dans modules/shaders.js. Corriger un seul laisse le defaut entier sur le
1294
+ // chemin qui sert reellement au jeu. Toute modification de l'un doit etre portee a l'autre.
1295
+ //
1296
+ // Le fract(sin(dot(...))) remplace coutait HUIT sin par pixel couvert (2 valueNoise x 4 hash21).
1297
+ // Mesure sur la map du proprietaire : ~19 ecrans pleins de recouvrement, soit ~150 sin par pixel
1298
+ // d'ecran et par image. Il rapportait que ca ramait, et eteindre le bruit supprimait le probleme.
1271
1299
  fn hash21(p: vec2<f32>) -> f32 {
1272
- return fract(sin(dot(p, vec2<f32>(127.1, 311.7))) * 43758.5453);
1300
+ var p3 = fract(vec3<f32>(p.x, p.y, p.x) * 0.1031);
1301
+ p3 = p3 + dot(p3, vec3<f32>(p3.y, p3.z, p3.x) + 33.33);
1302
+ return fract((p3.x + p3.y) * p3.z);
1273
1303
  }
1274
1304
 
1275
1305
  fn valueNoise(p: vec2<f32>) -> f32 {
@@ -1319,4 +1349,4 @@ return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles,
1319
1349
  }
1320
1350
  return vec4<f32>(i.col, i.alpha);
1321
1351
  }
1322
- `}),Pi=u=>r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:[Ne.particleBindGroupLayout]}),vertex:{module:vi,entryPoint:"vs",buffers:[{arrayStride:36,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x4"},{shaderLocation:2,offset:28,format:"float32x2"}]}]},fragment:{module:vi,entryPoint:"fs",targets:[{format:"rgba16float",blend:u}]},primitive:{topology:"triangle-list"},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"less-equal"}}),ks=Pi({color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),Xs=Pi({color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),_i=256*256*6,Ce=new Float32Array(_i*9),Wt=r.createBuffer({size:_i*9*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,label:"shapeStrokeBuffer"});let Mi=0,{sceneTexture:at,bloomTexA:ot,bloomTexB:lt}=li(r,c,a.width,a.height),zt=ci(r,a.width,a.height),mt,wi,Gt,Pt;const Bi=()=>{const u=f=>f.createView();mt=u(at),wi=u(ot),Gt=u(lt),Pt=u(zt)};Bi();const $t={uniformBuffer:v,appearanceUniformBuffer:E,horizontalBlurUniformBuffer:I,verticalBlurUniformBuffer:z,bloomIntensityBuffer:_};let Ft=Xt(r,De,$t,{sceneTexture:at,bloomTexA:ot,bloomTexB:lt});const D={mvp:new Float32Array(16),position:new Float32Array([0,0,10]),right:new Float32Array([1,0,0]),up:new Float32Array([0,1,0]),hasCamera:!1};let Ve=0,Ns=0;const yt=new Float32Array(5),Ri=new Float32Array(16),Ys=new Array(65),js=new Array(65),qs=new Array(65),Hs=new Array(65),Zs=new Array(65),Ws=new Array(65),Ti=[0,0,0],gt={key:null,ms:!1,bindGroup:null};let Ai=!1,Jt=!0,Dt=!1,Vt=null,Kt=a.width,Qt=a.height;function Ei(){const u=[at,ot,lt,zt],f=li(r,c,a.width,a.height);at=f.sceneTexture,ot=f.bloomTexA,lt=f.bloomTexB,zt=ci(r,a.width,a.height),Bi(),mi(),p.clear(),b.resizeTextures(),Ft=Xt(r,De,$t,{sceneTexture:at,bloomTexA:ot,bloomTexB:lt});let m=!1;const g=()=>{if(!m){m=!0,requestAnimationFrame(g);return}u.forEach(y=>y.destroy())};requestAnimationFrame(g)}function $s(u,f,m){D.mvp.set(bs(u,f)),f&&f.length>=10&&(D.right[0]=f[0],D.right[1]=f[4],D.right[2]=f[8],D.up[0]=f[1],D.up[1]=f[5],D.up[2]=f[9]),m&&(D.position[0]=m.x??m[0],D.position[1]=m.y??m[1],D.position[2]=m.z??m[2]),D.hasCamera=!0}function Js(u,f){D.mvp.set(u),f&&(D.position[0]=f.x??f[0],D.position[1]=f.y??f[1],D.position[2]=f.z??f[2]),D.hasCamera=!0}async function ei(u){if(Dt){Vt=u;return}Dt=!0;try{for(const f in T)delete T[f];p.clear(),b.resizeTextures(),Ft=Xt(r,De,$t,{sceneTexture:at,bloomTexA:ot,bloomTexB:lt}),await l.replaceSystems({systems:[],activeSystemIndex:0});for(const f of u)await l.addSystems(f.preset,f.position||[0,0,0]);for(const{config:f}of l.particleSystems)T[f.id]||(T[f.id]=G());Jt=!0,l.respawnAllSystems()}finally{if(Dt=!1,Vt){const f=Vt;Vt=null,ei(f)}}}async function Ks(u,f=[0,0,0]){return ei([{preset:u,position:f}])}function Qs(u){if(Ai||Dt||!l.ready||u<=0||l.particleSystems.length===0)return;const f=l.clock;if(f&&(f.loop=l.loop??i,f.duration=l.getTotalDuration(),u=f.tick(u)),u>.1&&(u=.1),u<=0)return;if((a.width!==Kt||a.height!==Qt)&&(Kt=a.width,Qt=a.height,Ei()),Ve+=u,_e.length){for(const h of _e){if(h.getPosition){const w=h.getPosition();w?(h.pos||(h.pos=h._posBuf),Array.isArray(w)?(h.pos[0]=w[0],h.pos[1]=w[1],h.pos[2]=w[2]):(h.pos[0]=w.x,h.pos[1]=w.y,h.pos[2]=w.z)):h.pos=null}h.vel=h._velBuf,h.pos&&h.prevPos&&h.wasActive&&u>0?(h.vel[0]=(h.pos[0]-h.prevPos[0])/u,h.vel[1]=(h.pos[1]-h.prevPos[1])/u,h.vel[2]=(h.pos[2]-h.prevPos[2])/u):(h.vel[0]=0,h.vel[1]=0,h.vel[2]=0),h.justResumed=!!h.pos&&!h.wasActive,h.justResumed&&(h.hist.length=0)}for(const{system:h,config:w}of l.particleSystems){const C=pi(w.id);if(!(!C||C.historyOnly)&&(w.hidden=!C.pos,C.pos)){let H=null;if(C.orientToDirection&&C.vel){const O=C.vel[0],L=C.vel[2];Math.hypot(O,L)>1e-4&&(H=[0,0,Math.atan2(O,L)])}h.setSimulationTransform({position:C.pos,velocity:C.vel,rotation:H}),h.updateAppearanceUniform(),(C.justResumed||h.activeParticles===0)&&h.spawnParticles()}}for(const h of _e)h.pos?ws(h,Ve):h.hist.length=0,h.pos?(h._prevPosBuf[0]=h.pos[0],h._prevPosBuf[1]=h.pos[1],h._prevPosBuf[2]=h.pos[2],h.prevPos=h._prevPosBuf):h.prevPos=null,h.wasActive=!!h.pos;if(globalThis.__HZFX_DEBUG&&(Ns++&63)===0){const h=l.particleSystems.reduce((O,L)=>O+(L.system.activeParticles|0),0),w=_e.find(O=>O.pos),C=w?Math.hypot(D.position[0]-w.pos[0],D.position[1]-w.pos[1],D.position[2]-w.pos[2]).toFixed(1):"-",H=_e.map(O=>`{ids:[${[...O.ids]}],pos:${O.pos?"1":"0"},hist:${O.hist.length}}`).join(",");console.info(`[HZFX] movingGroups(${_e.length})=[${H}] activeParticles=${h} systems=${l.particleSystems.length} ribbonVerts=${vt} camDist=${C} t=${Ve.toFixed(1)}`)}}if(l.updateAllSystems(u),f?f.loop:l.loop??i){const h=l.particleSystems.length>0&&l.particleSystems.every(({system:w})=>w.activeParticles===0&&!w.emitting);(f&&f.justLooped||h&&Jt)&&l.respawnAllSystems(),Jt=!h}for(const{system:h,config:w}of l.particleSystems)w.glbModelEnabled&&h.glbAnimator&&(h.glbAnimator.update(u),h.updateAnimatedGLBBuffer());r.queue.writeBuffer(v,0,D.mvp),yt[0]=D.position[0],yt[1]=D.position[1],yt[2]=D.position[2],yt[3]=a.height/Math.max(1,a.width),yt[4]=Ve,r.queue.writeBuffer(v,64,yt),Us();const g=l.particleSystems.some(({system:h,config:w})=>w.bloomEnabled&&!w.hidden&&(h.activeParticles>0||Xe.has(w.id))),y=r.createCommandEncoder();let R=!1;if(e)try{const h=e();if(h){let w=null,C=null,H=!1;if(h instanceof GPUTexture?h.width===a.width&&h.height===a.height&&(w=h,C=()=>h.createView({aspect:"depth-only"}),H=h.sampleCount>1):h.view&&(w=h.view,C=()=>h.view,H=!!h.multisampled),w){const{pipeline:O,layout:L}=S(H);(gt.key!==w||gt.ms!==H)&&(gt.key=w,gt.ms=H,gt.bindGroup=r.createBindGroup({layout:L,entries:[{binding:0,resource:C()}]}));const N=y.beginRenderPass({colorAttachments:[],depthStencilAttachment:{view:Pt,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});N.setPipeline(O),N.setBindGroup(0,gt.bindGroup),N.draw(3),N.end(),R=!0}}}catch{}const P=y.beginRenderPass({colorAttachments:[{view:mt,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}],depthStencilAttachment:R?{view:Pt,depthLoadOp:"load",depthStoreOp:"store"}:{view:Pt,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});for(const{system:h,config:w}of l.particleSystems)w.bloomEnabled||w.hidden||h.activeParticles===0&&!Xe.has(w.id)||(Ui(P,h,w),Ii(P,h,w));if(vt>0&&(P.setPipeline(Os),P.setBindGroup(0,Ls),P.setVertexBuffer(0,Zt),P.draw(vt)),P.end(),g){const h={colorAttachments:[{view:wi,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]},w={colorAttachments:[{view:Gt,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]};for(const{system:C,config:H}of l.particleSystems){if(!H.bloomEnabled||H.hidden||C.activeParticles===0&&!Xe.has(H.id))continue;const O=C.config.id,L=b.getBloomSourceTexture(O,a.width,a.height),N=y.beginRenderPass({colorAttachments:[{view:L.createView(),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}],depthStencilAttachment:{view:Pt,depthClearValue:1,depthLoadOp:"load",depthStoreOp:"store"}});Ui(N,C,H),Ii(N,C,H),N.end(),Ri[0]=H.bloomIntensity,r.queue.writeBuffer(_,0,Ri),p.systemBloomHorizontalBindGroups[O]||(p.systemBloomHorizontalBindGroups[O]=r.createBindGroup({layout:Ne.bloomBindGroupLayout,entries:[{binding:0,resource:De},{binding:1,resource:L.createView()},{binding:2,resource:{buffer:I}}]}));let V=y.beginRenderPass(h);V.setPipeline(It),V.setBindGroup(0,p.systemBloomHorizontalBindGroups[O]),V.draw(3),V.end(),V=y.beginRenderPass(w),V.setPipeline(It),V.setBindGroup(0,Ft.verticalBlurBindGroup),V.draw(3),V.end(),p.secondHorizontalBindGroups[O]||(p.secondHorizontalBindGroups[O]=r.createBindGroup({layout:Ne.bloomBindGroupLayout,entries:[{binding:0,resource:De},{binding:1,resource:Gt},{binding:2,resource:{buffer:I}}]})),V=y.beginRenderPass(h),V.setPipeline(It),V.setBindGroup(0,p.secondHorizontalBindGroups[O]),V.draw(3),V.end(),V=y.beginRenderPass(w),V.setPipeline(It),V.setBindGroup(0,Ft.verticalBlurBindGroup),V.draw(3),V.end();const xe=b.getBloomCompositeTexture(O,a.width,a.height);V=y.beginRenderPass({colorAttachments:[{view:xe.createView(),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]}),V.setPipeline(Fs),p.systemBloomCompositeBindGroups[O]||(p.systemBloomCompositeBindGroups[O]=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:De},{binding:1,resource:L.createView()},{binding:2,resource:Gt},{binding:3,resource:{buffer:C.bloomIntensityBuffer}}]})),V.setBindGroup(0,p.systemBloomCompositeBindGroups[O]),V.draw(3),V.end()}}const M=b.getCombinedTexture(a.width,a.height),x=y.beginRenderPass({colorAttachments:[{view:M.createView(),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});x.setPipeline(gi),p.combinedInitialBindGroup||(p.combinedInitialBindGroup=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:De},{binding:1,resource:mt},{binding:2,resource:mt},{binding:3,resource:{buffer:_}}]})),x.setBindGroup(0,p.combinedInitialBindGroup),x.draw(3);for(const{config:h,system:w}of l.particleSystems){if(!h.bloomEnabled||h.hidden||w.activeParticles===0&&!Xe.has(h.id))continue;const C=w.config.id;x.setPipeline(gi),p.combinedBloomCompositeBindGroups[C]||(p.combinedBloomCompositeBindGroups[C]=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:De},{binding:1,resource:b.getBloomCompositeTexture(C,a.width,a.height).createView()},{binding:2,resource:mt},{binding:3,resource:{buffer:_}}]})),x.setBindGroup(0,p.combinedBloomCompositeBindGroups[C]),x.draw(3)}x.end();const B=y.beginRenderPass({colorAttachments:[{view:n.getCurrentTexture().createView(),loadOp:o?"load":"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});B.setPipeline(Ds),p.finalBindGroup||(p.finalBindGroup=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:De},{binding:1,resource:M.createView()},{binding:2,resource:mt},{binding:3,resource:{buffer:_}}]})),B.setBindGroup(0,p.finalBindGroup),B.draw(3),B.end(),r.queue.submit([y.finish()])}function Ci(u,f){const m=u.config.id,g=!p.systemBindGroups[m]||p.textureStates[m]!==f.textureEnabled||p.textureRefs[m]!==u.particleTexture;return p.textureStates[m]=f.textureEnabled,p.textureRefs[m]=u.particleTexture,g&&(p.systemBindGroups[m]=r.createBindGroup({layout:Ne.particleBindGroupLayout,entries:[{binding:0,resource:{buffer:v}},{binding:1,resource:{buffer:u.appearanceUniformBuffer}},{binding:2,resource:u.particleTexture.createView()},{binding:3,resource:De}]})),p.systemBindGroups[m]}function Ui(u,f,m){const g=f.config.id,y=m.glbModelEnabled&&f.glbMeshData,R=Ci(f,m),P=m.shapeDisplay!==!1;if(y)P&&(u.setPipeline(Vs),u.setBindGroup(0,R),u.setVertexBuffer(0,f.glbVertexBuffer),u.setVertexBuffer(1,f.instanceBuffer),u.setVertexBuffer(2,f.velocityBuffer),u.setIndexBuffer(f.glbIndexBuffer,f.glbIndexFormat),u.drawIndexed(f.glbIndexCount,f.activeParticles));else{u.setPipeline(m.blendMode==="additive"?zs:Is),u.setIndexBuffer(W,"uint16"),T[g]||(T[g]=G()),u.setVertexBuffer(0,T[g]),u.setBindGroup(0,R),P&&(u.setVertexBuffer(1,f.instanceBuffer),u.setVertexBuffer(2,f.velocityBuffer),u.setVertexBuffer(3,f.trailBuffer),u.drawIndexed(6,f.activeParticles));const M=xt.get(g);M&&(u.setVertexBuffer(1,ne),u.setVertexBuffer(2,q),u.setVertexBuffer(3,tt),u.drawIndexed(6,M.count,0,0,M.first)),P&&m.depthWriteEnabled&&(u.setPipeline(Gs),u.drawIndexed(6,f.activeParticles))}}function Ii(u,f,m){const g=Xe.get(m.id);!g||g.count<=0||(u.setPipeline(m.blendMode==="additive"?Xs:ks),u.setBindGroup(0,Ci(f,m)),u.setVertexBuffer(0,Wt),u.draw(g.count,1,g.first,0))}function er(){Kt=a.width,Qt=a.height,Ei()}function tr(){p.clear()}function ir(){Ai=!0,l.destroy(),[at,ot,lt,zt].forEach(u=>u==null?void 0:u.destroy()),b.resizeTextures(),[v,E,I,z,_,W,ne,q,tt,Zt,Wt].forEach(u=>u==null?void 0:u.destroy()),Object.values(T).forEach(u=>u==null?void 0:u.destroy())}async function zi(u,f){const m=await l.addSystems(u,f);for(const{config:g}of l.particleSystems)T[g.id]||(T[g.id]=G());return l.respawnAllSystems(),new Set(Array.isArray(m)?m:[])}function Gi(u){for(const f of u){const m=l.particleSystems.findIndex(g=>g.config.id===f);m>=0&&l.removeSystem(m)}}async function sr(u,f=[0,0,0]){const m=await zi(u,f);return{remove(){Gi(m)}}}async function rr(u,f={}){const m=await zi(u,[0,0,0]);globalThis.__HZFX_DEBUG&&console.info(`[HZFX] addMovingEmitter: presetSystems=${(u&&u.systems||[]).length} newIds=[${[...m]}]`);const g={ids:m,pos:null,hist:[],getPosition:f.getPosition||null,orientToDirection:!!f.orientToDirection,_posBuf:[0,0,0],_velBuf:[0,0,0],_prevPosBuf:[0,0,0]};return _e.push(g),{setPosition(y){y&&(g.pos=Array.isArray(y)?[y[0],y[1],y[2]]:[y.x,y.y,y.z])},setOrientToDirection(y){g.orientToDirection=!!y},remove(){Gi(m);const y=_e.indexOf(g);y>=0&&_e.splice(y,1)}}}function nr(u,f){const g={ids:u instanceof Set?u:new Set(u),pos:null,hist:[],getPosition:f,historyOnly:!0,_posBuf:[0,0,0],_velBuf:[0,0,0],_prevPosBuf:[0,0,0]};return _e.push(g),{remove(){const y=_e.indexOf(g);y>=0&&_e.splice(y,1)},setIds(y){g.ids=y instanceof Set?y:new Set(y)}}}return{manager:l,device:r,context:n,setCamera:$s,setCameraMVP:Js,setEmitters:ei,loadPreset:Ks,addEmitter:sr,addMovingEmitter:rr,render:Qs,resize:er,clearCaches:tr,trackHistoryGroup:nr,destroy:ir}}function $r(s){return()=>{var t,e,i,r,n,a,o,c;try{const l=s.backend;if(!l)return null;const d=s.domElement.width,S=s.domElement.height,b=(typeof s._getFrameBufferTarget=="function"?s._getFrameBufferTarget():null)||s._frameBufferTarget||null;if(s.needsFrameBufferTarget&&b){const E=l.get(b),I=((i=(e=(t=s._textures)==null?void 0:t.get)==null?void 0:e.call(t,b))==null?void 0:i.depthTexture)||b.depthTexture,z=[(r=E==null?void 0:E.depthTexture)==null?void 0:r.texture,E==null?void 0:E.depthTexture,(n=E==null?void 0:E.depthBuffer)==null?void 0:n.texture,I?(a=l.get(I))==null?void 0:a.texture:null];for(const _ of z)if(_&&typeof _.createView=="function"&&_.width===d&&_.height===S)return _;return null}const p=s.getCanvasTarget?l.get(s.getCanvasTarget()):null,v=((c=(o=p==null?void 0:p.descriptor)==null?void 0:o.depthStencilAttachment)==null?void 0:c.view)??null;return v?{view:v,multisampled:(s.currentSamples??0)>1}:null}catch{return null}}}exports.GLBAnimator=as;exports.HZClock=os;exports.Objects3DManager=Vr;exports.ParticleEmitter=$i;exports.ParticlePhysics=is;exports.ParticleScript=ai;exports.ParticleSystem=kt;exports.ParticleSystemManager=cs;exports.ParticleTextureManager=ss;exports.blurShader=Ki;exports.compositeShader=Qi;exports.createBindGroupLayouts=ps;exports.createBindGroups=Xt;exports.createBuffer=pt;exports.createCubeGeometry=ys;exports.createDepthTexture=ci;exports.createLookAtMatrix=kr;exports.createProjectionMatrix=Xr;exports.createRenderPipelines=hs;exports.createRenderTextures=li;exports.createSampler=ms;exports.createSphereGeometry=gs;exports.directRenderShader=es;exports.extractGLBTexture=oi;exports.fetchPreset=Hr;exports.glbMeshParticleShader=fs;exports.hexToRgb=Or;exports.initHzFxOverlay=Wr;exports.initWebGPU=us;exports.isHZFX=di;exports.loadScene=qr;exports.makeThreeSceneDepth=$r;exports.multiplyMatrices=bs;exports.object3dShader=ds;exports.packHZFX=_s;exports.parseGLB=ns;exports.particlePhysicsShader=ts;exports.particleShader=Ji;exports.rgbToHex=Lr;exports.saveScene=jr;exports.serializeSystemConfig=Ms;exports.unpackHZFX=fi;
1352
+ `}),Pi=u=>r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:[Ne.particleBindGroupLayout]}),vertex:{module:vi,entryPoint:"vs",buffers:[{arrayStride:36,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x4"},{shaderLocation:2,offset:28,format:"float32x2"}]}]},fragment:{module:vi,entryPoint:"fs",targets:[{format:"rgba16float",blend:u}]},primitive:{topology:"triangle-list"},depthStencil:{format:"depth24plus",depthWriteEnabled:!1,depthCompare:"less-equal"}}),Ns=Pi({color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),Ys=Pi({color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}),_i=256*256*6,Ce=new Float32Array(_i*9),Wt=r.createBuffer({size:_i*9*4,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,label:"shapeStrokeBuffer"});let Mi=0,{sceneTexture:ot,bloomTexA:lt,bloomTexB:ct}=li(r,l,n.width,n.height),zt=ci(r,n.width,n.height),mt,wi,Dt,Pt;const Ri=()=>{const u=f=>f.createView();mt=u(ot),wi=u(lt),Dt=u(ct),Pt=u(zt)};Ri();const $t={uniformBuffer:v,appearanceUniformBuffer:C,horizontalBlurUniformBuffer:z,verticalBlurUniformBuffer:D,bloomIntensityBuffer:_};let Gt=Xt(r,Fe,$t,{sceneTexture:ot,bloomTexA:lt,bloomTexB:ct});const V={mvp:new Float32Array(16),position:new Float32Array([0,0,10]),right:new Float32Array([1,0,0]),up:new Float32Array([0,1,0]),hasCamera:!1};let Ve=0,js=0;const yt=new Float32Array(5),Bi=new Float32Array(16),qs=new Array(65),Hs=new Array(65),Zs=new Array(65),Ws=new Array(65),$s=new Array(65),Js=new Array(65),Ti=[0,0,0],gt={key:null,ms:!1,bindGroup:null};let Ei=!1,Jt=!0,Ft=!1,Vt=null,Kt=n.width,Qt=n.height;function Ai(){const u=[ot,lt,ct,zt],f=li(r,l,n.width,n.height);ot=f.sceneTexture,lt=f.bloomTexA,ct=f.bloomTexB,zt=ci(r,n.width,n.height),Ri(),mi(),h.clear(),b.resizeTextures(),Gt=Xt(r,Fe,$t,{sceneTexture:ot,bloomTexA:lt,bloomTexB:ct});let y=!1;const p=()=>{if(!y){y=!0,requestAnimationFrame(p);return}u.forEach(g=>g.destroy())};requestAnimationFrame(p)}function Ks(u,f,y){V.mvp.set(xs(u,f)),f&&f.length>=10&&(V.right[0]=f[0],V.right[1]=f[4],V.right[2]=f[8],V.up[0]=f[1],V.up[1]=f[5],V.up[2]=f[9]),y&&(V.position[0]=y.x??y[0],V.position[1]=y.y??y[1],V.position[2]=y.z??y[2]),V.hasCamera=!0}function Qs(u,f){V.mvp.set(u),f&&(V.position[0]=f.x??f[0],V.position[1]=f.y??f[1],V.position[2]=f.z??f[2]),V.hasCamera=!0}async function ei(u){if(Ft){Vt=u;return}Ft=!0;try{for(const f in T)delete T[f];h.clear(),b.resizeTextures(),Gt=Xt(r,Fe,$t,{sceneTexture:ot,bloomTexA:lt,bloomTexB:ct}),await c.replaceSystems({systems:[],activeSystemIndex:0});for(const f of u)await c.addSystems(f.preset,f.position||[0,0,0]);for(const{config:f}of c.particleSystems)T[f.id]||(T[f.id]=G());Jt=!0,c.respawnAllSystems()}finally{if(Ft=!1,Vt){const f=Vt;Vt=null,ei(f)}}}async function er(u,f=[0,0,0]){return ei([{preset:u,position:f}])}function tr(u){if(Ei||Ft||!c.ready||u<=0||c.particleSystems.length===0)return;const f=c.clock;if(f&&(f.loop=c.loop??i,f.duration=c.getTotalDuration(),u=f.tick(u)),u>.1&&(u=.1),u<=0)return;if((n.width!==Kt||n.height!==Qt)&&(Kt=n.width,Qt=n.height,Ai()),Ve+=u,_e.length){for(const m of _e){if(m.getPosition){const M=m.getPosition();M?(m.pos||(m.pos=m._posBuf),Array.isArray(M)?(m.pos[0]=M[0],m.pos[1]=M[1],m.pos[2]=M[2]):(m.pos[0]=M.x,m.pos[1]=M.y,m.pos[2]=M.z)):m.pos=null}m.vel=m._velBuf,m.pos&&m.prevPos&&m.wasActive&&u>0?(m.vel[0]=(m.pos[0]-m.prevPos[0])/u,m.vel[1]=(m.pos[1]-m.prevPos[1])/u,m.vel[2]=(m.pos[2]-m.prevPos[2])/u):(m.vel[0]=0,m.vel[1]=0,m.vel[2]=0),m.justResumed=!!m.pos&&!m.wasActive,m.justResumed&&(m.hist.length=0)}for(const{system:m,config:M}of c.particleSystems){const E=pi(M.id);if(!(!E||E.historyOnly)&&(M.hidden=!E.pos,E.pos)){let q=null;if(E.orientToDirection&&E.vel){const X=E.vel[0],O=E.vel[2];Math.hypot(X,O)>1e-4&&(q=[0,0,Math.atan2(X,O)])}m.setSimulationTransform({position:E.pos,velocity:E.vel,rotation:q}),m.updateAppearanceUniform(),(E.justResumed||m.activeParticles===0)&&m.spawnParticles()}}for(const m of _e)m.pos?Bs(m,Ve):m.hist.length=0,m.pos?(m._prevPosBuf[0]=m.pos[0],m._prevPosBuf[1]=m.pos[1],m._prevPosBuf[2]=m.pos[2],m.prevPos=m._prevPosBuf):m.prevPos=null,m.wasActive=!!m.pos;if(globalThis.__HZFX_DEBUG&&(js++&63)===0){const m=c.particleSystems.reduce((X,O)=>X+(O.system.activeParticles|0),0),M=_e.find(X=>X.pos),E=M?Math.hypot(V.position[0]-M.pos[0],V.position[1]-M.pos[1],V.position[2]-M.pos[2]).toFixed(1):"-",q=_e.map(X=>`{ids:[${[...X.ids]}],pos:${X.pos?"1":"0"},hist:${X.hist.length}}`).join(",");console.info(`[HZFX] movingGroups(${_e.length})=[${q}] activeParticles=${m} systems=${c.particleSystems.length} ribbonVerts=${vt} camDist=${E} t=${Ve.toFixed(1)}`)}}if(c.updateAllSystems(u),f?f.loop:c.loop??i){const m=c.particleSystems.length>0&&c.particleSystems.every(({system:M})=>M.activeParticles===0&&!M.emitting);(f&&f.justLooped||m&&Jt)&&c.respawnAllSystems(),Jt=!m}for(const{system:m,config:M}of c.particleSystems)M.glbModelEnabled&&m.glbAnimator&&(m.glbAnimator.update(u),m.updateAnimatedGLBBuffer());r.queue.writeBuffer(v,0,V.mvp),yt[0]=V.position[0],yt[1]=V.position[1],yt[2]=V.position[2],yt[3]=n.height/Math.max(1,n.width),yt[4]=Ve,r.queue.writeBuffer(v,64,yt),zs();const p=r.createCommandEncoder();let g=!1;if(e)try{const m=e();if(m){let M=null,E=null,q=!1;if(m instanceof GPUTexture?m.width===n.width&&m.height===n.height&&(M=m,E=()=>m.createView({aspect:"depth-only"}),q=m.sampleCount>1):m.view&&(M=m.view,E=()=>m.view,q=!!m.multisampled),M){const{pipeline:X,layout:O}=S(q);(gt.key!==M||gt.ms!==q)&&(gt.key=M,gt.ms=q,gt.bindGroup=r.createBindGroup({layout:O,entries:[{binding:0,resource:E()}]}));const U=p.beginRenderPass({colorAttachments:[],depthStencilAttachment:{view:Pt,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});U.setPipeline(X),U.setBindGroup(0,gt.bindGroup),U.draw(3),U.end(),g=!0}}}catch{}const w=p.beginRenderPass({colorAttachments:[{view:mt,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}],depthStencilAttachment:g?{view:Pt,depthLoadOp:"load",depthStoreOp:"store"}:{view:Pt,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});for(const{system:m,config:M}of c.particleSystems)M.bloomEnabled||M.hidden||m.activeParticles===0&&!nt.has(M.id)||(Ui(w,m,M),Ii(w,m,M));vt>0&&(w.setPipeline(ks),w.setBindGroup(0,Xs),w.setVertexBuffer(0,Zt),w.draw(vt)),w.end();const P=new Map;for(const{system:m,config:M}of c.particleSystems){if(!M.bloomEnabled||M.hidden||m.activeParticles===0&&!nt.has(M.id))continue;const E=M.bloomColor||[1,1,1],q=`b${M.bloomIntensity??1}|${E[0]}|${E[1]}|${E[2]}`,X=P.get(q);X?X.membres.push({system:m,config:M}):P.set(q,{membres:[{system:m,config:M}],premier:m})}if(P.size>0){const m={colorAttachments:[{view:wi,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]},M={colorAttachments:[{view:Dt,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]};for(const[E,q]of P){const X=b.getBloomSourceTexture(E,n.width,n.height),O=p.beginRenderPass({colorAttachments:[{view:X.createView(),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}],depthStencilAttachment:{view:Pt,depthClearValue:1,depthLoadOp:"load",depthStoreOp:"store"}});for(const{system:Se,config:Oe}of q.membres)Ui(O,Se,Oe),Ii(O,Se,Oe);O.end(),Bi[0]=q.membres[0].config.bloomIntensity,r.queue.writeBuffer(_,0,Bi),h.systemBloomHorizontalBindGroups[E]||(h.systemBloomHorizontalBindGroups[E]=r.createBindGroup({layout:Ne.bloomBindGroupLayout,entries:[{binding:0,resource:Fe},{binding:1,resource:X.createView()},{binding:2,resource:{buffer:z}}]}));let U=p.beginRenderPass(m);U.setPipeline(It),U.setBindGroup(0,h.systemBloomHorizontalBindGroups[E]),U.draw(3),U.end(),U=p.beginRenderPass(M),U.setPipeline(It),U.setBindGroup(0,Gt.verticalBlurBindGroup),U.draw(3),U.end(),h.secondHorizontalBindGroups[E]||(h.secondHorizontalBindGroups[E]=r.createBindGroup({layout:Ne.bloomBindGroupLayout,entries:[{binding:0,resource:Fe},{binding:1,resource:Dt},{binding:2,resource:{buffer:z}}]})),U=p.beginRenderPass(m),U.setPipeline(It),U.setBindGroup(0,h.secondHorizontalBindGroups[E]),U.draw(3),U.end(),U=p.beginRenderPass(M),U.setPipeline(It),U.setBindGroup(0,Gt.verticalBlurBindGroup),U.draw(3),U.end();const be=b.getBloomCompositeTexture(E,n.width,n.height);U=p.beginRenderPass({colorAttachments:[{view:be.createView(),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]}),U.setPipeline(Vs),h.systemBloomCompositeBindGroups[E]||(h.systemBloomCompositeBindGroups[E]=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:Fe},{binding:1,resource:X.createView()},{binding:2,resource:Dt},{binding:3,resource:{buffer:q.premier.bloomIntensityBuffer}}]})),U.setBindGroup(0,h.systemBloomCompositeBindGroups[E]),U.draw(3),U.end()}}const R=b.getCombinedTexture(n.width,n.height),x=p.beginRenderPass({colorAttachments:[{view:R.createView(),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});x.setPipeline(gi),h.combinedInitialBindGroup||(h.combinedInitialBindGroup=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:Fe},{binding:1,resource:mt},{binding:2,resource:mt},{binding:3,resource:{buffer:_}}]})),x.setBindGroup(0,h.combinedInitialBindGroup),x.draw(3);for(const m of P.keys())x.setPipeline(gi),h.combinedBloomCompositeBindGroups[m]||(h.combinedBloomCompositeBindGroups[m]=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:Fe},{binding:1,resource:b.getBloomCompositeTexture(m,n.width,n.height).createView()},{binding:2,resource:mt},{binding:3,resource:{buffer:_}}]})),x.setBindGroup(0,h.combinedBloomCompositeBindGroups[m]),x.draw(3);x.end();const B=p.beginRenderPass({colorAttachments:[{view:a.getCurrentTexture().createView(),loadOp:o?"load":"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});B.setPipeline(Os),h.finalBindGroup||(h.finalBindGroup=r.createBindGroup({layout:Ne.compositeBindGroupLayout,entries:[{binding:0,resource:Fe},{binding:1,resource:R.createView()},{binding:2,resource:mt},{binding:3,resource:{buffer:_}}]})),B.setBindGroup(0,h.finalBindGroup),B.draw(3),B.end(),r.queue.submit([p.finish()])}function Ci(u,f){const y=u.config.id,p=!h.systemBindGroups[y]||h.textureStates[y]!==f.textureEnabled||h.textureRefs[y]!==u.particleTexture;return h.textureStates[y]=f.textureEnabled,h.textureRefs[y]=u.particleTexture,p&&(h.systemBindGroups[y]=r.createBindGroup({layout:Ne.particleBindGroupLayout,entries:[{binding:0,resource:{buffer:v}},{binding:1,resource:{buffer:u.appearanceUniformBuffer}},{binding:2,resource:u.particleTexture.createView()},{binding:3,resource:Fe}]})),h.systemBindGroups[y]}function Ui(u,f,y){const p=f.config.id,g=y.glbModelEnabled&&f.glbMeshData,w=Ci(f,y),P=y.shapeDisplay!==!1;if(g)P&&(u.setPipeline(Ls),u.setBindGroup(0,w),u.setVertexBuffer(0,f.glbVertexBuffer),u.setVertexBuffer(1,f.instanceBuffer),u.setVertexBuffer(2,f.velocityBuffer),u.setIndexBuffer(f.glbIndexBuffer,f.glbIndexFormat),u.drawIndexed(f.glbIndexCount,f.activeParticles));else{u.setPipeline(y.blendMode==="additive"?Gs:Ds),u.setIndexBuffer(Z,"uint16"),T[p]||(T[p]=G()),u.setVertexBuffer(0,T[p]),u.setBindGroup(0,w),P&&(u.setVertexBuffer(1,f.instanceBuffer),u.setVertexBuffer(2,f.velocityBuffer),u.setVertexBuffer(3,f.trailBuffer),u.drawIndexed(6,f.activeParticles));const R=xt.get(p);R&&(u.setVertexBuffer(1,re),u.setVertexBuffer(2,j),u.setVertexBuffer(3,tt),u.drawIndexed(6,R.count,0,0,R.first)),P&&y.depthWriteEnabled&&(u.setPipeline(Fs),u.drawIndexed(6,f.activeParticles))}}function Ii(u,f,y){const p=nt.get(y.id);!p||p.count<=0||(u.setPipeline(y.blendMode==="additive"?Ys:Ns),u.setBindGroup(0,Ci(f,y)),u.setVertexBuffer(0,Wt),u.draw(p.count,1,p.first,0))}function ir(){Kt=n.width,Qt=n.height,Ai()}function sr(){h.clear()}function rr(){Ei=!0,c.destroy(),[ot,lt,ct,zt].forEach(u=>u==null?void 0:u.destroy()),b.resizeTextures(),[v,C,z,D,_,Z,re,j,tt,Zt,Wt].forEach(u=>u==null?void 0:u.destroy()),Object.values(T).forEach(u=>u==null?void 0:u.destroy())}async function zi(u,f){const y=await c.addSystems(u,f);for(const{config:p}of c.particleSystems)T[p.id]||(T[p.id]=G());return c.respawnAllSystems(),new Set(Array.isArray(y)?y:[])}function Di(u){for(const f of u){const y=c.particleSystems.findIndex(p=>p.config.id===f);y>=0&&c.removeSystem(y)}}async function ar(u,f=[0,0,0]){const y=await zi(u,f);return{remove(){Di(y)}}}async function nr(u,f={}){const y=await zi(u,[0,0,0]);globalThis.__HZFX_DEBUG&&console.info(`[HZFX] addMovingEmitter: presetSystems=${(u&&u.systems||[]).length} newIds=[${[...y]}]`);const p={ids:y,pos:null,hist:[],getPosition:f.getPosition||null,orientToDirection:!!f.orientToDirection,_posBuf:[0,0,0],_velBuf:[0,0,0],_prevPosBuf:[0,0,0]};return _e.push(p),{setPosition(g){g&&(p.pos=Array.isArray(g)?[g[0],g[1],g[2]]:[g.x,g.y,g.z])},setOrientToDirection(g){p.orientToDirection=!!g},remove(){Di(y);const g=_e.indexOf(p);g>=0&&_e.splice(g,1)}}}function or(u,f){const p={ids:u instanceof Set?u:new Set(u),pos:null,hist:[],getPosition:f,historyOnly:!0,_posBuf:[0,0,0],_velBuf:[0,0,0],_prevPosBuf:[0,0,0]};return _e.push(p),{remove(){const g=_e.indexOf(p);g>=0&&_e.splice(g,1)},setIds(g){p.ids=g instanceof Set?g:new Set(g)}}}return{manager:c,device:r,context:a,setCamera:Ks,setCameraMVP:Qs,setEmitters:ei,loadPreset:er,addEmitter:ar,addMovingEmitter:nr,render:tr,resize:ir,clearCaches:sr,trackHistoryGroup:or,destroy:rr}}function Kr(s){return()=>{var t,e,i,r,a,n,o,l;try{const c=s.backend;if(!c)return null;const d=s.domElement.width,S=s.domElement.height,b=(typeof s._getFrameBufferTarget=="function"?s._getFrameBufferTarget():null)||s._frameBufferTarget||null;if(s.needsFrameBufferTarget&&b){const C=c.get(b),z=((i=(e=(t=s._textures)==null?void 0:t.get)==null?void 0:e.call(t,b))==null?void 0:i.depthTexture)||b.depthTexture,D=[(r=C==null?void 0:C.depthTexture)==null?void 0:r.texture,C==null?void 0:C.depthTexture,(a=C==null?void 0:C.depthBuffer)==null?void 0:a.texture,z?(n=c.get(z))==null?void 0:n.texture:null];for(const _ of D)if(_&&typeof _.createView=="function"&&_.width===d&&_.height===S)return _;return null}const h=s.getCanvasTarget?c.get(s.getCanvasTarget()):null,v=((l=(o=h==null?void 0:h.descriptor)==null?void 0:o.depthStencilAttachment)==null?void 0:l.view)??null;return v?{view:v,multisampled:(s.currentSamples??0)>1}:null}catch{return null}}}exports.GLBAnimator=os;exports.HZClock=ls;exports.Objects3DManager=Lr;exports.ParticleEmitter=Ji;exports.ParticlePhysics=ss;exports.ParticleScript=ni;exports.ParticleSystem=kt;exports.ParticleSystemManager=us;exports.ParticleTextureManager=rs;exports.blurShader=Qi;exports.compositeShader=es;exports.createBindGroupLayouts=ms;exports.createBindGroups=Xt;exports.createBuffer=pt;exports.createCubeGeometry=bs;exports.createDepthTexture=ci;exports.createLookAtMatrix=Nr;exports.createProjectionMatrix=Yr;exports.createRenderPipelines=ys;exports.createRenderTextures=li;exports.createSampler=gs;exports.createSphereGeometry=Ss;exports.directRenderShader=ts;exports.extractGLBTexture=oi;exports.fetchPreset=Wr;exports.glbMeshParticleShader=hs;exports.hexToRgb=kr;exports.initHzFxOverlay=Jr;exports.initWebGPU=ds;exports.isHZFX=di;exports.loadScene=Zr;exports.makeThreeSceneDepth=Kr;exports.multiplyMatrices=xs;exports.object3dShader=ps;exports.packHZFX=ws;exports.parseGLB=ns;exports.particlePhysicsShader=is;exports.particleShader=Ki;exports.rgbToHex=Xr;exports.saveScene=Hr;exports.serializeSystemConfig=Rs;exports.unpackHZFX=fi;