hz-particles 1.4.1 → 1.4.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.
|
@@ -874,7 +874,7 @@ return function(__deltaTime, __time, __currentFrame, __totalFrames, __particles,
|
|
|
874
874
|
var currentFrame = __currentFrame, totalFrames = __totalFrames;
|
|
875
875
|
var particles = __particles, config = __config, math = __math;
|
|
876
876
|
${Ns(t)}
|
|
877
|
-
};`,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,Ui)}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 $e){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 $e)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 Ii(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 P=t.getUint32(n,!0),T=t.getUint32(n+4,!0),E=s.slice(n+8,n+8+P);if(T===1313821514){const k=new TextDecoder("utf-8").decode(E);a=JSON.parse(k)}else T===5130562&&(o=E);n+=8+P}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 u=l.attributes.POSITION;if(u===void 0)throw new Error("Mesh primitive missing POSITION attribute");const m=Pt(a,o,u,3,5126);let p;if(l.attributes.NORMAL!==void 0)p=Pt(a,o,l.attributes.NORMAL,3,5126);else{const P=l.indices;if(P===void 0)throw new Error("Cannot generate normals without indices");const T=yi(a,o,P);p=Ys(m,T)}const d=l.indices;if(d===void 0)throw new Error("Mesh primitive missing indices");const b=yi(a,o,d),w=m.length/3,M=b.length;let R=null;l.attributes.TEXCOORD_0!==void 0&&(R=Pt(a,o,l.attributes.TEXCOORD_0,2,5126));let x=!1;if(a.materials&&a.materials.length>0){const P=a.materials[0];P.pbrMetallicRoughness&&P.pbrMetallicRoughness.baseColorTexture!==void 0&&(x=!0)}let L=null;if(a.skins&&a.skins.length>0)try{L=Js(a,o,l),globalThis.__HZFX_DEBUG&&console.log("Animation data extracted:",L)}catch(P){console.warn("Failed to extract animation data:",P)}return{positions:m,normals:p,indices:b,texCoords:R,vertexCount:w,indexCount:M,animationData:L,hasBaseColorTexture:x}}function Pt(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),u=n.count,m=new DataView(t,l,u*i*4),p=new Float32Array(u*i);for(let d=0;d<u*i;d++)p[d]=m.getFloat32(d*4,!0);return p}function yi(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 Ys(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]],u=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],m=[l[0]-o[0],l[1]-o[1],l[2]-o[2]],p=[u[1]*m[2]-u[2]*m[1],u[2]*m[0]-u[0]*m[2],u[0]*m[1]-u[1]*m[0]],d=Math.sqrt(p[0]*p[0]+p[1]*p[1]+p[2]*p[2]);d>0&&(p[0]/=d,p[1]/=d,p[2]/=d),e[r]=e[n]=e[a]=p[0],e[r+1]=e[n+1]=e[a+1]=p[1],e[r+2]=e[n+2]=e[a+2]=p[2]}return e}function Hs(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 qs(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 Zs(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 $s(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 Ws(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),u=new Float32Array(c*n);for(let m=0;m<c*n;m++)u[m]=l.getFloat32(m*4,!0);return u}function Js(s,t,e){const i=s.skins[0],r=i.joints,n=Zs(s,t,i.inverseBindMatrices),a=e.attributes.JOINTS_0!==void 0?Hs(s,t,e.attributes.JOINTS_0):null,o=e.attributes.WEIGHTS_0!==void 0?qs(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(u=>({translation:u.translation||[0,0,0],rotation:u.rotation||[0,0,0,1],scale:u.scale||[1,1,1],children:u.children||[],name:u.name||""})),l=[];if(s.animations&&s.animations.length>0)for(const u of s.animations){const m=[];let p=0;for(const d of u.channels){const b=u.samplers[d.sampler],w=$s(s,t,b.input),M=Ws(s,t,b.output),R=w[w.length-1];R>p&&(p=R),m.push({targetNode:d.target.node,targetPath:d.target.path,interpolation:b.interpolation||"LINEAR",timestamps:w,values:M})}l.push({name:u.name||`Animation ${l.length}`,duration:p,channels:m})}return{joints:r,inverseBindMatrices:n,jointIndices:a,jointWeights:o,nodes:c,animations:l}}async function Mt(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 L=t.getUint32(n,!0),P=t.getUint32(n+4,!0),T=s.slice(n+8,n+8+L);if(P===1313821514){const F=new TextDecoder("utf-8").decode(T);a=JSON.parse(F)}else P===5130562&&(o=T);n+=8+L}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 m=a.textures[l].source;if(m===void 0||!a.images||!a.images[m])return null;const p=a.images[m],d=p.mimeType||"image/png";if(p.bufferView===void 0)return null;if(!o)throw new Error("GLB file missing BIN chunk (required for embedded textures)");const b=a.bufferViews[p.bufferView],w=b.byteOffset||0,M=b.byteLength,R=o.slice(w,w+M);return{imageBlob:new Blob([R],{type:d}),mimeType:d}}function Qs(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 Ks(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 u=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]);return u>1e-4?(i[0]/=u,i[1]/=u,i[2]/=u,i[3]/=u):(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 er(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,u=e*o,m=e*c,p=i*o,d=i*c,b=r*c,w=n*a,M=n*o,R=n*c,x=t||new Float32Array(16);return x[0]=1-(p+b),x[1]=u+R,x[2]=m-M,x[3]=0,x[4]=u-R,x[5]=1-(l+b),x[6]=d+w,x[7]=0,x[8]=m+M,x[9]=d-w,x[10]=1-(l+p),x[11]=0,x[12]=0,x[13]=0,x[14]=0,x[15]=1,x}const tr=new Float32Array(16);function ir(s,t,e,i){const r=er(t,tr),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 gi(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 Gi{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,u=c*3,m=c*2;n[l]=this.restPositions[u],n[l+1]=this.restPositions[u+1],n[l+2]=this.restPositions[u+2],n[l+3]=this.restNormals[u],n[l+4]=this.restNormals[u+1],n[l+5]=this.restNormals[u+2],n[l+6]=i?i[m]:0,n[l+7]=i?i[m+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:Os}),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 w=Math.floor((c+l)/2);r[w]<=e?c=w:l=w}const u=r[c],m=r[l],p=(e-u)/(m-u),d=this._extractValue(n,c,o,this._sV0),b=this._extractValue(n,l,o,this._sV1);return a==="STEP"?(i[0]=d[0],i[1]=d[1],i[2]=d[2],o==="rotation"&&(i[3]=d[3]),i):o==="rotation"?Ks(d,b,p,i):Qs(d,b,p,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)));ir(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]):gi(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];gi(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 u=l*3,m=l*4,p=e[u],d=e[u+1],b=e[u+2],w=i[u],M=i[u+1],R=i[u+2];let x=0,L=0,P=0,T=0,E=0,F=0;for(let Y=0;Y<4;Y++){const N=a[m+Y];if(N===0)continue;const z=c[o[m+Y]];x+=(z[0]*p+z[4]*d+z[8]*b+z[12])*N,L+=(z[1]*p+z[5]*d+z[9]*b+z[13])*N,P+=(z[2]*p+z[6]*d+z[10]*b+z[14])*N,T+=(z[0]*w+z[4]*M+z[8]*R)*N,E+=(z[1]*w+z[5]*M+z[9]*R)*N,F+=(z[2]*w+z[6]*M+z[10]*R)*N}const k=Math.sqrt(T*T+E*E+F*F);k>1e-4&&(n[u]=T/k,n[u+1]=E/k,n[u+2]=F/k),r[u]=x,r[u+1]=L,r[u+2]=P}}}class zi{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 bi={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 sr(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,u=d=>((a*d+n)*d+r)*d,m=d=>((l*d+c)*d+o)*d,p=d=>(3*a*d+2*n)*d+r;return d=>{if(d<=0)return 0;if(d>=1)return 1;let b=d;for(let w=0;w<8;w++){const M=u(b)-d;if(Math.abs(M)<1e-5)break;const R=p(b);if(Math.abs(R)<1e-6)break;b-=M/R}return m(b)}}function Di(s,t){return typeof s=="function"?s(t):Array.isArray(s)&&s.length===4?sr(s[0],s[1],s[2],s[3])(t):(bi[s]||bi.linear)(t)}function rr(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)*Di(r.ease,o)}}return e.v}function nr(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 m=0;m<i-1;m++){const p=s[m],d=s[m+1];if(t>=p.t&&t<=d.t){const b=d.t-p.t;n=p.v,a=d.v,o=Di(p.ease,b>0?(t-p.t)/b:0);break}}}const c=n[0]+(a[0]-n[0])*o,l=n[1]+(a[1]-n[1])*o,u=n[2]+(a[2]-n[2])*o;return e?(e[0]=c,e[1]=l,e[2]=u,e):[c,l,u]}const ar=["gravityStrength","emissionRate","damping","particleSize","particleSpeed"],or={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 Si(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 ct{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.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.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.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 wi(e),this.physics=new Ci(t,this.MAX_PARTICLES),this.textureManager=new Ai(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.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 Bt(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 Bt(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 Ii(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 Gi(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=or[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(){if(this.activeParticles=0,this.currentEmissionTime=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.updateAppearanceUniform(),this.updateBloomIntensity()):this._particleScript.snapshotConfig(this.config)),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 t=this.config.particleCount;this.particleCount=t;let e=0;const i=500;for(let r=0;r<t;r++)if(this.emitParticle(),e++,e>=i||r===t-1){const n=r-e+1,a=n*8,o=n*4;this.device.queue.writeBuffer(this.instanceBuffer,a*4,this.particleData,a,e*8),this.device.queue.writeBuffer(this.velocityBuffer,o*4,this.particleVelocities,o,e*4),e=0}this.emitting=!1}else{this.emitting=!0;const t=this.config.lifetime||5,e=this.config.emissionDurationInfinite?t:Math.min(this.config.emissionDuration||10,t);this.particleCount=Math.min(Math.ceil((this.config.emissionRate||10)*e),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],u=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]*u,this.particleVelocities[i+1]=r[3]*c+r[4]*l+r[5]*u,this.particleVelocities[i+2]=r[6]*c+r[7]*l+r[8]*u}(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 u=this.config.emissionDurationInfinite?1/0:(this.config.emissionDuration||0)+(this.config.lifetime||0);if(u>0&&this._scriptTime>=u&&!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));else if(!this._scriptConfigRestored){const m=u>0?Math.ceil(u/.016666666666666666):0,{configDirty:p,particlesDirty:d}=this._particleScript.execute(t,this._scriptTime,this._scriptFrame,m,this._scriptParticleData,this._scriptVelocityData,this.activeParticles);d&&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)),p&&(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.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 u=this.activeParticles;let m=!1;if(this.config.followSystemId){if(this._pendingFollowEmissions.length>0){const p=this._pendingFollowEmissions.length/6;for(let d=0;d<p;d++){const b=d*6;if(this.emitFollowerParticle(this._pendingFollowEmissions[b],this._pendingFollowEmissions[b+1],this._pendingFollowEmissions[b+2]))m=!0;else break}}}else{let p=0;if(this.config.emissionRate>=1){p=Math.floor(this.config.emissionRate*t);const d=this.config.emissionRate*t-p;Math.random()<d&&(p+=1)}else{const d=this.config.emissionRate*t;Math.random()<d&&(p=1)}p===0&&c&&this.config.emissionRate>0&&this.activeParticles<this.particleCount&&(p=1);for(let d=0;d<p&&this.emitParticle();d++)m=!0}if(m){const p=this.activeParticles-u,d=u*8,b=u*4;this.device.queue.writeBuffer(this.instanceBuffer,d*4,this.particleData,d,p*8),this.device.queue.writeBuffer(this.velocityBuffer,b*4,this.particleVelocities,b,p*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(u=>{this._scriptReadbackPending=!1,u.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,u=e*4;this.particleVelocities.copyWithin(u,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],u=Math.sqrt(o*o+c*c+l*l);if(u>.001){const m=this.config.particleSpeed*2;this.particleVelocities[i]=o/u*m,this.particleVelocities[i+1]=c/u*m,this.particleVelocities[i+2]=l/u*m}else{const m=Math.sqrt(r*r+n*n+a*a);if(m>.001){const p=this.config.particleSpeed*2;this.particleVelocities[i]=r/m*p,this.particleVelocities[i+1]=n/m*p,this.particleVelocities[i+2]=a/m*p}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){this.physics.setAttractor(t,e)}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 Fi{constructor(t){this.device=t,this.particleSystems=[],this.activeSystemIndex=0,this.systemCounter=1,this.onSystemCreated=null,this.loop=void 0,this.clock=new zi({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 ct(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;for(const{system:e}of this.particleSystems)e.spawnParticles();(t=this.clock)==null||t.reset()}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){const l=c.keyframes;if(!(!l||c.keyframesEnabled===!1)){for(const u of ar){const m=l[u];if(m&&m.length){const p=rr(m,a);p!==void 0&&(c[u]=p)}}if(l.particleColor&&l.particleColor.length){const u=c.particleColor,m=u&&typeof u.length=="number"&&u.length>=3?u:void 0,p=nr(l.particleColor,a,m);p&&(c.particleColor=p,o.updateAppearanceUniform())}}}}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 ct(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=Si(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 Mt(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]]);const u=new ct(this.device,l);this.particleSystems.push({system:u,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=Si(c.glbModelData);else if(c.glbFileName){const u=await fetch(`/${c.glbFileName}`);u.ok?l=await u.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 u=await Mt(l);if(u){const m=await createImageBitmap(u.imageBlob);await o.setTexture(m),globalThis.__HZFX_DEBUG&&console.log(`GLB embedded texture restored for ${c.name}`)}}catch(u){console.warn(`Failed to restore GLB texture for ${c.name}:`,u),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((m,p)=>{l.onload=m,l.onerror=p,l.src=c.textureImageData});const u=await createImageBitmap(l);await o.setTexture(u),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}}}async function Vi(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 oe="rgba16float";function Rt(s,t,e,i){const r=s.createTexture({size:[e,i],format:oe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),n=s.createTexture({size:[e,i],format:oe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),a=s.createTexture({size:[e,i],format:oe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1});return{sceneTexture:r,bloomTexA:n,bloomTexB:a}}function Tt(s,t,e){return s.createTexture({size:[t,e],format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT})}function Te(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 Oi=`
|
|
877
|
+
};`,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,Ui)}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 $e){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 $e)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 Ii(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 P=t.getUint32(n,!0),T=t.getUint32(n+4,!0),E=s.slice(n+8,n+8+P);if(T===1313821514){const k=new TextDecoder("utf-8").decode(E);a=JSON.parse(k)}else T===5130562&&(o=E);n+=8+P}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 u=l.attributes.POSITION;if(u===void 0)throw new Error("Mesh primitive missing POSITION attribute");const m=Pt(a,o,u,3,5126);let p;if(l.attributes.NORMAL!==void 0)p=Pt(a,o,l.attributes.NORMAL,3,5126);else{const P=l.indices;if(P===void 0)throw new Error("Cannot generate normals without indices");const T=yi(a,o,P);p=Ys(m,T)}const d=l.indices;if(d===void 0)throw new Error("Mesh primitive missing indices");const b=yi(a,o,d),w=m.length/3,M=b.length;let R=null;l.attributes.TEXCOORD_0!==void 0&&(R=Pt(a,o,l.attributes.TEXCOORD_0,2,5126));let x=!1;if(a.materials&&a.materials.length>0){const P=a.materials[0];P.pbrMetallicRoughness&&P.pbrMetallicRoughness.baseColorTexture!==void 0&&(x=!0)}let L=null;if(a.skins&&a.skins.length>0)try{L=Js(a,o,l),globalThis.__HZFX_DEBUG&&console.log("Animation data extracted:",L)}catch(P){console.warn("Failed to extract animation data:",P)}return{positions:m,normals:p,indices:b,texCoords:R,vertexCount:w,indexCount:M,animationData:L,hasBaseColorTexture:x}}function Pt(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),u=n.count,m=new DataView(t,l,u*i*4),p=new Float32Array(u*i);for(let d=0;d<u*i;d++)p[d]=m.getFloat32(d*4,!0);return p}function yi(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 Ys(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]],u=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],m=[l[0]-o[0],l[1]-o[1],l[2]-o[2]],p=[u[1]*m[2]-u[2]*m[1],u[2]*m[0]-u[0]*m[2],u[0]*m[1]-u[1]*m[0]],d=Math.sqrt(p[0]*p[0]+p[1]*p[1]+p[2]*p[2]);d>0&&(p[0]/=d,p[1]/=d,p[2]/=d),e[r]=e[n]=e[a]=p[0],e[r+1]=e[n+1]=e[a+1]=p[1],e[r+2]=e[n+2]=e[a+2]=p[2]}return e}function Hs(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 qs(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 Zs(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 $s(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 Ws(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),u=new Float32Array(c*n);for(let m=0;m<c*n;m++)u[m]=l.getFloat32(m*4,!0);return u}function Js(s,t,e){const i=s.skins[0],r=i.joints,n=Zs(s,t,i.inverseBindMatrices),a=e.attributes.JOINTS_0!==void 0?Hs(s,t,e.attributes.JOINTS_0):null,o=e.attributes.WEIGHTS_0!==void 0?qs(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(u=>({translation:u.translation||[0,0,0],rotation:u.rotation||[0,0,0,1],scale:u.scale||[1,1,1],children:u.children||[],name:u.name||""})),l=[];if(s.animations&&s.animations.length>0)for(const u of s.animations){const m=[];let p=0;for(const d of u.channels){const b=u.samplers[d.sampler],w=$s(s,t,b.input),M=Ws(s,t,b.output),R=w[w.length-1];R>p&&(p=R),m.push({targetNode:d.target.node,targetPath:d.target.path,interpolation:b.interpolation||"LINEAR",timestamps:w,values:M})}l.push({name:u.name||`Animation ${l.length}`,duration:p,channels:m})}return{joints:r,inverseBindMatrices:n,jointIndices:a,jointWeights:o,nodes:c,animations:l}}async function Mt(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 L=t.getUint32(n,!0),P=t.getUint32(n+4,!0),T=s.slice(n+8,n+8+L);if(P===1313821514){const F=new TextDecoder("utf-8").decode(T);a=JSON.parse(F)}else P===5130562&&(o=T);n+=8+L}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 m=a.textures[l].source;if(m===void 0||!a.images||!a.images[m])return null;const p=a.images[m],d=p.mimeType||"image/png";if(p.bufferView===void 0)return null;if(!o)throw new Error("GLB file missing BIN chunk (required for embedded textures)");const b=a.bufferViews[p.bufferView],w=b.byteOffset||0,M=b.byteLength,R=o.slice(w,w+M);return{imageBlob:new Blob([R],{type:d}),mimeType:d}}function Qs(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 Ks(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 u=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]);return u>1e-4?(i[0]/=u,i[1]/=u,i[2]/=u,i[3]/=u):(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 er(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,u=e*o,m=e*c,p=i*o,d=i*c,b=r*c,w=n*a,M=n*o,R=n*c,x=t||new Float32Array(16);return x[0]=1-(p+b),x[1]=u+R,x[2]=m-M,x[3]=0,x[4]=u-R,x[5]=1-(l+b),x[6]=d+w,x[7]=0,x[8]=m+M,x[9]=d-w,x[10]=1-(l+p),x[11]=0,x[12]=0,x[13]=0,x[14]=0,x[15]=1,x}const tr=new Float32Array(16);function ir(s,t,e,i){const r=er(t,tr),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 gi(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 Gi{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,u=c*3,m=c*2;n[l]=this.restPositions[u],n[l+1]=this.restPositions[u+1],n[l+2]=this.restPositions[u+2],n[l+3]=this.restNormals[u],n[l+4]=this.restNormals[u+1],n[l+5]=this.restNormals[u+2],n[l+6]=i?i[m]:0,n[l+7]=i?i[m+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:Os}),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 w=Math.floor((c+l)/2);r[w]<=e?c=w:l=w}const u=r[c],m=r[l],p=(e-u)/(m-u),d=this._extractValue(n,c,o,this._sV0),b=this._extractValue(n,l,o,this._sV1);return a==="STEP"?(i[0]=d[0],i[1]=d[1],i[2]=d[2],o==="rotation"&&(i[3]=d[3]),i):o==="rotation"?Ks(d,b,p,i):Qs(d,b,p,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)));ir(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]):gi(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];gi(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 u=l*3,m=l*4,p=e[u],d=e[u+1],b=e[u+2],w=i[u],M=i[u+1],R=i[u+2];let x=0,L=0,P=0,T=0,E=0,F=0;for(let Y=0;Y<4;Y++){const N=a[m+Y];if(N===0)continue;const z=c[o[m+Y]];x+=(z[0]*p+z[4]*d+z[8]*b+z[12])*N,L+=(z[1]*p+z[5]*d+z[9]*b+z[13])*N,P+=(z[2]*p+z[6]*d+z[10]*b+z[14])*N,T+=(z[0]*w+z[4]*M+z[8]*R)*N,E+=(z[1]*w+z[5]*M+z[9]*R)*N,F+=(z[2]*w+z[6]*M+z[10]*R)*N}const k=Math.sqrt(T*T+E*E+F*F);k>1e-4&&(n[u]=T/k,n[u+1]=E/k,n[u+2]=F/k),r[u]=x,r[u+1]=L,r[u+2]=P}}}class zi{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 bi={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 sr(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,u=d=>((a*d+n)*d+r)*d,m=d=>((l*d+c)*d+o)*d,p=d=>(3*a*d+2*n)*d+r;return d=>{if(d<=0)return 0;if(d>=1)return 1;let b=d;for(let w=0;w<8;w++){const M=u(b)-d;if(Math.abs(M)<1e-5)break;const R=p(b);if(Math.abs(R)<1e-6)break;b-=M/R}return m(b)}}function Di(s,t){return typeof s=="function"?s(t):Array.isArray(s)&&s.length===4?sr(s[0],s[1],s[2],s[3])(t):(bi[s]||bi.linear)(t)}function rr(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)*Di(r.ease,o)}}return e.v}function nr(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 m=0;m<i-1;m++){const p=s[m],d=s[m+1];if(t>=p.t&&t<=d.t){const b=d.t-p.t;n=p.v,a=d.v,o=Di(p.ease,b>0?(t-p.t)/b:0);break}}}const c=n[0]+(a[0]-n[0])*o,l=n[1]+(a[1]-n[1])*o,u=n[2]+(a[2]-n[2])*o;return e?(e[0]=c,e[1]=l,e[2]=u,e):[c,l,u]}const ar=["gravityStrength","emissionRate","damping","particleSize","particleSpeed"],or={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 Si(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 ct{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.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.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.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 wi(e),this.physics=new Ci(t,this.MAX_PARTICLES),this.textureManager=new Ai(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.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 Bt(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 Bt(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 Ii(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 Gi(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=or[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(){if(this.activeParticles=0,this.currentEmissionTime=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.updateAppearanceUniform(),this.updateBloomIntensity()):this._particleScript.snapshotConfig(this.config)),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 t=this.config.particleCount;this.particleCount=t;let e=0;const i=500;for(let r=0;r<t;r++)if(this.emitParticle(),e++,e>=i||r===t-1){const n=r-e+1,a=n*8,o=n*4;this.device.queue.writeBuffer(this.instanceBuffer,a*4,this.particleData,a,e*8),this.device.queue.writeBuffer(this.velocityBuffer,o*4,this.particleVelocities,o,e*4),e=0}this.emitting=!1}else{this.emitting=!0;const t=this.config.lifetime||5,e=this.config.emissionDurationInfinite?t:Math.min(this.config.emissionDuration||10,t);this.particleCount=Math.min(Math.ceil((this.config.emissionRate||10)*e),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],u=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]*u,this.particleVelocities[i+1]=r[3]*c+r[4]*l+r[5]*u,this.particleVelocities[i+2]=r[6]*c+r[7]*l+r[8]*u}(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 u=this.config.emissionDurationInfinite?1/0:(this.config.emissionDuration||0)+(this.config.lifetime||0);if(u>0&&this._scriptTime>=u&&!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));else if(!this._scriptConfigRestored){const m=u>0?Math.ceil(u/.016666666666666666):0,{configDirty:p,particlesDirty:d}=this._particleScript.execute(t,this._scriptTime,this._scriptFrame,m,this._scriptParticleData,this._scriptVelocityData,this.activeParticles);d&&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)),p&&(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.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 u=this.activeParticles;let m=!1;if(this.config.followSystemId){if(this._pendingFollowEmissions.length>0){const p=this._pendingFollowEmissions.length/6;for(let d=0;d<p;d++){const b=d*6;if(this.emitFollowerParticle(this._pendingFollowEmissions[b],this._pendingFollowEmissions[b+1],this._pendingFollowEmissions[b+2]))m=!0;else break}}}else{let p=0;if(this.config.emissionRate>=1){p=Math.floor(this.config.emissionRate*t);const d=this.config.emissionRate*t-p;Math.random()<d&&(p+=1)}else{const d=this.config.emissionRate*t;Math.random()<d&&(p=1)}p===0&&c&&this.config.emissionRate>0&&this.activeParticles<this.particleCount&&(p=1);for(let d=0;d<p&&this.emitParticle();d++)m=!0}if(m){const p=this.activeParticles-u,d=u*8,b=u*4;this.device.queue.writeBuffer(this.instanceBuffer,d*4,this.particleData,d,p*8),this.device.queue.writeBuffer(this.velocityBuffer,b*4,this.particleVelocities,b,p*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(u=>{this._scriptReadbackPending=!1,u.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,u=e*4;this.particleVelocities.copyWithin(u,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],u=Math.sqrt(o*o+c*c+l*l);if(u>.001){const m=this.config.particleSpeed*2;this.particleVelocities[i]=o/u*m,this.particleVelocities[i+1]=c/u*m,this.particleVelocities[i+2]=l/u*m}else{const m=Math.sqrt(r*r+n*n+a*a);if(m>.001){const p=this.config.particleSpeed*2;this.particleVelocities[i]=r/m*p,this.particleVelocities[i+1]=n/m*p,this.particleVelocities[i+2]=a/m*p}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){this.physics.setAttractor(t,e)}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 Fi{constructor(t){this.device=t,this.particleSystems=[],this.activeSystemIndex=0,this.systemCounter=1,this.onSystemCreated=null,this.loop=void 0,this.clock=new zi({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 ct(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;for(const{system:e}of this.particleSystems)e.spawnParticles();(t=this.clock)==null||t.reset()}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){const l=c.keyframes;if(!(!l||c.keyframesEnabled===!1)){for(const u of ar){const m=l[u];if(m&&m.length){const p=rr(m,a);p!==void 0&&(c[u]=p)}}if(l.particleColor&&l.particleColor.length){const u=c.particleColor,m=u&&typeof u.length=="number"&&u.length>=3?u:void 0,p=nr(l.particleColor,a,m);p&&(c.particleColor=p,o.updateAppearanceUniform())}}}}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 ct(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=Si(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 Mt(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 u=new ct(this.device,l);this.particleSystems.push({system:u,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=Si(c.glbModelData);else if(c.glbFileName){const u=await fetch(`/${c.glbFileName}`);u.ok?l=await u.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 u=await Mt(l);if(u){const m=await createImageBitmap(u.imageBlob);await o.setTexture(m),globalThis.__HZFX_DEBUG&&console.log(`GLB embedded texture restored for ${c.name}`)}}catch(u){console.warn(`Failed to restore GLB texture for ${c.name}:`,u),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((m,p)=>{l.onload=m,l.onerror=p,l.src=c.textureImageData});const u=await createImageBitmap(l);await o.setTexture(u),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}}}async function Vi(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 oe="rgba16float";function Rt(s,t,e,i){const r=s.createTexture({size:[e,i],format:oe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),n=s.createTexture({size:[e,i],format:oe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1}),a=s.createTexture({size:[e,i],format:oe,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,mipLevelCount:1,sampleCount:1});return{sceneTexture:r,bloomTexA:n,bloomTexB:a}}function Tt(s,t,e){return s.createTexture({size:[t,e],format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT})}function Te(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 Oi=`
|
|
878
878
|
struct Uniforms {
|
|
879
879
|
transform: mat4x4<f32>,
|
|
880
880
|
cameraPosition: vec3<f32>,
|
|
@@ -3051,6 +3051,10 @@ class Ws {
|
|
|
3051
3051
|
o.attractorPosition[0] + e[0],
|
|
3052
3052
|
o.attractorPosition[1] + e[1],
|
|
3053
3053
|
o.attractorPosition[2] + e[2]
|
|
3054
|
+
]), o.confinementEnabled && o.confinementSpace === "world" && Array.isArray(o.confinementCenter) && (l.confinementCenter = [
|
|
3055
|
+
(o.confinementCenter[0] || 0) + e[0],
|
|
3056
|
+
(o.confinementCenter[1] || 0) + e[1],
|
|
3057
|
+
(o.confinementCenter[2] || 0) + e[2]
|
|
3054
3058
|
]);
|
|
3055
3059
|
const u = new vt(this.device, l);
|
|
3056
3060
|
this.particleSystems.push({
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hz-particles",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.2",
|
|
4
4
|
"description": "High-performance WebGPU particle engine with compute shaders, GPU instancing, GLB model support, and skeletal animations",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist-lib/hz-particles.cjs",
|