babylon.quarks 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +585 -0
  2. package/README.md +3 -1
  3. package/dist/babylon.quarks.cjs +1 -1
  4. package/dist/babylon.quarks.cjs.map +1 -1
  5. package/dist/babylon.quarks.esm.js +1 -1
  6. package/dist/babylon.quarks.esm.js.map +1 -1
  7. package/dist/babylon.quarks.umd.min.js +1 -1
  8. package/dist/babylon.quarks.umd.min.js.map +1 -1
  9. package/dist/types/index.d.cts +4811 -974
  10. package/dist/types/index.d.ts +4811 -974
  11. package/package.json +7 -2
  12. package/src/BatchedRenderer.ts +106 -79
  13. package/src/EffectPool.ts +96 -16
  14. package/src/MeshSurfaceEmitter.ts +24 -13
  15. package/src/ParticleEmitter.ts +119 -26
  16. package/src/ParticleSystem.ts +305 -55
  17. package/src/QuarksLoader.ts +298 -171
  18. package/src/QuarksPrefab.ts +301 -94
  19. package/src/QuarksSerializer.ts +44 -16
  20. package/src/QuarksUtil.ts +88 -11
  21. package/src/SpriteBatch.ts +24 -6
  22. package/src/TrailBatch.ts +20 -7
  23. package/src/VFXBatch.ts +182 -528
  24. package/src/batchKey.ts +6 -2
  25. package/src/batchSettings.ts +548 -0
  26. package/src/effectDocumentJSON.ts +261 -0
  27. package/src/effectResources.ts +21 -24
  28. package/src/envAtlas.ts +8 -2
  29. package/src/geometryUtil.ts +1 -1
  30. package/src/index.ts +41 -4
  31. package/src/nodeId.ts +25 -2
  32. package/src/shaderProgram.ts +213 -16
  33. package/src/shaderVariants.ts +124 -7
  34. package/src/shaders/chunks/blend.ts +39 -0
  35. package/src/shaders/chunks/fog.ts +8 -3
  36. package/src/shaders/chunks/imageProcessing.ts +143 -0
  37. package/src/shaders/chunks/soft.ts +6 -5
  38. package/src/shaders/chunks/surface.ts +2 -2
  39. package/src/shaders/particle_frag.glsl.ts +5 -1
  40. package/src/shaders/particle_frag.wgsl.ts +4 -0
  41. package/src/shaders/particle_physics_frag.glsl.ts +7 -2
  42. package/src/shaders/particle_physics_frag.wgsl.ts +4 -0
  43. package/src/shaders/trail_frag.glsl.ts +6 -1
  44. package/src/shaders/trail_frag.wgsl.ts +4 -0
  45. package/src/system/EmissionController.ts +23 -20
  46. package/src/system/EventDispatcher.ts +26 -10
  47. package/src/system/ParticleSpawner.ts +96 -19
  48. package/src/system/geometry.ts +22 -29
  49. package/src/system/integrate.ts +61 -4
  50. package/src/system/materialResolve.ts +56 -7
  51. package/src/system/normalize.ts +34 -2
  52. package/src/system/serialization.ts +54 -33
  53. package/src/system/settingsSchema.ts +57 -17
  54. package/src/system/types.ts +150 -42
  55. package/src/trailSettings.ts +9 -6
@@ -1,2 +1,2 @@
1
- import{VertexBuffer as t}from"@babylonjs/core/Buffers/buffer.js";import{RandomGUID as e}from"@babylonjs/core/Misc/guid.js";import{Frustum as i}from"@babylonjs/core/Maths/math.frustum.js";import{Plane as s}from"@babylonjs/core/Maths/math.plane.js";import{TransformNode as n}from"@babylonjs/core/Meshes/transformNode.js";import{Constants as r}from"@babylonjs/core/Engines/constants.js";import{BoundingInfo as o}from"@babylonjs/core/Culling/boundingInfo.js";import{BaseTexture as a}from"@babylonjs/core/Materials/Textures/baseTexture.js";import{ShaderMaterial as h}from"@babylonjs/core/Materials/shaderMaterial.js";import{Color3 as l}from"@babylonjs/core/Maths/math.color.js";import{Vector3 as c,Vector4 as u,Vector2 as d,Matrix as f,Quaternion as m}from"@babylonjs/core/Maths/math.vector.js";import{Mesh as p}from"@babylonjs/core/Meshes/mesh.js";import{Scene as y}from"@babylonjs/core/scene.js";import{Camera as g}from"@babylonjs/core/Cameras/camera.js";import{RawTexture as v}from"@babylonjs/core/Materials/Textures/rawTexture.js";import{VertexData as x}from"@babylonjs/core/Meshes/mesh.vertexData.js";import{ShaderStore as w}from"@babylonjs/core/Engines/shaderStore.js";import{Effect as b}from"@babylonjs/core/Materials/effect.js";import{ShaderLanguage as S}from"@babylonjs/core/Materials/shaderLanguage.js";import{Texture as M}from"@babylonjs/core/Materials/Textures/texture.js";import{StandardMaterial as z}from"@babylonjs/core/Materials/standardMaterial.js";import{InstancedMesh as _}from"@babylonjs/core/Meshes/instancedMesh.js";let V=null;function A(){return null===V?Math.random():V()}function T(){return V??Math.random}function O(t){const e=T();return V=t,e}function $(t){let e=t>>>0||2654435769;return()=>{e=e+1831565813|0;let t=e;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}function P(t,e){const i=O(t);try{return e()}finally{O(i)}}const C=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let F=1234567;const I=Math.PI/180,U=180/Math.PI;function B(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return(C[255&t]+C[t>>8&255]+C[t>>16&255]+C[t>>24&255]+"-"+C[255&e]+C[e>>8&255]+"-"+C[e>>16&15|64]+C[e>>24&255]+"-"+C[63&i|128]+C[i>>8&255]+"-"+C[i>>16&255]+C[i>>24&255]+C[255&s]+C[s>>8&255]+C[s>>16&255]+C[s>>24&255]).toLowerCase()}function E(t,e,i){return Math.max(e,Math.min(i,t))}function N(t,e){return(t%e+e)%e}function D(t,e,i,s,n){return s+(t-e)*(n-s)/(i-e)}function k(t,e,i){return t!==e?(i-t)/(e-t):0}function R(t,e,i){return(1-i)*t+i*e}function L(t,e,i,s){return R(t,e,1-Math.exp(-i*s))}function q(t,e=1){return e-Math.abs(N(t,2*e)-e)}function J(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}function W(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*t*(t*(6*t-15)+10)}function Q(t,e){return t+Math.floor(A()*(e-t+1))}function G(t,e){return t+A()*(e-t)}function j(t){return t*(.5-A())}function Y(t){void 0!==t&&(F=t);let e=F+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}function H(t){return t*I}function X(t){return t*U}function Z(t){return!(t&t-1)&&0!==t}function K(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function tt(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function et(t,e,i,s,n){const r=Math.cos,o=Math.sin,a=r(i/2),h=o(i/2),l=r((e+s)/2),c=o((e+s)/2),u=r((e-s)/2),d=o((e-s)/2),f=r((s-e)/2),m=o((s-e)/2);switch(n){case"XYX":t.set(a*c,h*u,h*d,a*l);break;case"YZY":t.set(h*d,a*c,h*u,a*l);break;case"ZXZ":t.set(h*u,h*d,a*c,a*l);break;case"XZX":t.set(a*c,h*m,h*f,a*l);break;case"YXY":t.set(h*f,a*c,h*m,a*l);break;case"ZYZ":t.set(h*m,h*f,a*c,a*l);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function it(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function st(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const nt={DEG2RAD:I,RAD2DEG:U,generateUUID:B,clamp:E,euclideanModulo:N,mapLinear:D,inverseLerp:k,lerp:R,damp:L,pingpong:q,smoothstep:J,smootherstep:W,randInt:Q,randFloat:G,randFloatSpread:j,seededRandom:Y,degToRad:H,radToDeg:X,isPowerOfTwo:Z,ceilPowerOfTwo:K,floorPowerOfTwo:tt,setQuaternionFromProperEuler:et,normalize:st,denormalize:it};class rt{constructor(t=0,e=0,i=0,s=1){this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,n,r,o){let a=i[s+0],h=i[s+1],l=i[s+2],c=i[s+3];const u=n[r+0],d=n[r+1],f=n[r+2],m=n[r+3];if(0===o)return t[e+0]=a,t[e+1]=h,t[e+2]=l,void(t[e+3]=c);if(1===o)return t[e+0]=u,t[e+1]=d,t[e+2]=f,void(t[e+3]=m);if(c!==m||a!==u||h!==d||l!==f){let t=1-o;const e=a*u+h*d+l*f+c*m,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const n=Math.sqrt(s),r=Math.atan2(n,e*i);t=Math.sin(t*r)/n,o=Math.sin(o*r)/n}const n=o*i;if(a=a*t+u*n,h=h*t+d*n,l=l*t+f*n,c=c*t+m*n,t===1-o){const t=1/Math.sqrt(a*a+h*h+l*l+c*c);a*=t,h*=t,l*=t,c*=t}}t[e]=a,t[e+1]=h,t[e+2]=l,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,n,r){const o=i[s],a=i[s+1],h=i[s+2],l=i[s+3],c=n[r],u=n[r+1],d=n[r+2],f=n[r+3];return t[e]=o*f+l*c+a*d-h*u,t[e+1]=a*f+l*u+h*c-o*d,t[e+2]=h*f+l*d+o*u-a*c,t[e+3]=l*f-o*c-a*u-h*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new rt(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,s=t._y,n=t._z,r=t._order,o=Math.cos,a=Math.sin,h=o(i/2),l=o(s/2),c=o(n/2),u=a(i/2),d=a(s/2),f=a(n/2);switch(r){case"XYZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"YXZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"ZXY":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"ZYX":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"YZX":this._x=u*l*c+h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c-u*d*f;break;case"XZY":this._x=u*l*c-h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c+u*d*f;break;default:console.warn("../math.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],n=e[8],r=e[1],o=e[5],a=e[9],h=e[2],l=e[6],c=e[10],u=i+o+c;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(l-a)*t,this._y=(n-h)*t,this._z=(r-s)*t}else if(i>o&&i>c){const t=2*Math.sqrt(1+i-o-c);this._w=(l-a)/t,this._x=.25*t,this._y=(s+r)/t,this._z=(n+h)/t}else if(o>c){const t=2*Math.sqrt(1+o-i-c);this._w=(n-h)/t,this._x=(s+r)/t,this._y=.25*t,this._z=(a+l)/t}else{const t=2*Math.sqrt(1+c-i-o);this._w=(r-s)/t,this._x=(n+h)/t,this._y=(a+l)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(E(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,n=t._z,r=t._w,o=e._x,a=e._y,h=e._z,l=e._w;return this._x=i*l+r*o+s*h-n*a,this._y=s*l+r*a+n*o-i*h,this._z=n*l+r*h+i*a-s*o,this._w=r*l-i*o-s*a-n*h,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,n=this._z,r=this._w;let o=r*t._w+i*t._x+s*t._y+n*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=r,this._x=i,this._y=s,this._z=n,this;const a=1-o*o;if(a<=Number.EPSILON){const t=1-e;return this._w=t*r+e*this._w,this._x=t*i+e*this._x,this._y=t*s+e*this._y,this._z=t*n+e*this._z,this.normalize(),this}const h=Math.sqrt(a),l=Math.atan2(h,o),c=Math.sin((1-e)*l)/h,u=Math.sin(e*l)/h;return this._w=r*c+this._w*u,this._x=i*c+this._x*u,this._y=s*c+this._y*u,this._z=n*c+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*A(),e=2*Math.PI*A(),i=A(),s=Math.sqrt(1-i),n=Math.sqrt(i);return this.set(s*Math.sin(t),s*Math.cos(t),n*Math.sin(e),n*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}rt.prototype.isQuaternion=!0;class ot{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new ot(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(ht.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(ht.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6]*s,this.y=n[1]*e+n[4]*i+n[7]*s,this.z=n[2]*e+n[5]*i+n[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=t.elements,r=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*e+n[4]*i+n[8]*s+n[12])*r,this.y=(n[1]*e+n[5]*i+n[9]*s+n[13])*r,this.z=(n[2]*e+n[6]*i+n[10]*s+n[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,n=t.x,r=t.y,o=t.z,a=t.w,h=2*(r*s-o*i),l=2*(o*e-n*s),c=2*(n*i-r*e);return this.x=e+a*h+r*c-o*l,this.y=i+a*l+o*h-n*c,this.z=s+a*c+n*l-r*h,this}transformDirection(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s,this.y=n[1]*e+n[5]*i+n[9]*s,this.z=n[2]*e+n[6]*i+n[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,n=t.z,r=e.x,o=e.y,a=e.z;return this.x=s*a-n*o,this.y=n*r-i*a,this.z=i*o-s*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return at.copy(this).projectOnVector(t),this.sub(at)}reflect(t){return this.sub(at.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(E(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}random(){return this.x=A(),this.y=A(),this.z=A(),this}randomDirection(){const t=A()*Math.PI*2,e=2*A()-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this.z=Math.abs(this.z),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}ot.prototype.isVector3=!0;const at=new ot,ht=new rt,lt=2e3,ct=2001;class ut{constructor(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,i){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p){const y=this.elements;return y[0]=t,y[4]=e,y[8]=i,y[12]=s,y[1]=n,y[5]=r,y[9]=o,y[13]=a,y[2]=h,y[6]=l,y[10]=c,y[14]=u,y[3]=d,y[7]=f,y[11]=m,y[15]=p,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new ut).fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/dt.setFromMatrixColumn(t,0).length(),n=1/dt.setFromMatrixColumn(t,1).length(),r=1/dt.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,n=t.z,r=Math.cos(i),o=Math.sin(i),a=Math.cos(s),h=Math.sin(s),l=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*l,i=r*c,s=o*l,n=o*c;e[0]=a*l,e[4]=-a*c,e[8]=h,e[1]=i+s*h,e[5]=t-n*h,e[9]=-o*a,e[2]=n-t*h,e[6]=s+i*h,e[10]=r*a}else if("YXZ"===t.order){const t=a*l,i=a*c,s=h*l,n=h*c;e[0]=t+n*o,e[4]=s*o-i,e[8]=r*h,e[1]=r*c,e[5]=r*l,e[9]=-o,e[2]=i*o-s,e[6]=n+t*o,e[10]=r*a}else if("ZXY"===t.order){const t=a*l,i=a*c,s=h*l,n=h*c;e[0]=t-n*o,e[4]=-r*c,e[8]=s+i*o,e[1]=i+s*o,e[5]=r*l,e[9]=n-t*o,e[2]=-r*h,e[6]=o,e[10]=r*a}else if("ZYX"===t.order){const t=r*l,i=r*c,s=o*l,n=o*c;e[0]=a*l,e[4]=s*h-i,e[8]=t*h+n,e[1]=a*c,e[5]=n*h+t,e[9]=i*h-s,e[2]=-h,e[6]=o*a,e[10]=r*a}else if("YZX"===t.order){const t=r*a,i=r*h,s=o*a,n=o*h;e[0]=a*l,e[4]=n-t*c,e[8]=s*c+i,e[1]=c,e[5]=r*l,e[9]=-o*l,e[2]=-h*l,e[6]=i*c+s,e[10]=t-n*c}else if("XZY"===t.order){const t=r*a,i=r*h,s=o*a,n=o*h;e[0]=a*l,e[4]=-c,e[8]=h*l,e[1]=t*c+n,e[5]=r*l,e[9]=i*c-s,e[2]=s*c-i,e[6]=o*l,e[10]=n*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(mt,t,pt)}lookAt(t,e,i){const s=this.elements;return vt.subVectors(t,e),0===vt.lengthSq()&&(vt.z=1),vt.normalize(),yt.crossVectors(i,vt),0===yt.lengthSq()&&(1===Math.abs(i.z)?vt.x+=1e-4:vt.z+=1e-4,vt.normalize(),yt.crossVectors(i,vt)),yt.normalize(),gt.crossVectors(vt,yt),s[0]=yt.x,s[4]=gt.x,s[8]=vt.x,s[1]=yt.y,s[5]=gt.y,s[9]=vt.y,s[2]=yt.z,s[6]=gt.z,s[10]=vt.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[4],a=i[8],h=i[12],l=i[1],c=i[5],u=i[9],d=i[13],f=i[2],m=i[6],p=i[10],y=i[14],g=i[3],v=i[7],x=i[11],w=i[15],b=s[0],S=s[4],M=s[8],z=s[12],_=s[1],V=s[5],A=s[9],T=s[13],O=s[2],$=s[6],P=s[10],C=s[14],F=s[3],I=s[7],U=s[11],B=s[15];return n[0]=r*b+o*_+a*O+h*F,n[4]=r*S+o*V+a*$+h*I,n[8]=r*M+o*A+a*P+h*U,n[12]=r*z+o*T+a*C+h*B,n[1]=l*b+c*_+u*O+d*F,n[5]=l*S+c*V+u*$+d*I,n[9]=l*M+c*A+u*P+d*U,n[13]=l*z+c*T+u*C+d*B,n[2]=f*b+m*_+p*O+y*F,n[6]=f*S+m*V+p*$+y*I,n[10]=f*M+m*A+p*P+y*U,n[14]=f*z+m*T+p*C+y*B,n[3]=g*b+v*_+x*O+w*F,n[7]=g*S+v*V+x*$+w*I,n[11]=g*M+v*A+x*P+w*U,n[15]=g*z+v*T+x*C+w*B,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],n=t[12],r=t[1],o=t[5],a=t[9],h=t[13],l=t[2],c=t[6],u=t[10],d=t[14];return t[3]*(+n*a*c-s*h*c-n*o*u+i*h*u+s*o*d-i*a*d)+t[7]*(+e*a*d-e*h*u+n*r*u-s*r*d+s*h*l-n*a*l)+t[11]*(+e*h*c-e*o*d-n*r*c+i*r*d+n*o*l-i*h*l)+t[15]*(-s*o*l-e*a*c+e*o*u+s*r*c-i*r*u+i*a*l)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=t[9],u=t[10],d=t[11],f=t[12],m=t[13],p=t[14],y=t[15],g=c*p*h-m*u*h+m*a*d-o*p*d-c*a*y+o*u*y,v=f*u*h-l*p*h-f*a*d+r*p*d+l*a*y-r*u*y,x=l*m*h-f*c*h+f*o*d-r*m*d-l*o*y+r*c*y,w=f*c*a-l*m*a-f*o*u+r*m*u+l*o*p-r*c*p,b=e*g+i*v+s*x+n*w;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/b;return t[0]=g*S,t[1]=(m*u*n-c*p*n-m*s*d+i*p*d+c*s*y-i*u*y)*S,t[2]=(o*p*n-m*a*n+m*s*h-i*p*h-o*s*y+i*a*y)*S,t[3]=(c*a*n-o*u*n-c*s*h+i*u*h+o*s*d-i*a*d)*S,t[4]=v*S,t[5]=(l*p*n-f*u*n+f*s*d-e*p*d-l*s*y+e*u*y)*S,t[6]=(f*a*n-r*p*n-f*s*h+e*p*h+r*s*y-e*a*y)*S,t[7]=(r*u*n-l*a*n+l*s*h-e*u*h-r*s*d+e*a*d)*S,t[8]=x*S,t[9]=(f*c*n-l*m*n-f*i*d+e*m*d+l*i*y-e*c*y)*S,t[10]=(r*m*n-f*o*n+f*i*h-e*m*h-r*i*y+e*o*y)*S,t[11]=(l*o*n-r*c*n-l*i*h+e*c*h+r*i*d-e*o*d)*S,t[12]=w*S,t[13]=(l*m*s-f*c*s+f*i*u-e*m*u-l*i*p+e*c*p)*S,t[14]=(f*o*s-r*m*s-f*i*a+e*m*a+r*i*p-e*o*p)*S,t[15]=(r*c*s-l*o*s+l*i*a-e*c*a-r*i*u+e*o*u)*S,this}scale(t){const e=this.elements,i=t.x,s=t.y,n=t.z;return e[0]*=i,e[4]*=s,e[8]*=n,e[1]*=i,e[5]*=s,e[9]*=n,e[2]*=i,e[6]*=s,e[10]*=n,e[3]*=i,e[7]*=s,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),n=1-i,r=t.x,o=t.y,a=t.z,h=n*r,l=n*o;return this.set(h*r+i,h*o-s*a,h*a+s*o,0,h*o+s*a,l*o+i,l*a-s*r,0,h*a-s*o,l*a+s*r,n*a*a+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,n,r){return this.set(1,i,n,0,t,1,r,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,n=e._x,r=e._y,o=e._z,a=e._w,h=n+n,l=r+r,c=o+o,u=n*h,d=n*l,f=n*c,m=r*l,p=r*c,y=o*c,g=a*h,v=a*l,x=a*c,w=i.x,b=i.y,S=i.z;return s[0]=(1-(m+y))*w,s[1]=(d+x)*w,s[2]=(f-v)*w,s[3]=0,s[4]=(d-x)*b,s[5]=(1-(u+y))*b,s[6]=(p+g)*b,s[7]=0,s[8]=(f+v)*S,s[9]=(p-g)*S,s[10]=(1-(u+m))*S,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let n=dt.set(s[0],s[1],s[2]).length();const r=dt.set(s[4],s[5],s[6]).length(),o=dt.set(s[8],s[9],s[10]).length();this.determinant()<0&&(n=-n),t.x=s[12],t.y=s[13],t.z=s[14],ft.copy(this);const a=1/n,h=1/r,l=1/o;return ft.elements[0]*=a,ft.elements[1]*=a,ft.elements[2]*=a,ft.elements[4]*=h,ft.elements[5]*=h,ft.elements[6]*=h,ft.elements[8]*=l,ft.elements[9]*=l,ft.elements[10]*=l,e.setFromRotationMatrix(ft),i.x=n,i.y=r,i.z=o,this}makePerspective(t,e,i,s,n,r,o=2e3){const a=this.elements,h=2*n/(e-t),l=2*n/(i-s),c=(e+t)/(e-t),u=(i+s)/(i-s);let d,f;if(o===lt)d=-(r+n)/(r-n),f=-2*r*n/(r-n);else{if(o!==ct)throw new Error("Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-r/(r-n),f=-r*n/(r-n)}return a[0]=h,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=u,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=f,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,i,s,n,r,o=2e3){const a=this.elements,h=1/(e-t),l=1/(i-s),c=1/(r-n),u=(e+t)*h,d=(i+s)*l;let f,m;if(o===lt)f=(r+n)*c,m=-2*c;else{if(o!==ct)throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);f=n*c,m=-1*c}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-u,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-f,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}ut.prototype.isMatrix4=!0;const dt=new ot,ft=new ut,mt=new ot(0,0,0),pt=new ot(1,1,1),yt=new ot,gt=new ot,vt=new ot,xt=new ut,wt=new rt;class bt{constructor(t=0,e=0,i=0,s=bt.DEFAULT_ORDER){this._x=t,this._y=e,this._z=i,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new bt(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,n=s[0],r=s[4],o=s[8],a=s[1],h=s[5],l=s[9],c=s[2],u=s[6],d=s[10];switch(e){case"XYZ":this._y=Math.asin(E(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(u,h),this._z=0);break;case"YXZ":this._x=Math.asin(-E(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin(E(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-r,h)):(this._y=0,this._z=Math.atan2(a,n));break;case"ZYX":this._y=Math.asin(-E(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(a,n)):(this._x=0,this._z=Math.atan2(-r,h));break;case"YZX":this._z=Math.asin(E(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-E(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(u,h),this._y=Math.atan2(o,n)):(this._x=Math.atan2(-l,d),this._y=0);break;default:console.warn("../math.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return xt.makeRotationFromQuaternion(t),this.setFromRotationMatrix(xt,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return wt.setFromEuler(this),this.setFromQuaternion(wt,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(t){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}bt.DEFAULT_ORDER="XYZ",bt.prototype.isEuler=!0;class St{constructor(t,e,i,s,n,r,o,a,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,o,a,h)}set(t,e,i,s,n,r,o,a,h){const l=this.elements;return l[0]=t,l[1]=s,l[2]=o,l[3]=e,l[4]=n,l[5]=a,l[6]=i,l[7]=r,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[3],a=i[6],h=i[1],l=i[4],c=i[7],u=i[2],d=i[5],f=i[8],m=s[0],p=s[3],y=s[6],g=s[1],v=s[4],x=s[7],w=s[2],b=s[5],S=s[8];return n[0]=r*m+o*g+a*w,n[3]=r*p+o*v+a*b,n[6]=r*y+o*x+a*S,n[1]=h*m+l*g+c*w,n[4]=h*p+l*v+c*b,n[7]=h*y+l*x+c*S,n[2]=u*m+d*g+f*w,n[5]=u*p+d*v+f*b,n[8]=u*y+d*x+f*S,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*r*l-e*o*h-i*n*l+i*o*a+s*n*h-s*r*a}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=l*r-o*h,u=o*a-l*n,d=h*n-r*a,f=e*c+i*u+s*d;if(0===f)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return t[0]=c*m,t[1]=(s*h-l*i)*m,t[2]=(o*i-s*r)*m,t[3]=u*m,t[4]=(l*e-s*a)*m,t[5]=(s*n-o*e)*m,t[6]=d*m,t[7]=(i*a-h*e)*m,t[8]=(r*e-i*n)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,n,r,o){const a=Math.cos(n),h=Math.sin(n);return this.set(i*a,i*h,-i*(a*r+h*o)+r+t,-s*h,s*a,-s*(-h*r+a*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(Mt.makeScale(t,e)),this}rotate(t){return this.premultiply(Mt.makeRotation(-t)),this}translate(t,e){return this.premultiply(Mt.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new St).fromArray(this.elements)}}St.prototype.isMatrix3=!0;const Mt=new St,zt=new Float32Array(4);class _t extends rt{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Vt=_t.prototype;Vt.data=zt,Vt.offset=0,Object.defineProperties(_t.prototype,{_x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},_y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},_z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},_w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class At{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new At(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(E(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*i-r*s+t.x,this.y=n*s+r*i+t.y,this}random(){return this.x=A(),this.y=A(),this}*[Symbol.iterator](){yield this.x,yield this.y}}At.isVector2=!0;const Tt=new Float32Array(3);class Ot extends ot{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const $t=Ot.prototype;$t.data=Tt,$t.offset=0,Object.defineProperties(Ot.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}}});class Pt{constructor(t=0,e=0,i=0,s=1){this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new Pt(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s+r[12]*n,this.y=r[1]*e+r[5]*i+r[9]*s+r[13]*n,this.z=r[2]*e+r[6]*i+r[10]*s+r[14]*n,this.w=r[3]*e+r[7]*i+r[11]*s+r[15]*n,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,n;const r=.01,o=.1,a=t.elements,h=a[0],l=a[4],c=a[8],u=a[1],d=a[5],f=a[9],m=a[2],p=a[6],y=a[10];if(Math.abs(l-u)<r&&Math.abs(c-m)<r&&Math.abs(f-p)<r){if(Math.abs(l+u)<o&&Math.abs(c+m)<o&&Math.abs(f+p)<o&&Math.abs(h+d+y-3)<o)return this.set(1,0,0,0),this;e=Math.PI;const t=(h+1)/2,a=(d+1)/2,g=(y+1)/2,v=(l+u)/4,x=(c+m)/4,w=(f+p)/4;return t>a&&t>g?t<r?(i=0,s=.707106781,n=.707106781):(i=Math.sqrt(t),s=v/i,n=x/i):a>g?a<r?(i=.707106781,s=0,n=.707106781):(s=Math.sqrt(a),i=v/s,n=w/s):g<r?(i=.707106781,s=.707106781,n=0):(n=Math.sqrt(g),i=x/n,s=w/n),this.set(i,s,n,e),this}let g=Math.sqrt((p-f)*(p-f)+(c-m)*(c-m)+(u-l)*(u-l));return Math.abs(g)<.001&&(g=1),this.x=(p-f)/g,this.y=(c-m)/g,this.z=(u-l)/g,this.w=Math.acos((h+d+y-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}random(){return this.x=A(),this.y=A(),this.z=A(),this.w=A(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}Pt.prototype.isVector4=!0;const Ct=new Float32Array(4);class Ft extends Pt{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const It=Ft.prototype;let Ut;function Bt(t){Ut=t}function Et(){return Ut}It.data=Ct,It.offset=0,Object.defineProperties(Ft.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class Nt{constructor(t,e){this.resolver=t,this.bounce=e,this.type="ApplyCollision",this.tempV=new ot}initialize(t){}update(t,e){const i=this.resolver??Ut;void 0!==i&&i.resolve(t.position,this.tempV)&&t.velocity.reflect(this.tempV).multiplyScalar(this.bounce)}frameUpdate(t){}toJSON(){return{type:this.type,bounce:this.bounce}}static fromJSON(t){return new Nt(void 0,"number"==typeof t.bounce?t.bounce:1)}clone(){return new Nt(this.resolver,this.bounce)}reset(){}}const Dt=t=>({r:t.x,g:t.y,b:t.z,a:t.w}),kt=t=>new Pt(t.r,t.g,t.b,t.a),Rt=(t,e)=>{switch(e){case"Vector3":return new ot(t.x,t.y,t.z);case"Vector4":return new Pt(t.x,t.y,t.z,t.w);case"Color":return new ot(t.r,t.g,t.b);default:return t}},Lt=(t,e)=>{switch(e){case"Vector3":return{x:t.x,y:t.y,z:t.z};case"Vector4":return{x:t.x,y:t.y,z:t.z,w:t.w};case"Color":return{r:t.x,g:t.y,b:t.z};default:return t}},qt=t=>{console.warn(`[quarks] ${t}`)},Jt=(t,e)=>Array.isArray(t)?new ot(t[0]??e.x,t[1]??e.y,t[2]??e.z):e,Wt=(t,e)=>{const i=e?.type;return null==e?`Missing ${t}`:void 0===i?`${t[0].toUpperCase()}${t.slice(1)} without a type`:`Unknown ${t} ${JSON.stringify(i)}`};class Qt{constructor(t){this.value=t,this.type="value"}startGen(t){}genValue(t){return this.value}toJSON(){return{type:"ConstantValue",value:this.value}}static fromJSON(t){return new Qt(t.value)}clone(){return new Qt(this.value)}}class Gt{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(A())}genValue(t){return-1===this.indexCount&&this.startGen(t),nt.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new Gt(t.a,t.b)}clone(){return new Gt(this.a,this.b)}}class jt{constructor(t,e,i,s){this.p=[t,e,i,s]}genValue(t){const e=this.p,i=t*t,s=1-t,n=s*s;return e[0]*n*s+e[1]*n*t*3+e[2]*s*i*3+e[3]*i*t}derivativeCoefficients(t){const e=[];for(let i=t,s=i.length-1;s>0;s--){const t=[];for(let e=0;e<s;e++){const n=s*(i[e+1]-i[e]);t.push(n)}e.push(t),i=t}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],i=1-t,s=i*t*2,n=t*t;return i*i*e[0]+s*e[1]+n*e[2]}controlCurve(t,e){this.p[1]=t/3+this.p[0],this.p[2]=this.p[3]-e/3}hull(t){let e,i=this.p,s=[],n=0,r=0,o=0;const a=[];for(a[n++]=i[0],a[n++]=i[1],a[n++]=i[2],a[n++]=i[3];i.length>1;){for(s=[],r=0,o=i.length-1;r<o;r++)e=t*i[r]+(1-t)*i[r+1],a[n++]=e,s.push(e);i=s}return a}split(t){const e=this.hull(t);return{left:new jt(e[0],e[4],e[7],e[9]),right:new jt(e[9],e[8],e[6],e[3]),span:e}}clone(){return new jt(this.p[0],this.p[1],this.p[2],this.p[3])}toJSON(){return{p0:this.p[0],p1:this.p[1],p2:this.p[2],p3:this.p[3]}}static fromJSON(t){return new jt(t.p0,t.p1,t.p2,t.p3)}}class Yt{constructor(){this.functions=new Array}findFunction(t){const e=this.functions,i=e.length-1;if(i<=0)return 0===i&&t>=e[0][1]&&t<=1?0:-1;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;return-1}getStartX(t){return this.functions[t][1]}setStartX(t,e){t>0&&(this.functions[t][1]=e)}getEndX(t){return t+1<this.functions.length?this.functions[t+1][1]:1}setEndX(t,e){t+1<this.functions.length&&(this.functions[t+1][1]=e)}insertFunction(t,e){const i=this.findFunction(t);this.functions.splice(i+1,0,[e,t])}removeFunction(t){return this.functions.splice(t,1)[0][0]}getFunction(t){return this.functions[t][0]}setFunction(t,e){this.functions[t][0]=e}get numOfFunctions(){return this.functions.length}}class Ht extends Yt{constructor(t=[[new jt(0,1/3,1/3*2,1),0]]){super(),this.table=null,this.tableSignature=null,this.type="function",this.functions=t}refreshTable(){const t=this.functions,e=t.length;if(0===e)return this.table=null,void(this.tableSignature=null);const i=5*e;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));for(let i=0,r=0;i<e;i++,r+=5){const e=t[i][0].p,o=t[i][1];n||(n=s[r]!==e[0]||s[r+1]!==e[1]||s[r+2]!==e[2]||s[r+3]!==e[3]||s[r+4]!==o),n&&(s[r]=e[0],s[r+1]=e[1],s[r+2]=e[2],s[r+3]=e[3],s[r+4]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const r=Ht.TABLE_SIZE,o=null!==this.table&&this.table.length===r?this.table:new Float32Array(r),a=1/(r-1);for(let t=0;t<r;t++)o[t]=this.genValueExact(t*a);this.table=o}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genValue(t,e=0){const i=this.table;if(null!==i){const t=i.length-1;if(e<=0)return i[0];if(e>=1)return i[t];const s=e*t,n=0|s,r=s-n,o=i[n];return o+(i[n+1]-o)*r}return this.genValueExact(e)}genValueExact(t){const e=this.functions,i=e.length;if(0===i)return 0;const s=this.findFunction(t);if(-1===s)return t<e[0][1]?e[0][0].genValue(0):e[i-1][0].genValue(1);const n=e[s][1],r=(s+1<i?e[s+1][1]:1)-n;return e[s][0].genValue(r>0?(t-n)/r:0)}toSVG(t,e){if(e<1)return"";let i=["M",0,this.functions[0][0].p[0]].join(" ");for(let s=1/e;s<=1;s+=1/e)i=[i,"L",s*t,this.genValue(void 0,s)].join(" ");return i}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new Ht(t.functions.map(t=>[jt.fromJSON(t.function),t.start]))}clone(){return new Ht(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}function Xt(t){switch(t?.type){case"ConstantValue":return Qt.fromJSON(t);case"IntervalValue":return Gt.fromJSON(t);case"PiecewiseBezier":return Ht.fromJSON(t);default:return qt(`${Wt("value generator",t)}; using 0.`),new Qt(0)}}Ht.TABLE_SIZE=257;class Zt{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,i,s){return e.setFromAxisAngle(this.axis,this.angle.genValue(t,s)*i)}toJSON(){return{type:"AxisAngle",axis:{x:this.axis.x,y:this.axis.y,z:this.axis.z},angle:this.angle.toJSON()}}static fromJSON(t){return new Zt(new ot(t.axis.x,t.axis.y,t.axis.z),Xt(t.angle))}clone(){return new Zt(this.axis.clone(),this.angle.clone())}}class Kt{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(A())}genColor(t,e){return-1===this.indexCount&&this.startGen(t),e.copy(this.a).lerp(this.b,t[this.indexCount])}toJSON(){return{type:"ColorRange",a:Dt(this.a),b:Dt(this.b)}}static fromJSON(t){return new Kt(kt(t.a),kt(t.b))}clone(){return new Kt(this.a.clone(),this.b.clone())}}class te{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){const e=this.keys,i=e.length-1;if(i<0||t<e[0][1])return-1;if(t>=e[i][1])return i;if(1===i)return 0;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;return-1}getStartX(t){return this.keys[t][1]}getEndX(t){return t+1<this.keys.length?this.keys[t+1][1]:1}genValue(t,e){const i=this.keys,s=this.findKey(e),n=i.length-1;if("Number"===this.subType){if(-1===s)return i[0][0];if(s>=n)return i[n][0];const t=i[s][1],r=i[s][0],o=i[s+1][1]-t;return(i[s+1][0]-r)*(o>0?(e-t)/o:0)+r}{if(-1===s)return t.copy(i[0][0]);if(s>=n)return t.copy(i[n][0]);const r=i[s][1],o=i[s+1][1]-r;return t.copy(i[s][0]).lerp(i[s+1][0],o>0?(e-r)/o:0)}}toJSON(){return{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:Lt(t,this.subType),pos:e}))}}static fromJSON(t){return new te(t.keys.map(e=>[Rt(e.value,t.subType),e.pos]),t.subType)}clone(){return"Number"===this.subType?new te(this.keys.map(([t,e])=>[t,e]),this.subType):new te(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const ee=new Pt;class ie{constructor(t=[[new ot(0,0,0),0],[new ot(1,1,1),0]],e=[[1,0],[1,1]]){this.table=null,this.tableSignature=null,this.type="function",this.color=new te(t,"Color"),this.alpha=new te(e,"Number")}refreshTable(){const t=this.color.keys,e=this.alpha.keys,i=4*t.length+2*e.length;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));let r=0;for(let e=0;e<t.length;e++,r+=4){const i=t[e][0],o=t[e][1];n||(n=s[r]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+3]!==o),n&&(s[r]=i.x,s[r+1]=i.y,s[r+2]=i.z,s[r+3]=o)}for(let t=0;t<e.length;t++,r+=2){const i=e[t][0],o=e[t][1];n||(n=s[r]!==i||s[r+1]!==o),n&&(s[r]=i,s[r+1]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const o=ie.TABLE_SIZE,a=null!==this.table&&this.table.length===4*o?this.table:new Float32Array(4*o),h=1/(o-1),l=ee;for(let t=0;t<o;t++){this.genColorExact(l,t*h);const e=4*t;a[e]=l.x,a[e+1]=l.y,a[e+2]=l.z,a[e+3]=l.w}this.table=a}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genColor(t,e,i){const s=this.table;if(null!==s){const t=ie.TABLE_SIZE-1;if(i<=0)return e.x=s[0],e.y=s[1],e.z=s[2],e.w=s[3],e;if(i>=1){const i=4*t;return e.x=s[i],e.y=s[i+1],e.z=s[i+2],e.w=s[i+3],e}const n=i*t,r=0|n,o=n-r,a=4*r,h=a+4;return e.x=s[a]+(s[h]-s[a])*o,e.y=s[a+1]+(s[h+1]-s[a+1])*o,e.z=s[a+2]+(s[h+2]-s[a+2])*o,e.w=s[a+3]+(s[h+3]-s[a+3])*o,e}return this.genColorExact(e,i)}genColorExact(t,e){const i=this.color.keys,s=i.length-1,n=this.color.findKey(e);let r,o,a;if(-1===n||n>=s){const t=i[-1===n?0:s][0];r=t.x,o=t.y,a=t.z}else{const t=i[n][0],s=i[n+1][0],h=i[n][1],l=i[n+1][1]-h,c=l>0?(e-h)/l:0;r=t.x+(s.x-t.x)*c,o=t.y+(s.y-t.y)*c,a=t.z+(s.z-t.z)*c}const h=this.alpha.keys,l=h.length-1,c=this.alpha.findKey(e);let u;if(-1===c||c>=l)u=h[-1===c?0:l][0];else{const t=h[c][1],i=h[c][0],s=h[c+1][1]-t;u=i+(h[c+1][0]-i)*(s>0?(e-t)/s:0)}return t.x=r,t.y=o,t.z=a,t.w=u,t}toJSON(){return{type:"Gradient",color:this.color.toJSON(),alpha:this.alpha.toJSON()}}static fromJSON(t){if(t.functions){const e=t.functions.map(t=>[Kt.fromJSON(t.function).a,t.start]);return t.functions.length>0&&e.push([Kt.fromJSON(t.functions[t.functions.length-1].function).b,1]),new ie(e.map(t=>[new ot(t[0].x,t[0].y,t[0].z),t[1]]),e.map(t=>[t[0].w,t[1]]))}{const e=new ie;return e.alpha=te.fromJSON(t.alpha),e.color=te.fromJSON(t.color),e}}clone(){const t=new ie;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}ie.TABLE_SIZE=257;class se{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const i=A();return e.copy(this.a).lerp(this.b,i)}toJSON(){return{type:"RandomColor",a:Dt(this.a),b:Dt(this.b)}}static fromJSON(t){return new se(kt(t.a),kt(t.b))}clone(){return new se(this.a.clone(),this.b.clone())}}const ne=new Pt;class re{constructor(t,e){this.indexCount=0,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(A())}genColor(t,e,i){return this.gradient1.genColor(t,e,i),this.gradient2.genColor(t,ne,i),t&&void 0!==t[this.indexCount]?e.lerp(ne,t[this.indexCount]):e.lerp(ne,A()),e}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new re(ie.fromJSON(t.gradient1),ie.fromJSON(t.gradient2))}clone(){return new re(this.gradient1.clone(),this.gradient2.clone())}}class oe{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:Dt(this.color)}}static fromJSON(t){return new oe(kt(t.color))}clone(){return new oe(this.color.clone())}}function ae(t){switch(t?.type){case"ConstantColor":return oe.fromJSON(t);case"ColorRange":return Kt.fromJSON(t);case"RandomColor":return se.fromJSON(t);case"Gradient":return ie.fromJSON(t);case"RandomColorBetweenGradient":return re.fromJSON(t);default:return qt(`${Wt("colour generator",t)}; using white.`),new oe(new Pt(1,1,1,1))}}class he{constructor(t,e,i,s){this.angleX=t,this.angleY=e,this.angleZ=i,this.type="rotation",this.eular=new bt(0,0,0,s)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,i,s){return this.eular.set(this.angleX.genValue(t,s)*i,this.angleY.genValue(t,s)*i,this.angleZ.genValue(t,s)*i),e.setFromEuler(this.eular)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.eular.order}}static fromJSON(t){return new he(Xt(t.angleX),Xt(t.angleY),Xt(t.angleZ),t.eulerOrder)}clone(){return new he(this.angleX.clone(),this.angleY.clone(),this.angleZ.clone(),this.eular.order)}}class le{constructor(){this.indexCount=0,this.type="rotation"}startGen(t){let e,i,s,n,r,o;this.indexCount=t.length;do{e=2*A()-1,i=2*A()-1,s=e*e+i*i}while(s>1);do{n=2*A()-1,r=2*A()-1,o=n*n+r*r}while(o>1);const a=Math.sqrt((1-s)/o);t.push(e,i,a*n,a*r)}genValue(t,e,i,s){-1===this.indexCount&&this.startGen(t);const n=this.indexCount;return e.set(t[n],t[n+1],t[n+2],t[n+3]),e}toJSON(){return{type:"RandomQuat"}}static fromJSON(t){return new le}clone(){return new le}}function ce(t){switch(t?.type){case"AxisAngle":return Zt.fromJSON(t);case"Euler":return he.fromJSON(t);case"RandomQuat":return le.fromJSON(t);default:return qt(`${Wt("rotation generator",t)}; using a random rotation.`),new le}}class ue{constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,i){return e.set(this.x.genValue(t,i),this.y.genValue(t,i),this.z.genValue(t,i))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new ue(Xt(t.x),Xt(t.y),Xt(t.z))}clone(){return new ue(this.x.clone(),this.y.clone(),this.z.clone())}}function de(t){return"Vector3Function"===t?.type?ue.fromJSON(t):(qt(`${Wt("vector generator",t)}; using a zero vector.`),new ue(new Qt(0),new Qt(0),new Qt(0)))}function fe(t){switch(t?.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":return Xt(t);case"AxisAngle":case"RandomQuat":case"Euler":return ce(t);case"Vector3Function":return de(t);default:return qt(`${Wt("generator",t)}; using 0.`),new Qt(0)}}function me(t,e){return"world"===t||"local"===t?t:e}function pe(t){return 0===t?0:1/t}class ye{constructor(){this.position=new ot,this.quaternion=new rt,this.scale=new ot(1,1,1),this.quaternionInverse=new rt,this.scaleInverse=new ot(1,1,1)}refresh(t){t.emitter.matrixWorld.decompose(this.position,this.quaternion,this.scale),this.quaternionInverse.copy(this.quaternion).invert(),this.scaleInverse.set(pe(this.scale.x),pe(this.scale.y),pe(this.scale.z))}toSimulation(t,e,i){return i&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion):i||"world"!==e||t.applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}pointToSimulation(t,e,i){return i&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion).add(this.position):i||"world"!==e||t.sub(this.position).applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}}class ge{constructor(t,e,i="world"){this.direction=t,this.magnitude=e,this.space=i,this.type="ApplyForce",this._frame=new ye,this._direction=new ot,this._direction.copy(t)}initialize(t,e){this.ps=e,this.magnitude.startGen(t.memory)}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const i=this.magnitude.genValue(t.memory)*this._step(e),s=this._direction,n=t.velocity;n.x+=s.x*i,n.y+=s.y*i,n.z+=s.z*i}updateAll(t,e,i){const s=this.magnitude,n=this._direction,r=this._step(i),o=s instanceof Qt,a=o?s.value*r:0;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const h=o?a:s.genValue(e.memory)*r,l=e.velocity;l.x+=n.x*h,l.y+=n.y*h,l.z+=n.z*h}}frameUpdate(t){this._direction.copy(this.direction),void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&(this._frame.refresh(this.ps),this._frame.toSimulation(this._direction,this.space,this.ps.worldSpace))}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new ge(Jt(t.direction,new ot(0,0,0)),Xt(t.magnitude??t.force),me(t.space,"world"))}clone(){return new ge(this.direction.clone(),this.magnitude.clone(),this.space)}reset(){}}class ve{constructor(t=0,e=0,i=new ot){this.scaleX=t,this.scaleY=e,this.position=i,this.locations=[]}transform(t,e){const i=this.locations.length;if(0===i)return;const s=this.locations[e%i];t.x=s.x*this.scaleX+this.position.x,t.y=s.y*this.scaleY+this.position.y,t.z=this.position.z}static fromJSON(t){const e=t.position,i=Array.isArray(e)?new ot(e[0],e[1],e[2]):new ot(e?.x??0,e?.y??0,e?.z??0),s=new ve(t.scaleX??0,t.scaleY??0,i);return s.locations=(t.locations??[]).map(t=>new At(t.x,t.y)),s}clone(){const t=new ve(this.scaleX,this.scaleY,this.position.clone());return t.locations=this.locations.map(t=>t.clone()),t}toJSON(){return{type:"TextureSequencer",scaleX:this.scaleX,scaleY:this.scaleY,position:[this.position.x,this.position.y,this.position.z],locations:this.locations.map(t=>({x:t.x,y:t.y}))}}fromImage(t,e){const i=document.createElement("canvas");i.width=t.width,i.height=t.height;const s=i.getContext("2d");if(!s)return;s.drawImage(t,0,0);const n=s.getImageData(0,0,i.width,i.height,{colorSpace:"srgb"});i.remove(),this.locations.length=0;for(let t=0;t<n.height;t++)for(let i=0;i<n.width;i++)n.data[4*(t*n.width+i)+3]>e&&this.locations.push(new At(i,n.height-t))}}function xe(t){switch(t?.type){case void 0:return null==t?void qt(`${Wt("sequencer",t)}; skipping it.`):ve.fromJSON(t);case"TextureSequencer":return ve.fromJSON(t);default:return void qt(`${Wt("sequencer",t)}; skipping it.`)}}class we{constructor(t){this.type="ApplySequences",this.sequencers=[],this.time=0,this.index=0,this.pCount=0,this.tempV=new ot,this.delay=t}initialize(t){t.id=this.pCount,t.dst=new ot,t.begin=new ot,t.inMotion=!1,this.pCount++}reset(){this.time=0,this.index=0,this.pCount=0}update(t,e){const i=this.sequencers[this.index];if(void 0===i)return;const s=t.id*this.delay;this.time>=i[0].a+s&&this.time<=i[0].b+s?(t.inMotion||(t.inMotion=!0,t.begin.copy(t.position),i[1].transform(t.dst,t.id)),t.position.lerpVectors(t.begin,t.dst,we.BEZIER.genValue((this.time-i[0].a-s)/(i[0].b-i[0].a)))):this.time>i[0].b+s&&(t.inMotion=!1)}frameUpdate(t){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=t}appendSequencer(t,e){this.sequencers.push([t,e])}toJSON(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(([t,e])=>({range:t.toJSON(),sequencer:e.toJSON()}))}}static fromJSON(t){const e=new we("number"==typeof t.delay?t.delay:0);return(Array.isArray(t.sequencers)?t.sequencers:[]).forEach(t=>{const i=xe(t.sequencer);void 0!==i&&e.sequencers.push([Xt(t.range),i])}),e}clone(){const t=new we(this.delay);return t.sequencers=this.sequencers.map(t=>[t[0].clone(),t[1].clone()]),t}}we.BEZIER=new jt(0,0,1,1);class be{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new ot,this._q=new rt,this.memory=[]}initialize(t){const e=t.velocity.length();0!=e&&(t.velocity.normalize(),0===t.velocity.x&&0===t.velocity.y?this._temp.set(0,t.velocity.z,0):this._temp.set(-t.velocity.y,t.velocity.x,0),this.memory.length=0,this.angle.startGen(this.memory),this._q.setFromAxisAngle(this._temp.normalize(),this.angle.genValue(this.memory)),this._temp.copy(t.velocity),t.velocity.applyQuaternion(this._q),this._q.setFromAxisAngle(this._temp,A()*Math.PI*2),t.velocity.applyQuaternion(this._q),t.velocity.setLength(e))}update(t,e){}frameUpdate(t){}toJSON(){return{type:this.type,angle:this.angle.toJSON()}}static fromJSON(t){return new be(Xt(t.angle))}clone(){return new be(this.angle.clone())}reset(){this.memory.length=0}}function Se(t,e){const i=t.velocity.length()*t.speedModifier,s=e.b-e.a;if(0===s)return i>=e.a?1:0;const n=(i-e.a)/s;return n<0?0:n>1?1:n}class Me{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=Se(t,this.speedRange);this.color.genColor(t.memory,t.color,i),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new Me(ae(t.color),t.speedRange?Gt.fromJSON(t.speedRange):new Gt(0,1))}clone(){return new Me(this.color.clone(),this.speedRange.clone())}reset(){}}class ze{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=t.color,s=t.startColor;this.color.genColor(t.memory,i,t.age/t.life),i.x*=s.x,i.y*=s.y,i.z*=s.z,i.w*=s.w}updateAll(t,e,i){const s=this.color;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=e.color,r=e.startColor;s.genColor(e.memory,n,e.age/e.life),n.x*=r.x,n.y*=r.y,n.z*=r.z,n.w*=r.w}}frameUpdate(t){this.color.refreshTable?.()}toJSON(){return{type:this.type,color:this.color.toJSON()}}static fromJSON(t){return new ze(ae(t.color))}clone(){return new ze(this.color.clone())}reset(){}}class _e{constructor(t=64){this.previousVelocity=_e.EMPTY,this.rotationQuaternion=_e.EMPTY,this.angularVelocityQuaternion=_e.EMPTY,this.memory=new Float64Array(0),this.memoryStride=0,this.capacity=Math.max(1,t),this.position=new Float32Array(3*this.capacity),this.previousPosition=new Float32Array(3*this.capacity),this.previousSize=new Float32Array(3*this.capacity),this.previousColor=new Float32Array(4*this.capacity),this.velocity=new Float32Array(3*this.capacity),this.size=new Float32Array(3*this.capacity),this.startSize=new Float32Array(3*this.capacity),this.color=new Float32Array(4*this.capacity),this.startColor=new Float32Array(4*this.capacity),this.scalars=new Float64Array(this.capacity*_e.SCALAR_STRIDE),this.rotation=new Float32Array(this.capacity),this.angularVelocity=new Float32Array(this.capacity),this.uvTile=new Float32Array(this.capacity),this.startSpeed=new Float32Array(this.capacity),this.flip=new Uint8Array(this.capacity)}ensureCapacity(t){if(t<=this.capacity)return!1;let e=this.capacity;for(;e<t;)e*=2;this.position=_e.grow(this.position,3*e),this.previousPosition=_e.grow(this.previousPosition,3*e);const i=this.previousSize===this.size,s=this.previousColor===this.color;if(i||(this.previousSize=_e.grow(this.previousSize,3*e)),this.previousVelocity.length>0&&(this.previousVelocity=_e.grow(this.previousVelocity,3*e)),this.rotationQuaternion.length>0){const t=this.rotationQuaternion.length;this.rotationQuaternion=_e.grow(this.rotationQuaternion,4*e),this.angularVelocityQuaternion=_e.grow(this.angularVelocityQuaternion,4*e);for(let i=t+3;i<4*e;i+=4)this.rotationQuaternion[i]=1,this.angularVelocityQuaternion[i]=1}if(s||(this.previousColor=_e.grow(this.previousColor,4*e)),this.velocity=_e.grow(this.velocity,3*e),this.size=_e.grow(this.size,3*e),this.startSize=_e.grow(this.startSize,3*e),this.color=_e.grow(this.color,4*e),i&&(this.previousSize=this.size),s&&(this.previousColor=this.color),this.startColor=_e.grow(this.startColor,4*e),this.scalars=_e.growDouble(this.scalars,e*_e.SCALAR_STRIDE),this.memoryStride>0){const t=new Float64Array(e*this.memoryStride);t.fill(NaN),t.set(this.memory),this.memory=t}this.rotation=_e.grow(this.rotation,e),this.angularVelocity=_e.grow(this.angularVelocity,e),this.uvTile=_e.grow(this.uvTile,e),this.startSpeed=_e.grow(this.startSpeed,e);const n=new Uint8Array(e);return n.set(this.flip),this.flip=n,this.capacity=e,!0}keepPreviousVelocity(){return!(this.previousVelocity.length>=3*this.capacity)&&(this.previousVelocity=new Float32Array(3*this.capacity),!0)}recordMemory(t,e){const i=e.length;let s=this.memoryStride;if(i>s||this.memory.length<this.capacity*s){s=Math.max(s,i);const t=new Float64Array(this.capacity*s);t.fill(NaN);const e=this.memoryStride,n=this.memory,r=e>0?n.length/e:0;for(let i=0,o=0,a=0;i<r;i++,o+=e,a+=s)for(let i=0;i<e;i++)t[a+i]=n[o+i];this.memory=t,this.memoryStride=s}const n=t*s;for(let t=0;t<s;t++){const s=t<i?e[t]:void 0;this.memory[n+t]="number"==typeof s?s:NaN}}useSizeSnapshot(t){t?this.previousSize===this.size&&(this.previousSize=new Float32Array(this.size)):this.previousSize=this.size}useColorSnapshot(t){t?this.previousColor===this.color&&(this.previousColor=new Float32Array(this.color)):this.previousColor=this.color}ensureQuaternionColumns(){if(this.rotationQuaternion.length>=4*this.capacity)return!1;this.rotationQuaternion=new Float32Array(4*this.capacity),this.angularVelocityQuaternion=new Float32Array(4*this.capacity);for(let t=3;t<this.rotationQuaternion.length;t+=4)this.rotationQuaternion[t]=1,this.angularVelocityQuaternion[t]=1;return!0}swapRows(t,e){if(t===e)return;const i=3*t,s=3*e;_e.swap3(this.position,i,s),_e.swap3(this.previousPosition,i,s),this.previousSize!==this.size&&_e.swap3(this.previousSize,i,s),this.previousVelocity.length>0&&_e.swap3(this.previousVelocity,i,s),_e.swap3(this.velocity,i,s),_e.swap3(this.size,i,s),_e.swap3(this.startSize,i,s);const n=4*t,r=4*e;_e.swap4(this.color,n,r),this.previousColor!==this.color&&_e.swap4(this.previousColor,n,r),_e.swap4(this.startColor,n,r),this.rotationQuaternion.length>0&&(_e.swap4(this.rotationQuaternion,n,r),_e.swap4(this.angularVelocityQuaternion,n,r)),_e.swap3(this.scalars,t*_e.SCALAR_STRIDE,e*_e.SCALAR_STRIDE);const o=this.memoryStride;if(o>0){const i=this.memory;for(let s=0,n=t*o,r=e*o;s<o;s++,n++,r++){const t=i[n];i[n]=i[r],i[r]=t}}_e.swap1(this.rotation,t,e),_e.swap1(this.angularVelocity,t,e),_e.swap1(this.uvTile,t,e),_e.swap1(this.startSpeed,t,e),_e.swap1(this.flip,t,e)}static swap1(t,e,i){const s=t[e];t[e]=t[i],t[i]=s}static growDouble(t,e){const i=new Float64Array(e);return i.set(t),i}static swap3(t,e,i){let s=t[e];t[e]=t[i],t[i]=s,s=t[e+1],t[e+1]=t[i+1],t[i+1]=s,s=t[e+2],t[e+2]=t[i+2],t[i+2]=s}static swap4(t,e,i){_e.swap3(t,e,i);const s=t[e+3];t[e+3]=t[i+3],t[i+3]=s}static grow(t,e){const i=new Float32Array(e);return i.set(t),i}}_e.EMPTY=new Float32Array(0),_e.SCALAR_STRIDE=3,_e.AGE=0,_e.LIFE=1,_e.SPEED_MODIFIER=2;class Ve{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return null!==this.prev}hasNext(){return null!==this.next}}class Ae{constructor(){this.length=0,this.head=this.tail=null}isEmpty(){return null===this.head}clear(){this.length=0,this.head=this.tail=null}front(){return null===this.head?null:this.head.data}back(){return null===this.tail?null:this.tail.data}dequeue(){if(this.head){const t=this.head.data;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,t}}pop(){if(this.tail){const t=this.tail.data;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,t}}queue(t){const e=new Ve(t);this.tail||(this.tail=e),this.head&&(this.head.prev=e,e.next=this.head),this.head=e,this.length++}push(t){const e=new Ve(t);this.head||(this.head=e),this.tail&&(this.tail.next=e,e.prev=this.tail),this.tail=e,this.length++}insertBefore(t,e){const i=new Ve(e);i.next=t,i.prev=t.prev,null!==i.prev&&(i.prev.next=i),i.next.prev=i,t==this.head&&(this.head=i),this.length++}remove(t){if(null===this.head||null===this.tail)return;let e=this.head;for(t===this.head.data&&(this.head=this.head.next),t===this.tail.data&&(this.tail=this.tail.prev);null!==e.next&&e.data!==t;)e=e.next;e.data===t&&(null!==e.prev&&(e.prev.next=e.next),null!==e.next&&(e.next.prev=e.prev),this.length--)}*values(){let t=this.head;for(;null!==t;)yield t.data,t=t.next}}class Te{constructor(){this.position=new ot,this.velocity=new ot,this.age=0,this.life=1,this.size=new ot,this.rotation=0,this.color=new Pt(1,1,1,1),this.uvTile=0,this.memory=[]}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.position.set(0,0,0),this.velocity.set(0,0,0),this.age=0,this.life=1,this.size.set(1,1,1),this.rotation=0,this.color.set(1,1,1,1),this.uvTile=0}}class Oe{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get angularVelocity(){const t=this.angularVelocityQuaternion;return void 0!==t?t:this.store.angularVelocity[this.storeIndex]}set angularVelocity(t){if("number"==typeof t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=t;else if(void 0===t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=0;else{let e=this.angularVelocityQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new _t(this.store.angularVelocityQuaternion,4*this.storeIndex),this.angularVelocityQuaternion=e),e!==t&&e.copy(t)}}get rotation(){const t=this.rotationQuaternion;return void 0!==t?t:this.store.rotation[this.storeIndex]}set rotation(t){if("number"==typeof t)this.rotationQuaternion=void 0,this.store.rotation[this.storeIndex]=t;else{let e=this.rotationQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new _t(this.store.rotationQuaternion,4*this.storeIndex),this.rotationQuaternion=e),e!==t&&e.copy(t)}}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}get flip(){return this.store.flip[this.storeIndex]}set flip(t){this.store.flip[this.storeIndex]=t}constructor(t=new _e(1),e=0){this.rotationQuaternion=void 0,this.angularVelocityQuaternion=void 0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new Ot(t.position,i),this.previousPosition=new Ot(t.previousPosition,i),this.previousVelocity=new Ot(t.previousVelocity,i),this.velocity=new Ot(t.velocity,i),this.size=new Ot(t.size,i),this.startSize=new Ot(t.startSize,i),this.color=new Ft(t.color,s),this.startColor=new Ft(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*_e.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,i=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,i),this.startColor.bind(t.startColor,i),this.rotationQuaternion?.bind(t.rotationQuaternion,i),this.angularVelocityQuaternion?.bind(t.angularVelocityQuaternion,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*_e.SCALAR_STRIDE}get died(){return this.age>=this.life}reset(){this.memory.length=0}}const $e=new Float32Array(0);class Pe{constructor(t,e,i){this.position=t,this.size=e,this.color=i}}class Ce{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get previous(){return this._previous??(this._previous=new Ae)}set previous(t){this._previous=t}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}constructor(t=new _e(1),e=0){this.length=30,this._previous=void 0,this.historyPositions=$e,this.historySizes=$e,this.historyBaseSizes=$e,this.headWidthScale=1,this.historyColors=$e,this.historySides=$e,this.historyAges=$e,this.historyDistances=$e,this.historyCapacity=0,this.historyHead=0,this.historyCount=0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new Ot(t.position,i),this.previousPosition=new Ot(t.previousPosition,i),this.previousVelocity=new Ot(t.previousVelocity,i),this.velocity=new Ot(t.velocity,i),this.size=new Ot(t.size,i),this.startSize=new Ot(t.startSize,i),this.color=new Ft(t.color,s),this.startColor=new Ft(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*_e.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,i=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,i),this.startColor.bind(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*_e.SCALAR_STRIDE}ensureHistoryCapacity(t){this.historyCapacity!==t&&(this.historyCapacity=t,this.historySizes.length<t&&(this.historyPositions=new Float32Array(3*t),this.historySizes=new Float32Array(t),this.historyBaseSizes=new Float32Array(t),this.historyColors=new Float32Array(4*t),this.historyAges=new Float32Array(t),this.historyDistances=new Float32Array(t),this.historySides.length>0&&(this.historySides=new Float32Array(3*t))),this.historyHead=0,this.historyCount=0)}ensureSideHistory(){this.historySides.length<3*this.historyCapacity&&(this.historySides=new Float32Array(3*this.historyCapacity))}resetHistory(){this.historyHead=0,this.historyCount=0}getHistoryIndex(t){const e=this.historyCapacity;return(this.historyHead-this.historyCount+e+t)%e}update(t=!1,e=!0){0===this.historyCapacity&&this.ensureHistoryCapacity(Math.max(1,Math.ceil(this.length)));const i=this.historyCapacity,s=this.store,n=this.storeIndex,r=n*_e.SCALAR_STRIDE,o=s.scalars[r+_e.AGE];if(o>=s.scalars[r+_e.LIFE])return void this.dropOldest();const a=t&&this.historyCount>0,h=a?(this.historyHead+i-1)%i:this.historyHead,l=3*h,c=this.historyPositions,u=s.position,d=3*n;c[l]=u[d],c[l+1]=u[d+1],c[l+2]=u[d+2];const f=s.size[d];this.historyBaseSizes[h]=f,this.historySizes[h]=f*this.headWidthScale;const m=4*h,p=this.historyColors,y=s.color,g=4*n;p[m]=y[g],p[m+1]=y[g+1],p[m+2]=y[g+2],p[m+3]=y[g+3],this.historyAges[h]=o,a||(this.historyHead=(h+1)%i,this.historyCount<i&&this.historyCount++),e&&this.measureHeadDistance()}measureHeadDistance(){const t=this.historyCount;if(0===t)return;const e=this.historyCapacity,i=(this.historyHead+e-1)%e;if(1===t)return void(this.historyDistances[i]=0);const s=(i+e-1)%e,n=this.historyPositions,r=n[3*i]-n[3*s],o=n[3*i+1]-n[3*s+1],a=n[3*i+2]-n[3*s+2];this.historyDistances[i]=this.historyDistances[s]+Math.sqrt(r*r+o*o+a*a)}dropOldest(){this.historyCount>0&&this.historyCount--}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.headWidthScale=1,this.resetHistory()}}function Fe(t,e){return Math.floor(A()*(e-t))+t}const Ie=new ot(0,1,0),Ue=new ot(0,0,0),Be=new ot(1,1,1),Ee=new ot(0,0,1),Ne=1e-6;var De;!function(t){t[t.Death=0]="Death",t[t.Birth=1]="Birth",t[t.Frame=2]="Frame"}(De||(De={}));const ke={color:1,size:2,rotation:4,lifetime:8};function Re(t){let e=0;for(const i of t)e|=ke[i]??0;return e}class Le{constructor(t,e,i,s=De.Frame,n=1,r=[]){this.particleSystem=t,this.useVelocityAsBasis=e,this.subParticleSystem=i,this.mode=s,this.emitProbability=n,this.inherit=r,this.type="EmitSubParticleSystem",this.q_=new rt,this.v_=new ot,this.v2_=new ot,this.v3_=new ot,this.subEmissions=new Array,this.spareEmissions=new Array;const o=this.target;o&&(o.onlyUsedByOther=!0)}initialize(t){}update(t,e){(this.mode===De.Frame||this.mode===De.Birth&&0===t.age||this.mode===De.Death&&t.age+e>=t.life)&&this.emit(t,e)}get target(){const t=this.subParticleSystem;if(null===t||"object"!=typeof t)return;const e=t.system;return e?.isDisposed?void 0:e}emit(t,e){if(!this.target)return;if(A()>this.emitProbability)return;const i=this.spareEmissions.pop(),s=void 0!==i?i:{burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:new ut,travelDistance:0,particle:void 0,serial:void 0,previousWorldPos:void 0};s.burstParticleCount=0,s.burstParticleIndex=0,s.isBursting=!1,s.burstIndex=0,s.burstWaveIndex=0,s.time=0,s.waitEmiting=0,s.travelDistance=0,this.mode===De.Death?(s.particle=Le.copyInto(s.ghost??(s.ghost=new Oe),t),s.serial=void 0):(s.particle=t,s.serial=t.serial),s.inherit=Re(this.inherit),this.mode===De.Death&&(s.inherit&=~ke.lifetime),s.previousWorldPos=void 0,this.setMatrixFromParticle(s.matrix,t),this.subEmissions.push(s)}frameUpdate(t){const e=this.target;if(e)for(let i=0;i<this.subEmissions.length;i++)if(this.subEmissions[i].time>=e.duration){const t=this.subEmissions[i];t.particle=void 0,t.matrix=new ut,this.spareEmissions.push(t),this.subEmissions[i]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,i--}else{const s=this.subEmissions[i],n=s.particle;void 0!==n&&n===s.ghost||(void 0!==n&&n.age<n.life&&n.serial===s.serial?this.setMatrixFromParticle(s.matrix,n):s.particle=void 0),e.emit(t,s,s.matrix)}else this.clearEmissions()}toJSON(){return{type:this.type,subParticleSystem:"string"==typeof this.subParticleSystem?this.subParticleSystem:this.subParticleSystem?this.subParticleSystem.uuid:"",useVelocityAsBasis:this.useVelocityAsBasis,mode:this.mode,emitProbability:this.emitProbability,...this.inherit.length>0?{inherit:this.inherit.slice()}:{}}}static fromJSON(t,e){return new Le(e,t.useVelocityAsBasis,t.subParticleSystem,t.mode,t.emitProbability,Le.validInherit(t.inherit))}clone(){return new Le(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability,this.inherit.slice())}reset(){}clearEmissions(){for(const t of this.subEmissions)t.particle=void 0,this.spareEmissions.push(t);this.subEmissions.length=0}static copyInto(t,e){return t.position.copy(e.position),t.velocity.copy(e.velocity),t.color.copy(e.color),t.size.copy(e.size),t.rotation=e.rotation??0,t.age=e.age,t.life=e.life,t}static validInherit(t){return Array.isArray(t)?t.filter(t=>t in ke):[]}setMatrixFromParticle(t,e){let i;if(void 0===e.rotation||this.useVelocityAsBasis){const i=e.position,s=this.v3_.copy(e.velocity),n=s.length(),r=this.v_,o=this.v2_;if(n<Ne)r.set(1,0,0),o.set(0,1,0),s.set(0,0,1);else if(s.divideScalar(n),Math.abs(s.x)<Ne&&Math.abs(s.y)<Ne){const t=s.z>0?1:-1;r.set(1,0,0),o.set(0,t,0),s.set(0,0,t)}else r.copy(Ee).cross(s).normalize(),o.copy(s).cross(r);t.set(r.x,o.x,s.x,i.x,r.y,o.y,s.y,i.y,r.z,o.z,s.z,i.z,0,0,0,1)}else e.rotation instanceof rt?i=e.rotation:(this.q_.setFromAxisAngle(Ee,e.rotation),i=this.q_),t.compose(e.position,i,Be);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}class qe{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,i,s="world"){this.x=t,this.y=e,this.z=i,this.space=s,this.type="ForceOverLife",this._temp=new ot,this._frame=new ye}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const i=t.age/t.life;this._temp.set(this.x.genValue(t.memory,i),this.y.genValue(t.memory,i),this.z.genValue(t.memory,i));const s=void 0===this.ps||this.ps.worldSpace;this._frame.toSimulation(this._temp,this.space,s),t.velocity.addScaledVector(this._temp,this._step(e))}updateAll(t,e,i){const s=this._temp,n=this.x,r=this.y,o=this.z,a=this._frame,h=this.space,l=void 0===this.ps||this.ps.worldSpace,c=l!==("world"===h),u=this._step(i);for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const d=e.memory,f=e.age/e.life;s.set(n.genValue(d,f),r.genValue(d,f),o.genValue(d,f)),c&&a.toSimulation(s,h,l),e.velocity.addScaledVector(s,u)}}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new qe(Xt(t.x),Xt(t.y),Xt(t.z),me(t.space,"world"))}frameUpdate(t){void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&this._frame.refresh(this.ps)}clone(){return new qe(this.x.clone(),this.y.clone(),this.z.clone(),this.space)}reset(){}}class Je{constructor(t,e={}){this.type="FrameOverLife",this.salt=new Gt(0,1),this.frame=t,this.fps=e.fps??0,this.cycles=e.cycles??1,this.frameCount=e.frameCount??0,this.loop=e.loop??!0,this.random=e.random??!1,this.startFrame=e.startFrame}get frame(){return this._frame}set frame(t){this._frame=t}isPlain(){return!(this.fps>0)&&1===this.cycles&&void 0===this.startFrame}initialize(t){this._frame.startGen(t.memory),this.startFrame?.startGen(t.memory),this.salt.startGen(t.memory)}update(t,e){t.uvTile=this.frameAt(t,t.age,t.age/t.life)}updateAll(t,e,i){for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.uvTile=this.frameAt(e,e.age,e.age/e.life))}}frameAt(t,e,i){if(this.fps>0){const s=this.sampleFrame(t,i),n=this.frameCount;let r=Math.floor(e*this.fps)+this.offset(t);return this.random&&n>0?s+Math.floor(Je.hash(r,this.saltOf(t))*n):(n>0&&(r=this.loop?Je.wrap(r,n):Math.min(r,n-1)),s+r)}let s;if(1!==this.cycles&&this.cycles>0){const e=i*this.cycles;s=this.sampleFrame(t,i>=1?1:e-Math.floor(e))}else s=this.sampleFrame(t,i);return void 0!==this.startFrame&&(s+=this.offset(t),this.frameCount>0&&(s=Je.wrap(s,this.frameCount))),s}offset(t){return void 0!==this.startFrame?Math.floor(this.startFrame.genValue(t.memory)):0}saltOf(t){const e=t.memory[this.salt.indexCount];return"number"==typeof e?e:0}static hash(t,e){const i=43758.5453*Math.sin(12.9898*t+7833.233*e);return Math.min(i-Math.floor(i),.999999)}static wrap(t,e){return(t%e+e)%e}sampleFrame(t,e){return"function"===this._frame.type?this._frame.genValue(t.memory,e):this._frame.genValue(t.memory)}frameUpdate(t){this._frame.refreshTable?.()}toJSON(){return{type:this.type,frame:this.frame.toJSON(),...this.fps>0?{fps:this.fps}:{},...1!==this.cycles?{cycles:this.cycles}:{},...this.frameCount>0?{frameCount:this.frameCount}:{},...this.loop?{}:{loop:!1},...this.random?{random:!0}:{},...void 0!==this.startFrame?{startFrame:this.startFrame.toJSON()}:{}}}static fromJSON(t){return new Je(Xt(t.frame),{fps:"number"==typeof t.fps?t.fps:void 0,cycles:"number"==typeof t.cycles?t.cycles:void 0,frameCount:"number"==typeof t.frameCount?t.frameCount:void 0,loop:"boolean"==typeof t.loop?t.loop:void 0,random:!0===t.random,startFrame:void 0!==t.startFrame?Xt(t.startFrame):void 0})}clone(){return new Je(this.frame.clone(),{fps:this.fps,cycles:this.cycles,frameCount:this.frameCount,loop:this.loop,random:this.random,startFrame:this.startFrame?.clone()})}reset(){}}class We{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new ot}initialize(t){}update(t,e){const i=t.position.distanceToSquared(this.center);0!==i&&(this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/i*e))}updateAll(t,e,i){const s=this.center.x,n=this.center.y,r=this.center.z,o=this.magnitude*i;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const a=e.position,h=s-a.x,l=n-a.y,c=r-a.z,u=h*h+l*l+c*c;if(0===u)continue;const d=o/(u*Math.sqrt(u)),f=e.velocity;f.x+=h*d,f.y+=l*d,f.z+=c*d}}frameUpdate(t){}toJSON(){return{type:this.type,center:[this.center.x,this.center.y,this.center.z],magnitude:this.magnitude}}static fromJSON(t){return new We(Jt(t.center,new ot(0,0,0)),"number"==typeof t.magnitude?t.magnitude:0)}clone(){return new We(this.center.clone(),this.magnitude)}reset(){}}class Qe{constructor(t=new Qt(1),e="initial"){this.multiplier=t,this.mode=e,this.type="InheritVelocity",this._temp=new ot,this._tempPos=new ot,this._tempQInv=new rt,this._tempScaleInv=new ot(1,1,1)}initialize(t,e){this.ps=e,this.multiplier.startGen(t.memory),"initial"===this.mode&&e.emitterVelocity&&(this._temp.copy(e.emitterVelocity),e.worldSpace||(this.decomposeInverse(e),this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv)),t.velocity.addScaledVector(this._temp,this.multiplier.genValue(t.memory,0)))}frameUpdate(t){this.ps&&!this.ps.worldSpace&&this.decomposeInverse(this.ps)}update(t,e){"current"===this.mode&&void 0!==this.ps&&this.ps.emitterVelocity&&(this._temp.copy(this.ps.emitterVelocity),this.ps.worldSpace||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,this.multiplier.genValue(t.memory,t.age/t.life)*e))}decomposeInverse(t){t.emitter.matrixWorld.decompose(this._tempPos,this._tempQInv,this._tempScaleInv),this._tempQInv.invert(),this._tempScaleInv.set(1/this._tempScaleInv.x,1/this._tempScaleInv.y,1/this._tempScaleInv.z)}toJSON(){return{type:this.type,multiplier:this.multiplier.toJSON(),mode:this.mode}}static fromJSON(t){return new Qe(t.multiplier?Xt(t.multiplier):new Qt(1),"current"===t.mode?"current":"initial")}clone(){return new Qe(this.multiplier.clone(),this.mode)}reset(){}}class Ge{initialize(t,e){void 0!==e&&(this.ps=e),this.speed.startGen(t.memory)}motionScale(){const t=this.ps;return void 0!==t&&t.worldSpace?t.motionScale??1:1}constructor(t,e){this.speed=t,this.dampen=e,this.type="LimitSpeedOverLife"}dampenStep(t){const e=this.dampen>1?1:this.dampen>0?this.dampen:0;return 1-Math.pow(1-e/3,60*t)}update(t,e){const i=t.velocity.length(),s=this.speed.genValue(t.memory,t.age/t.life)*this.motionScale();if(i>s){const n=(i-s)/i;t.velocity.multiplyScalar(1-n*this.dampenStep(e))}}updateAll(t,e,i){const s=this.speed,n=this.dampenStep(i),r=this.motionScale();for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const o=e.velocity,a=o.length(),h=s.genValue(e.memory,e.age/e.life)*r;a>h&&o.multiplyScalar(1-(a-h)/a*n)}}toJSON(){return{type:this.type,speed:this.speed.toJSON(),dampen:this.dampen}}static fromJSON(t){return new Ge(Xt(t.speed),"number"==typeof t.dampen?t.dampen:1)}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Ge(this.speed.clone(),this.dampen)}reset(){}}const je=.5*(Math.sqrt(3)-1),Ye=(3-Math.sqrt(3))/6,He=1/3,Xe=1/6,Ze=(Math.sqrt(5)-1)/4,Ke=(5-Math.sqrt(5))/20,ti=new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),ei=new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);class ii{constructor(t=e){const e="function"==typeof t?t:function(t){let e=0,i=0,s=0,n=1;const r=function(){let t=4022871197;return function(e){e=e.toString();for(let i=0;i<e.length;i++){t+=e.charCodeAt(i);let s=.02519603282416938*t;t=s>>>0,s-=t,s*=t,t=s>>>0,s-=t,t+=4294967296*s}return 2.3283064365386963e-10*(t>>>0)}}();e=r(" "),i=r(" "),s=r(" "),e-=r(t),e<0&&(e+=1);i-=r(t),i<0&&(i+=1);s-=r(t),s<0&&(s+=1);return function(){const t=2091639*e+2.3283064365386963e-10*n;return e=i,i=s,s=t-(n=0|t)}}(t);this.p=function(t){const e=new Uint8Array(256);for(let t=0;t<256;t++)e[t]=t;for(let i=0;i<255;i++){const s=i+~~(t()*(256-i)),n=e[i];e[i]=e[s],e[s]=n}return e}(e),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(let t=0;t<512;t++)this.perm[t]=this.p[255&t],this.permMod12[t]=this.perm[t]%12}noise2D(t,e){const i=this.permMod12,s=this.perm;let n=0,r=0,o=0;const a=(t+e)*je,h=Math.floor(t+a),l=Math.floor(e+a),c=(h+l)*Ye,u=t-(h-c),d=e-(l-c);let f,m;u>d?(f=1,m=0):(f=0,m=1);const p=u-f+Ye,y=d-m+Ye,g=u-1+2*Ye,v=d-1+2*Ye,x=255&h,w=255&l;let b=.5-u*u-d*d;if(b>=0){const t=3*i[x+s[w]];b*=b,n=b*b*(ti[t]*u+ti[t+1]*d)}let S=.5-p*p-y*y;if(S>=0){const t=3*i[x+f+s[w+m]];S*=S,r=S*S*(ti[t]*p+ti[t+1]*y)}let M=.5-g*g-v*v;if(M>=0){const t=3*i[x+1+s[w+1]];M*=M,o=M*M*(ti[t]*g+ti[t+1]*v)}return 70*(n+r+o)}noise3D(t,e,i){const s=this.permMod12,n=this.perm;let r,o,a,h;const l=(t+e+i)*He,c=Math.floor(t+l),u=Math.floor(e+l),d=Math.floor(i+l),f=(c+u+d)*Xe,m=t-(c-f),p=e-(u-f),y=i-(d-f);let g,v,x,w,b,S;m>=p?p>=y?(g=1,v=0,x=0,w=1,b=1,S=0):m>=y?(g=1,v=0,x=0,w=1,b=0,S=1):(g=0,v=0,x=1,w=1,b=0,S=1):p<y?(g=0,v=0,x=1,w=0,b=1,S=1):m<y?(g=0,v=1,x=0,w=0,b=1,S=1):(g=0,v=1,x=0,w=1,b=1,S=0);const M=m-g+Xe,z=p-v+Xe,_=y-x+Xe,V=m-w+2*Xe,A=p-b+2*Xe,T=y-S+2*Xe,O=m-1+.5,$=p-1+.5,P=y-1+.5,C=255&c,F=255&u,I=255&d;let U=.6-m*m-p*p-y*y;if(U<0)r=0;else{const t=3*s[C+n[F+n[I]]];U*=U,r=U*U*(ti[t]*m+ti[t+1]*p+ti[t+2]*y)}let B=.6-M*M-z*z-_*_;if(B<0)o=0;else{const t=3*s[C+g+n[F+v+n[I+x]]];B*=B,o=B*B*(ti[t]*M+ti[t+1]*z+ti[t+2]*_)}let E=.6-V*V-A*A-T*T;if(E<0)a=0;else{const t=3*s[C+w+n[F+b+n[I+S]]];E*=E,a=E*E*(ti[t]*V+ti[t+1]*A+ti[t+2]*T)}let N=.6-O*O-$*$-P*P;if(N<0)h=0;else{const t=3*s[C+1+n[F+1+n[I+1]]];N*=N,h=N*N*(ti[t]*O+ti[t+1]*$+ti[t+2]*P)}return 32*(r+o+a+h)}noise4D(t,e,i,s){const n=this.perm;let r,o,a,h,l;const c=(t+e+i+s)*Ze,u=Math.floor(t+c),d=Math.floor(e+c),f=Math.floor(i+c),m=Math.floor(s+c),p=(u+d+f+m)*Ke,y=t-(u-p),g=e-(d-p),v=i-(f-p),x=s-(m-p);let w=0,b=0,S=0,M=0;y>g?w++:b++,y>v?w++:S++,y>x?w++:M++,g>v?b++:S++,g>x?b++:M++,v>x?S++:M++;const z=w>=3?1:0,_=b>=3?1:0,V=S>=3?1:0,A=M>=3?1:0,T=w>=2?1:0,O=b>=2?1:0,$=S>=2?1:0,P=M>=2?1:0,C=w>=1?1:0,F=b>=1?1:0,I=S>=1?1:0,U=M>=1?1:0,B=y-z+Ke,E=g-_+Ke,N=v-V+Ke,D=x-A+Ke,k=y-T+2*Ke,R=g-O+2*Ke,L=v-$+2*Ke,q=x-P+2*Ke,J=y-C+3*Ke,W=g-F+3*Ke,Q=v-I+3*Ke,G=x-U+3*Ke,j=y-1+4*Ke,Y=g-1+4*Ke,H=v-1+4*Ke,X=x-1+4*Ke,Z=255&u,K=255&d,tt=255&f,et=255&m;let it=.6-y*y-g*g-v*v-x*x;if(it<0)r=0;else{const t=n[Z+n[K+n[tt+n[et]]]]%32*4;it*=it,r=it*it*(ei[t]*y+ei[t+1]*g+ei[t+2]*v+ei[t+3]*x)}let st=.6-B*B-E*E-N*N-D*D;if(st<0)o=0;else{const t=n[Z+z+n[K+_+n[tt+V+n[et+A]]]]%32*4;st*=st,o=st*st*(ei[t]*B+ei[t+1]*E+ei[t+2]*N+ei[t+3]*D)}let nt=.6-k*k-R*R-L*L-q*q;if(nt<0)a=0;else{const t=n[Z+T+n[K+O+n[tt+$+n[et+P]]]]%32*4;nt*=nt,a=nt*nt*(ei[t]*k+ei[t+1]*R+ei[t+2]*L+ei[t+3]*q)}let rt=.6-J*J-W*W-Q*Q-G*G;if(rt<0)h=0;else{const t=n[Z+C+n[K+F+n[tt+I+n[et+U]]]]%32*4;rt*=rt,h=rt*rt*(ei[t]*J+ei[t+1]*W+ei[t+2]*Q+ei[t+3]*G)}let ot=.6-j*j-Y*Y-H*H-X*X;if(ot<0)l=0;else{const t=n[Z+1+n[K+1+n[tt+1+n[et+1]]]]%32*4;ot*=ot,l=ot*ot*(ei[t]*j+ei[t+1]*Y+ei[t+2]*H+ei[t+3]*X)}return 27*(r+o+a+h+l)}}const si=100,ni=new Array(si),ri=new ot,oi=new rt;function ai(t){let e=ni[t];return void 0===e&&(e=new ii(t),ni[t]=e),e}class hi{constructor(t,e,i=new Qt(1),s=new Qt(0),n=new Qt(0),r){this.frequency=t,this.power=e,this.positionAmount=i,this.rotationAmount=s,this.scrollSpeed=n,this.remap=r,this.type="Noise",this.duration=0,this.scrollOffset=0,this.scrollMemory=[],this._frequency=NaN,this._power=NaN,this._positionAmount=NaN,this._rotationAmount=NaN,this.scrollSpeed.startGen(this.scrollMemory)}sample(t,e,i){const s=t.noise2D(0,e),n=this.remap;return void 0===n?s:n.genValue(i,.5*(s+1))}initialize(t){const e="number"==typeof t.rotation;let i=t._noiseState;if(void 0===i)return i={lastPos:new ot,lastRot:0,lastRotQ:e?null:new rt,generatorX:ai(Fe(0,si)),generatorY:ai(Fe(0,si)),generatorZ:ai(Fe(0,si)),generatorW:ai(Fe(0,si))},void(t._noiseState=i);i.lastPos.set(0,0,0),i.lastRot=0,e?i.lastRotQ=null:null===i.lastRotQ?i.lastRotQ=new rt:i.lastRotQ.set(0,0,0,1),i.generatorX=ai(Fe(0,si)),i.generatorY=ai(Fe(0,si)),i.generatorZ=ai(Fe(0,si)),i.generatorW=ai(Fe(0,si))}static constantOf(t){return t instanceof Qt?t.value:NaN}rotateByNoise(t,e,i,s,n){const r=e.lastRotQ;t.multiply(r.invert()),ri.set(this.sample(e.generatorX,i,n),this.sample(e.generatorY,i,n),this.sample(e.generatorZ,i,n));const o=ri.length();o>0?(ri.multiplyScalar(1/o),oi.setFromAxisAngle(ri,this.sample(e.generatorW,i,n)*Math.PI*s)):oi.set(0,0,0,1),t.multiply(oi),r.copy(oi)}update(t,e){const i=t._noiseState;if(void 0===i)return;const s=t.memory,n=t.age/t.life,r=this._frequency,o=r==r?r:this.frequency.genValue(s,n),a=this._power,h=a==a?a:this.power.genValue(s,n),l=this._positionAmount,c=l==l?l:this.positionAmount.genValue(s,n),u=this._rotationAmount,d=u==u?u:this.rotationAmount.genValue(s,n),f=t.age*o+this.scrollOffset;if(c>0){const e=h*c;t.position.sub(i.lastPos),ri.set(this.sample(i.generatorX,f,s)*e,this.sample(i.generatorY,f,s)*e,this.sample(i.generatorZ,f,s)*e),t.position.add(ri),i.lastPos.copy(ri)}if(d>0){const e=h*d;if("number"==typeof t.rotation){const n=this.sample(i.generatorW,f,s)*Math.PI*e;t.rotation=t.rotation-i.lastRot+n,i.lastRot=n}else null!==i.lastRotQ&&this.rotateByNoise(t.rotation,i,f,e,s)}}updateAll(t,e,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.rotation,o=s.scalars,a=_e.SCALAR_STRIDE,h=this._frequency,l=this._power,c=this._positionAmount,u=this._rotationAmount;for(let i=0,s=0,d=0;i<e;i++,s+=3,d+=a){const e=o[d],a=o[d+1];if(e>=a)continue;const f=t[i],m=f._noiseState;if(void 0===m)continue;const p=f.memory,y=e/a,g=h==h?h:this.frequency.genValue(p,y),v=l==l?l:this.power.genValue(p,y),x=c==c?c:this.positionAmount.genValue(p,y),w=u==u?u:this.rotationAmount.genValue(p,y),b=e*g+this.scrollOffset;if(x>0){const t=v*x,e=m.lastPos,i=this.sample(m.generatorX,b,p)*t,r=this.sample(m.generatorY,b,p)*t,o=this.sample(m.generatorZ,b,p)*t;n[s]=Math.fround(n[s]-e.x)+i,n[s+1]=Math.fround(n[s+1]-e.y)+r,n[s+2]=Math.fround(n[s+2]-e.z)+o,e.set(i,r,o)}if(w>0){const t=v*w;if("number"==typeof f.rotation){const e=this.sample(m.generatorW,b,p)*Math.PI*t;r[i]=r[i]-m.lastRot+e,m.lastRot=e}else null!==m.lastRotQ&&this.rotateByNoise(f.rotation,m,b,t,p)}}}toJSON(){return{type:this.type,frequency:this.frequency.toJSON(),power:this.power.toJSON(),positionAmount:this.positionAmount.toJSON(),rotationAmount:this.rotationAmount.toJSON(),scrollSpeed:this.scrollSpeed.toJSON(),...void 0!==this.remap?{remap:this.remap.toJSON()}:{}}}frameUpdate(t){this.duration+=t,this.scrollOffset+=this.scrollSpeed.genValue(this.scrollMemory,0)*t,this._frequency=hi.constantOf(this.frequency),this._power=hi.constantOf(this.power),this._positionAmount=hi.constantOf(this.positionAmount),this._rotationAmount=hi.constantOf(this.rotationAmount)}static fromJSON(t){return new hi(Xt(t.frequency),Xt(t.power),t.positionAmount?Xt(t.positionAmount):void 0,t.rotationAmount?Xt(t.rotationAmount):void 0,t.scrollSpeed?Xt(t.scrollSpeed):new Qt(0),t.remap?Xt(t.remap):void 0)}clone(){return new hi(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone(),this.scrollSpeed.clone(),this.remap?.clone())}reset(){this.scrollOffset=0}}class li{constructor(t,e=new ot(0,1,0),i="local"){this.orbitSpeed=t,this.axis=e,this.space=i,this.type="OrbitOverLife",this.temp=new ot,this._frame=new ye,this._axis=new ot(0,1,0),this._center=new ot,this.rotation=new rt,this.refreshAxis()}initialize(t,e){this.ps=e,this.orbitSpeed.startGen(t.memory)}refreshAxis(){const t=this._axis.copy(this.axis),e=this._center.set(0,0,0);if(void 0!==this.ps){const i=this.ps.worldSpace;this._frame.toSimulation(t,this.space,i),this._frame.pointToSimulation(e,this.space,i)}const i=t.length();i>0?t.multiplyScalar(1/i):t.set(0,0,0)}converts(){return void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)}update(t,e){const i=this._axis;if(0===i.x&&0===i.y&&0===i.z)return;const s=t.position;s.sub(this._center),this.temp.copy(s).projectOnVector(i),this.rotation.setFromAxisAngle(i,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),s.sub(this.temp),s.applyQuaternion(this.rotation),s.add(this.temp),s.add(this._center)}updateAll(t,e,i){const s=this._axis;if(0===s.x&&0===s.y&&0===s.z)return;const n=this.orbitSpeed,r=this._center,o=this.temp,a=this.rotation;for(let h=0;h<e;h++){const e=t[h];if(e.age>=e.life)continue;const l=e.position;l.sub(r),o.copy(l).projectOnVector(s),a.setFromAxisAngle(s,n.genValue(e.memory,e.age/e.life)*i),l.sub(o),l.applyQuaternion(a),l.add(o),l.add(r)}}frameUpdate(t){this.converts()&&this._frame.refresh(this.ps),this.refreshAxis()}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z],..."local"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new li(Xt(t.orbitSpeed),t.axis?new ot(t.axis[0],t.axis[1],t.axis[2]):void 0,me(t.space,"local"))}clone(){return new li(this.orbitSpeed.clone(),this.axis.clone(),this.space)}reset(){}}class ci{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new rt}initialize(t){t.rotation instanceof rt&&(t.angularVelocity=new rt,this.angularVelocity.startGen(t.memory))}update(t,e){if(t.rotation instanceof rt){this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat);const i=t.angularVelocity;i instanceof rt&&i.copy(this.tempQuat)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new ci(ce(t.angularVelocity))}frameUpdate(t){}clone(){return new ci(this.angularVelocity.clone())}reset(){}}class ui{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new rt}initialize(t){"number"==typeof t.rotation&&this.angularVelocity.startGen(t.memory)}update(t,e){if("number"==typeof t.rotation){const i=Se(t,this.speedRange),s=this.angularVelocity.genValue(t.memory,i);t.rotation+=e*s,t.angularVelocity=s}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new ui(Xt(t.angularVelocity),t.speedRange?Gt.fromJSON(t.speedRange):new Gt(0,1))}frameUpdate(t){}clone(){return new ui(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class di{constructor(t){this.angularVelocity=t,this.type="RotationOverLife",this.tempQuat=new rt}initialize(t){"number"==typeof t.rotation?this.angularVelocity.startGen(t.memory):t.rotation instanceof rt&&(this.angularVelocity.startGen(t.memory),t.angularVelocity instanceof rt||(t.angularVelocity=new rt))}update(t,e){if("number"==typeof t.rotation){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);t.rotation+=e*i,t.angularVelocity=i}else if(t.rotation instanceof rt){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);this.turnAboutZ(t,t.rotation,i*e)}}updateAll(t,e,i){const s=this.angularVelocity;for(let n=0;n<e;n++){const e=t[n];if(e.age>=e.life)continue;const r=e.rotation;if("number"==typeof r){const t=s.genValue(e.memory,e.age/e.life);e.rotation=r+i*t,e.angularVelocity=t}else if(r instanceof rt){const t=s.genValue(e.memory,e.age/e.life);this.turnAboutZ(e,r,t*i)}}}turnAboutZ(t,e,i){const s=this.tempQuat.setFromAxisAngle(Ee,i);e.multiply(s);const n=t.angularVelocity;n instanceof rt&&n.copy(s)}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new di(Xt(t.angularVelocity))}frameUpdate(t){this.angularVelocity.refreshTable?.()}clone(){return new di(this.angularVelocity.clone())}reset(){}}class fi{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=Se(t,this.speedRange);this.size instanceof ue?this.size.genValue(t.memory,t.size,e).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,e))}toJSON(){return{type:this.type,size:this.size.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new fi(fe(t.size),t.speedRange?Gt.fromJSON(t.speedRange):new Gt(0,1))}frameUpdate(t){}clone(){return new fi(this.size.clone(),this.speedRange.clone())}reset(){}}class mi{constructor(t){this.type="SizeOverLife",this._sizeIsVector3=!1,this.size=t}get size(){return this._size}set size(t){this._size=t,this._sizeIsVector3=t instanceof ue}initialize(t){this._size.startGen(t.memory)}update(t){const e=t.age/t.life;if(this._sizeIsVector3)this._size.genValue(t.memory,t.size,e).multiply(t.startSize);else{const i=this._size.genValue(t.memory,e),s=t.size,n=t.startSize;s.x=n.x*i,s.y=n.y*i,s.z=n.z*i}}updateAll(t,e,i){if(this._sizeIsVector3){const i=this._size;for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||i.genValue(e.memory,e.size,e.age/e.life).multiply(e.startSize)}return}const s=this._size;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=s.genValue(e.memory,e.age/e.life),r=e.size,o=e.startSize;r.x=o.x*n,r.y=o.y*n,r.z=o.z*n}}toJSON(){return{type:this.type,size:this.size.toJSON()}}static fromJSON(t){return new mi(fe(t.size))}frameUpdate(t){this._size.refreshTable?.()}clone(){return new mi(this.size.clone())}reset(){}}class pi{initialize(t){this.speed.startGen(t.memory)}constructor(t){this.speed=t,this.type="SpeedOverLife"}update(t){t.speedModifier=this.speed.genValue(t.memory,t.age/t.life)}updateAll(t,e,i){const s=this.speed;for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.speedModifier=s.genValue(e.memory,e.age/e.life))}}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new pi(Xt(t.speed))}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new pi(this.speed.clone())}reset(){}}function yi(t){return 0===t?0:1/t}class gi{constructor(t,e,i,s,n=0){this.scale=t,this.octaves=e,this.velocityMultiplier=i,this.timeScale=s,this.seed=n,this.type="TurbulenceField",this.timeOffset=new ot,this.initialOffset=new ot,this.temp=new ot,this.temp2=new ot;const r=$(n);this.generator=new ii(r),this.initialOffset.set(r()*yi(t.x)*s.x,r()*yi(t.y)*s.y,r()*yi(t.z)*s.z),this.timeOffset.copy(this.initialOffset)}initialize(t){}update(t,e){const i=t.position.x*yi(this.scale.x),s=t.position.y*yi(this.scale.y),n=t.position.z*yi(this.scale.z);this.temp.set(0,0,0);let r=1;for(let t=0;t<this.octaves;t++)this.temp2.set(this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.x*r)/r,this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.y*r)/r,this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.z*r)/r),this.temp.add(this.temp2),r*=2;this.temp.multiply(this.velocityMultiplier),t.velocity.addScaledVector(this.temp,e)}updateAll(t,e,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.velocity,o=s.scalars,a=_e.SCALAR_STRIDE,h=this.generator,l=this.octaves,c=yi(this.scale.x),u=yi(this.scale.y),d=yi(this.scale.z),f=this.velocityMultiplier.x*i,m=this.velocityMultiplier.y*i,p=this.velocityMultiplier.z*i,y=this.timeOffset.x,g=this.timeOffset.y,v=this.timeOffset.z;for(let t=0,i=0,s=0;t<e;t++,i+=3,s+=a){if(o[s]>=o[s+1])continue;const t=n[i]*c,e=n[i+1]*u,a=n[i+2]*d;let x=0,w=0,b=0,S=1;for(let i=0;i<l;i++){const i=t*S,s=e*S,n=a*S;x+=h.noise4D(i,s,n,y*S)/S,w+=h.noise4D(i,s,n,g*S)/S,b+=h.noise4D(i,s,n,v*S)/S,S*=2}r[i]+=x*f,r[i+1]+=w*m,r[i+2]+=b*p}}toJSON(){return{type:this.type,scale:[this.scale.x,this.scale.y,this.scale.z],octaves:this.octaves,velocityMultiplier:[this.velocityMultiplier.x,this.velocityMultiplier.y,this.velocityMultiplier.z],timeScale:[this.timeScale.x,this.timeScale.y,this.timeScale.z],...0!==this.seed?{seed:this.seed}:{}}}frameUpdate(t){this.timeOffset.x+=t*this.timeScale.x,this.timeOffset.y+=t*this.timeScale.y,this.timeOffset.z+=t*this.timeScale.z}static fromJSON(t){return new gi(Jt(t.scale,new ot(1,1,1)),"number"==typeof t.octaves?t.octaves:1,Jt(t.velocityMultiplier,new ot(1,1,1)),Jt(t.timeScale,new ot(1,1,1)),"number"==typeof t.seed?t.seed:0)}clone(){return new gi(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone(),this.seed)}reset(){this.timeOffset.copy(this.initialOffset)}}const vi=new ot(1,0,0),xi=new ot(0,1,0),wi=new ot(0,0,1);class bi{constructor(t=new Qt(0),e=new Qt(0),i=new Qt(0),s=new Qt(0),n=new Qt(0),r=new Qt(0),o="local",a=new Qt(0),h=new ot){this.linearX=t,this.linearY=e,this.linearZ=i,this.orbitalX=s,this.orbitalY=n,this.orbitalZ=r,this.space=o,this.radial=a,this.orbitalOffset=h,this.type="VelocityOverLife",this._temp=new ot,this._tempEmitterPos=new ot,this._tempQ=new rt,this._tempQInv=new rt,this._tempScale=new ot(1,1,1),this._tempScaleInv=new ot(1,1,1),this._tempRot=new rt,this._axisX=new ot(1,0,0),this._axisY=new ot(0,1,0),this._axisZ=new ot(0,0,1),this._center=new ot}initialize(t,e){this.ps=e,this.linearX.startGen(t.memory),this.linearY.startGen(t.memory),this.linearZ.startGen(t.memory),this.orbitalX.startGen(t.memory),this.orbitalY.startGen(t.memory),this.orbitalZ.startGen(t.memory),this.radial.startGen(t.memory)}frameUpdate(t){this.ps&&(this.ps.emitter.matrixWorld.decompose(this._tempEmitterPos,this._tempQ,this._tempScale),this._tempQInv.copy(this._tempQ).invert(),this._tempScaleInv.set(1/this._tempScale.x,1/this._tempScale.y,1/this._tempScale.z),this._axisX.copy(vi),this._axisY.copy(xi),this._axisZ.copy(wi),this._center.copy(this.orbitalOffset),this.ps.worldSpace&&(this._axisX.applyQuaternion(this._tempQ),this._axisY.applyQuaternion(this._tempQ),this._axisZ.applyQuaternion(this._tempQ),this._center.multiply(this._tempScale).applyQuaternion(this._tempQ).add(this._tempEmitterPos)))}update(t,e){const i=t.age/t.life;this._temp.set(this.linearX.genValue(t.memory,i),this.linearY.genValue(t.memory,i),this.linearZ.genValue(t.memory,i));const s=void 0!==this.ps&&this.ps.worldSpace;s&&"local"===this.space?this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ):s||"world"!==this.space||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,e);const n=this.radial.genValue(t.memory,i);if(0!==n){this._temp.copy(t.position).sub(this._center);const i=this._temp.length();i>0&&t.position.addScaledVector(this._temp,n*e/i)}const r=this.orbitalX.genValue(t.memory,i)*e,o=this.orbitalY.genValue(t.memory,i)*e,a=this.orbitalZ.genValue(t.memory,i)*e;0===r&&0===o&&0===a||(t.position.sub(this._center),this.orbit(t.position,this._axisX,r),this.orbit(t.position,this._axisY,o),this.orbit(t.position,this._axisZ,a),t.position.add(this._center))}orbit(t,e,i){0!==i&&(this._tempRot.setFromAxisAngle(e,i),t.applyQuaternion(this._tempRot))}toJSON(){return{type:this.type,linearX:this.linearX.toJSON(),linearY:this.linearY.toJSON(),linearZ:this.linearZ.toJSON(),orbitalX:this.orbitalX.toJSON(),orbitalY:this.orbitalY.toJSON(),orbitalZ:this.orbitalZ.toJSON(),space:this.space,radial:this.radial.toJSON(),orbitalOffset:[this.orbitalOffset.x,this.orbitalOffset.y,this.orbitalOffset.z]}}static fromJSON(t){const e=t=>t?Xt(t):new Qt(0);return new bi(e(t.linearX),e(t.linearY),e(t.linearZ),e(t.orbitalX),e(t.orbitalY),e(t.orbitalZ),"world"===t.space?"world":"local",e(t.radial),Array.isArray(t.orbitalOffset)?new ot(t.orbitalOffset[0]??0,t.orbitalOffset[1]??0,t.orbitalOffset[2]??0):new ot)}clone(){return new bi(this.linearX.clone(),this.linearY.clone(),this.linearZ.clone(),this.orbitalX.clone(),this.orbitalY.clone(),this.orbitalZ.clone(),this.space,this.radial.clone(),this.orbitalOffset.clone())}reset(){}}class Si{initialize(t){this.width.startGen(t.memory)}constructor(t,e=!1){this.width=t,this.absolute=e,this.type="WidthOverLength"}update(t){if(!(t instanceof Ce))return;const e=t.memory;t.headWidthScale=this.absolute?1:this.width.genValue(e,0);const i=t.historyCount;if(0===i)return;const s=t.historyCapacity,n=t.historySizes,r=t.historyBaseSizes,o=1/i,a=this.absolute;let h=t.getHistoryIndex(0);for(let t=0;t<i;t++){const l=this.width.genValue(e,(i-t)*o);n[h]=a?l:r[h]*l,h++,h===s&&(h=0)}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON(),absolute:this.absolute}}static fromJSON(t){return new Si(Xt(t.width),t.absolute??!0)}clone(){return new Si(this.width.clone(),this.absolute)}reset(){}}const Mi={ApplyForce:{type:"ApplyForce",constructor:ge,params:[["direction",["vec3"]],["magnitude",["value"]],["space",["string"]]],loadJSON:ge.fromJSON},Noise:{type:"Noise",constructor:hi,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]],["scrollSpeed",["value"]],["remap",["valueFunc"]]],loadJSON:hi.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:gi,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]],["seed",["number"]]],loadJSON:gi.fromJSON},GravityForce:{type:"GravityForce",constructor:We,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:We.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:ze,params:[["color",["colorFunc"]]],loadJSON:ze.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:di,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:di.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:ci,params:[["angularVelocity",["rotationFunc"]]],loadJSON:ci.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:mi,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:mi.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:Me,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:Me.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:ui,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:ui.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:fi,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:fi.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:pi,params:[["speed",["value","valueFunc"]]],loadJSON:pi.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:Je,params:[["frame",["value","valueFunc"]],["fps",["number"]],["cycles",["number"]],["frameCount",["number"]],["loop",["boolean"]],["random",["boolean"]],["startFrame",["value"]]],loadJSON:Je.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:qe,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]],["space",["string"]]],loadJSON:qe.fromJSON},VelocityOverLife:{type:"VelocityOverLife",constructor:bi,params:[["linearX",["value","valueFunc"]],["linearY",["value","valueFunc"]],["linearZ",["value","valueFunc"]],["orbitalX",["value","valueFunc"]],["orbitalY",["value","valueFunc"]],["orbitalZ",["value","valueFunc"]],["space",["string"]],["radial",["value","valueFunc"]],["orbitalOffset",["vec3"]]],loadJSON:bi.fromJSON},InheritVelocity:{type:"InheritVelocity",constructor:Qe,params:[["multiplier",["value","valueFunc"]],["mode",["string"]]],loadJSON:Qe.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:li,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]],["space",["string"]]],loadJSON:li.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:Si,params:[["width",["value","valueFunc"]],["absolute",["boolean"]]],loadJSON:Si.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:be,params:[["angle",["value"]]],loadJSON:be.fromJSON},ApplySequences:{type:"ApplySequences",constructor:we,params:[["delay",["number"]]],loadJSON:we.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:Le,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]]],loadJSON:Le.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:Ge,params:[["speed",["value","valueFunc"]],["dampen",["number"]]],loadJSON:Ge.fromJSON},ApplyCollision:{type:"ApplyCollision",constructor:Nt,params:[["bounce",["number"]]],loadJSON:Nt.fromJSON}};function zi(t,e){const i=t?Mi[t.type]:void 0;return i?i.loadJSON(t,e):(qt(`${Wt("behavior",t)}; it is skipped.`),null)}const _i={PiecewiseBezier:Ht,Vector3Function:ue,Quaternion:rt,ConstantValue:Qt,Gradient:ie,Vector4View:Ft,AxisAngleGenerator:Zt,IntervalValue:Gt,ColorRange:Kt};function Vi(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.PiecewiseBezier ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length - 1 : 0;\n const ${t}_const = ${t} instanceof deps.ConstantValue;\n const ${t}_cv = ${t}_const ? ${t}.value : 0;\n const ${t}_iv = ${t} instanceof deps.IntervalValue;\n const ${t}_slot = ${t}_iv ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n const ${t}_a = ${t}_iv ? ${t}.a : 0, ${t}_b = ${t}_iv ? ${t}.b : 0;`}function Ai(t){return`const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz) * scalars[s + 2];\n let ts = span${t} === 0 ? (speed >= lo${t} ? 1 : 0) : (speed - lo${t}) / span${t};\n ts = ts < 0 ? 0 : ts > 1 ? 1 : ts;`}function Ti(t,e,i){return`let ${e};\n if (${t}_tbl !== null) {\n const tt = ${i};\n if (tt <= 0) ${e} = ${t}_tbl[0];\n else if (tt >= 1) ${e} = ${t}_tbl[${t}_last];\n else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const v0 = ${t}_tbl[ix];\n ${e} = v0 + (${t}_tbl[ix + 1] - v0) * (x - ix);\n }\n } else if (${t}_const) ${e} = ${t}_cv;\n else if (${t}_iv) {\n // The particle's own sample, from the memory column when it holds it.\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n ${e} = (1 - r) * ${t}_a + r * ${t}_b;\n } else ${e} = ${t}.genValue(p.memory, ${i});`}function Oi(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.Gradient ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length / 4 - 1 : 0;\n const ${t}_cr = ${t} instanceof deps.ColorRange;\n const ${t}_slot = ${t}_cr ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n // Rounded to float32 as copying the colour into the particle does.\n const ${t}_ax = ${t}_cr ? Math.fround(${t}.a.x) : 0, ${t}_ay = ${t}_cr ? Math.fround(${t}.a.y) : 0;\n const ${t}_az = ${t}_cr ? Math.fround(${t}.a.z) : 0, ${t}_aw = ${t}_cr ? Math.fround(${t}.a.w) : 0;\n const ${t}_bx = ${t}_cr ? ${t}.b.x : 0, ${t}_by = ${t}_cr ? ${t}.b.y : 0;\n const ${t}_bz = ${t}_cr ? ${t}.b.z : 0, ${t}_bw = ${t}_cr ? ${t}.b.w : 0;`}function $i(t,e){return`if (${t}_tbl !== null) {\n const tt = ${e};\n const tbl = ${t}_tbl;\n let r, g, b, a;\n if (tt <= 0) {\n r = tbl[0]; g = tbl[1]; b = tbl[2]; a = tbl[3];\n } else if (tt >= 1) {\n const o = ${t}_last * 4;\n r = tbl[o]; g = tbl[o + 1]; b = tbl[o + 2]; a = tbl[o + 3];\n } else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const fr = x - ix;\n const o = ix * 4;\n const nx = o + 4;\n r = tbl[o] + (tbl[nx] - tbl[o]) * fr;\n g = tbl[o + 1] + (tbl[nx + 1] - tbl[o + 1]) * fr;\n b = tbl[o + 2] + (tbl[nx + 2] - tbl[o + 2]) * fr;\n a = tbl[o + 3] + (tbl[nx + 3] - tbl[o + 3]) * fr;\n }\n color[o4] = Math.fround(r) * startColor[o4];\n color[o4 + 1] = Math.fround(g) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(b) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(a) * startColor[o4 + 3];\n } else if (${t}_cr) {\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n color[o4] = Math.fround(${t}_ax + (${t}_bx - ${t}_ax) * r) * startColor[o4];\n color[o4 + 1] = Math.fround(${t}_ay + (${t}_by - ${t}_ay) * r) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(${t}_az + (${t}_bz - ${t}_az) * r) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(${t}_aw + (${t}_bw - ${t}_aw) * r) * startColor[o4 + 3];\n } else {\n ${t}.genColor(p.memory, tmpColor, ${e});\n color[o4] = tmpColor.x * startColor[o4];\n color[o4 + 1] = tmpColor.y * startColor[o4 + 1];\n color[o4 + 2] = tmpColor.z * startColor[o4 + 2];\n color[o4 + 3] = tmpColor.w * startColor[o4 + 3];\n }`}function Pi(t,e,i,s,n,r,o){return`{\n const cx = 2 * (${n} * ${i} - ${r} * ${e});\n const cy = 2 * (${r} * ${t} - ${s} * ${i});\n const cz = 2 * (${s} * ${e} - ${n} * ${t});\n const nx = ${t} + ${o} * cx + ${n} * cz - ${r} * cy;\n const ny = ${e} + ${o} * cy + ${r} * cx - ${s} * cz;\n ${i} = ${i} + ${o} * cz + ${s} * cy - ${n} * cx;\n ${t} = nx;\n ${e} = ny;\n }`}function Ci(t,e){return`const ${t}_q = ${e};\n const ${t}x = ${t}_q.x, ${t}y = ${t}_q.y, ${t}z = ${t}_q.z, ${t}w = ${t}_q.w;`}function Fi(t,e){return`const ${t}_v = ${e};\n const ${t}x = ${t}_v.x, ${t}y = ${t}_v.y, ${t}z = ${t}_v.z;`}function Ii(t,e,i,s){return`{\n const half = ${t} / 2;\n const sn = Math.sin(half);\n const qx = ${e} * sn, qy = ${i} * sn, qz = ${s} * sn, qw = Math.cos(half);\n ${Pi("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(px); py = Math.fround(py); pz = Math.fround(pz);\n }`}function Ui(t,e){switch(t.type){case"ColorOverLife":return{setup:Oi(`g${e}`,`behaviors[${e}].color`),body:`{${$i(`g${e}`,"t")}}`};case"SizeOverLife":return{setup:`const g${e} = behaviors[${e}].size;\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Vi(`sg${e}`,`g${e}`)}`,body:`if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, t).multiply(p.startSize);\n } else {\n ${Ti(`sg${e}`,"v","t")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }`};case"ApplyForce":return{setup:`const b${e} = behaviors[${e}];\n const d${e} = b${e}._direction;\n const dx${e} = d${e}.x, dy${e} = d${e}.y, dz${e} = d${e}.z;\n const step${e} = b${e}._step(delta);\n ${Vi(`g${e}`,`b${e}.magnitude`)}`,body:`{\n ${Ti(`g${e}`,"m","t")}\n const s = m * step${e};\n vel[o3] += dx${e} * s; vel[o3 + 1] += dy${e} * s; vel[o3 + 2] += dz${e} * s;\n }`};case"RotationOverLife":return{setup:`${Vi(`g${e}`,`behaviors[${e}].angularVelocity`)}\n const rotation_${e} = count > 0 ? particles[0].rotation : undefined;\n const angle_${e} = typeof rotation_${e} === 'number';\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = !angle_${e} && rq${e}.length > 0 && rotation_${e} instanceof deps.Quaternion;`,body:`if (angle_${e}) {\n ${Ti(`g${e}`,"rate","t")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n } else if (quat_${e}) {\n ${Ti(`g${e}`,"rate","t")}\n const half = (rate * delta) / 2;\n const qz = Math.sin(half), qw = Math.cos(half);\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + ay * qz;\n rq${e}[o4 + 1] = ay * qw - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz;\n rq${e}[o4 + 3] = aw * qw - az * qz;\n aq${e}[o4] = 0; aq${e}[o4 + 1] = 0; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"FrameOverLife":return{setup:`${Vi(`g${e}`,`behaviors[${e}].frame`)}\n const b${e} = behaviors[${e}];\n const plain${e} = typeof b${e}.isPlain !== 'function' || b${e}.isPlain();`,body:`if (plain${e}) {${Ti(`g${e}`,"v","t")} uvTile[row] = v;}\n else uvTile[row] = b${e}.frameAt(p, age, t);`};case"SpeedOverLife":return{setup:Vi(`g${e}`,`behaviors[${e}].speed`),body:`{${Ti(`g${e}`,"v","t")} scalars[s + 2] = v;}`};case"ForceOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Vi(`gx${e}`,`b${e}.x`)}\n ${Vi(`gy${e}`,`b${e}.y`)}\n ${Vi(`gz${e}`,`b${e}.z`)}\n const world${e} = b${e}.ps === undefined || b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const toLocal${e} = !world${e} && b${e}.space === 'world';\n const step${e} = b${e}._step(delta);\n const fr${e} = b${e}._frame;\n ${Fi(`sc${e}`,`toWorld${e} ? fr${e}.scale : fr${e}.scaleInverse`)}\n ${Ci(`q${e}`,`toWorld${e} ? fr${e}.quaternion : fr${e}.quaternionInverse`)}`,body:`{\n ${Ti(`gx${e}`,"fx","t")}\n ${Ti(`gy${e}`,"fy","t")}\n ${Ti(`gz${e}`,"fz","t")}\n if (toWorld${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${Pi("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n } else if (toLocal${e}) {\n ${Pi("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n }\n vel[o3] += fx * step${e}; vel[o3 + 1] += fy * step${e}; vel[o3 + 2] += fz * step${e};}`};case"LimitSpeedOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Vi(`g${e}`,`b${e}.speed`)}\n const dampen${e} = b${e}.dampenStep(delta);\n const ms${e} = typeof b${e}.motionScale === 'function' ? b${e}.motionScale() : 1;`,body:`{const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz);\n ${Ti(`g${e}`,"limitBase","t")}\n const limit = limitBase * ms${e};\n if (speed > limit) {\n const f = 1 - ((speed - limit) / speed) * dampen${e};\n vel[o3] = vx * f; vel[o3 + 1] = vy * f; vel[o3 + 2] = vz * f;\n }}`};case"GravityForce":return{setup:`const b${e} = behaviors[${e}];\n const cx${e} = b${e}.center.x, cy${e} = b${e}.center.y, cz${e} = b${e}.center.z;\n const gm${e} = b${e}.magnitude * delta;`,body:`{const dx = cx${e} - pos[o3], dy = cy${e} - pos[o3 + 1], dz = cz${e} - pos[o3 + 2];\n const d2 = dx * dx + dy * dy + dz * dz;\n if (d2 > 0) {\n const f = gm${e} / (d2 * Math.sqrt(d2));\n vel[o3] += dx * f; vel[o3 + 1] += dy * f; vel[o3 + 2] += dz * f;\n }}`};case"ColorBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${Oi(`g${e}`,`b${e}.color`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};`,body:`{${Ai(e)}\n ${$i(`g${e}`,"ts")}}`};case"SizeBySpeed":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.size;\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Vi(`sg${e}`,`g${e}`)}`,body:`{${Ai(e)}\n if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, ts).multiply(p.startSize);\n } else {\n ${Ti(`sg${e}`,"v","ts")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }}`};case"RotationBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${Vi(`g${e}`,`b${e}.angularVelocity`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const angle_${e} = count > 0 && typeof particles[0].rotation === 'number';`,body:`if (angle_${e}) {\n ${Ai(e)}\n ${Ti(`g${e}`,"rate","ts")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n }`};case"OrbitOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Vi(`g${e}`,`b${e}.orbitSpeed`)}\n ${Fi(`ax${e}`,`b${e}._axis`)}\n ${Fi(`c${e}`,`b${e}._center`)}\n const alen${e} = ax${e}x * ax${e}x + ax${e}y * ax${e}y + ax${e}z * ax${e}z;\n const orbit${e} = alen${e} !== 0;\n const chalf${e} = (g${e}_cv * delta) / 2;\n const csn${e} = Math.sin(chalf${e});\n const cqx${e} = ax${e}x * csn${e}, cqy${e} = ax${e}y * csn${e}, cqz${e} = ax${e}z * csn${e};\n const cqw${e} = Math.cos(chalf${e});`,body:`if (orbit${e}) {\n let px = Math.fround(pos[o3] - c${e}x), py = Math.fround(pos[o3 + 1] - c${e}y), pz = Math.fround(pos[o3 + 2] - c${e}z);\n // Divided by the squared length as projectOnVector does, so the bits match.\n const f = (ax${e}x * px + ax${e}y * py + ax${e}z * pz) / alen${e};\n const tx = ax${e}x * f, ty = ax${e}y * f, tz = ax${e}z * f;\n let qx, qy, qz, qw;\n if (g${e}_const) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n ${Ti(`g${e}`,"sp","t")}\n const half = (sp * delta) / 2;\n const sn = Math.sin(half);\n qx = ax${e}x * sn; qy = ax${e}y * sn; qz = ax${e}z * sn; qw = Math.cos(half);\n }\n px = Math.fround(px - tx); py = Math.fround(py - ty); pz = Math.fround(pz - tz);\n ${Pi("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(Math.fround(px) + tx); py = Math.fround(Math.fround(py) + ty); pz = Math.fround(Math.fround(pz) + tz);\n pos[o3] = px + c${e}x;\n pos[o3 + 1] = py + c${e}y;\n pos[o3 + 2] = pz + c${e}z;}`};case"Rotation3DOverLife":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.angularVelocity;\n const q${e} = b${e}.tempQuat;\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = rq${e}.length > 0 && count > 0 && particles[0].rotation instanceof deps.Quaternion;\n const fixed_${e} = g${e} instanceof deps.AxisAngleGenerator && g${e}.angle instanceof deps.ConstantValue;\n let cqx${e} = 0, cqy${e} = 0, cqz${e} = 0, cqw${e} = 1;\n if (fixed_${e}) {\n g${e}.genValue(undefined, q${e}, delta, 0);\n cqx${e} = q${e}.x; cqy${e} = q${e}.y; cqz${e} = q${e}.z; cqw${e} = q${e}.w;\n }`,body:`if (quat_${e}) {\n let qx, qy, qz, qw;\n if (fixed_${e}) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n g${e}.genValue(p.memory, q${e}, delta, t);\n qx = q${e}.x; qy = q${e}.y; qz = q${e}.z; qw = q${e}.w;\n }\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + aw * qx + ay * qz - az * qy;\n rq${e}[o4 + 1] = ay * qw + aw * qy + az * qx - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz + ax * qy - ay * qx;\n rq${e}[o4 + 3] = aw * qw - ax * qx - ay * qy - az * qz;\n aq${e}[o4] = qx; aq${e}[o4 + 1] = qy; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"VelocityOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Vi(`lx${e}`,`b${e}.linearX`)}\n ${Vi(`ly${e}`,`b${e}.linearY`)}\n ${Vi(`lz${e}`,`b${e}.linearZ`)}\n ${Vi(`ox${e}`,`b${e}.orbitalX`)}\n ${Vi(`oy${e}`,`b${e}.orbitalY`)}\n ${Vi(`oz${e}`,`b${e}.orbitalZ`)}\n ${Fi(`aX${e}`,`b${e}._axisX`)}\n ${Fi(`aY${e}`,`b${e}._axisY`)}\n ${Fi(`aZ${e}`,`b${e}._axisZ`)}\n ${Vi(`rd${e}`,`b${e}.radial`)}\n ${Fi(`ce${e}`,`b${e}._center`)}\n const world${e} = b${e}.ps !== undefined && b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const convert${e} = toWorld${e} || (!world${e} && b${e}.space === 'world');\n ${Fi(`sc${e}`,`toWorld${e} ? b${e}._tempScale : b${e}._tempScaleInv`)}\n ${Ci(`q${e}`,`toWorld${e} ? b${e}._tempQ : b${e}._tempQInv`)}`,body:`{\n ${Ti(`lx${e}`,"fx","t")}\n ${Ti(`ly${e}`,"fy","t")}\n ${Ti(`lz${e}`,"fz","t")}\n if (convert${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${Pi("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n let px = Math.fround(pos[o3] + fx * delta);\n let py = Math.fround(pos[o3 + 1] + fy * delta);\n let pz = Math.fround(pos[o3 + 2] + fz * delta);\n ${Ti(`rd${e}`,"radial","t")}\n if (radial !== 0) {\n // Away from the centre, along the line through the particle.\n const dx = px - ce${e}x, dy = py - ce${e}y, dz = pz - ce${e}z;\n const length = Math.sqrt(dx * dx + dy * dy + dz * dz);\n if (length > 0) {\n const f = (radial * delta) / length;\n px = Math.fround(px + dx * f); py = Math.fround(py + dy * f); pz = Math.fround(pz + dz * f);\n }\n }\n ${Ti(`ox${e}`,"rx","t")}\n ${Ti(`oy${e}`,"ry","t")}\n ${Ti(`oz${e}`,"rz","t")}\n rx *= delta; ry *= delta; rz *= delta;\n if (rx !== 0 || ry !== 0 || rz !== 0) {\n px = Math.fround(px - ce${e}x); py = Math.fround(py - ce${e}y); pz = Math.fround(pz - ce${e}z);\n if (rx !== 0) ${Ii("rx",`aX${e}x`,`aX${e}y`,`aX${e}z`)}\n if (ry !== 0) ${Ii("ry",`aY${e}x`,`aY${e}y`,`aY${e}z`)}\n if (rz !== 0) ${Ii("rz",`aZ${e}x`,`aZ${e}y`,`aZ${e}z`)}\n px = Math.fround(px + ce${e}x); py = Math.fround(py + ce${e}y); pz = Math.fround(pz + ce${e}z);\n }\n pos[o3] = px; pos[o3 + 1] = py; pos[o3 + 2] = pz;}`};case"InheritVelocity":return{setup:`const b${e} = behaviors[${e}];\n const ps${e} = b${e}.ps;\n const ev${e} = b${e}.mode === 'current' && ps${e} !== undefined ? ps${e}.emitterVelocity : undefined;\n const active${e} = ev${e} !== undefined;\n let ivx${e} = 0, ivy${e} = 0, ivz${e} = 0;\n if (active${e}) {\n ivx${e} = ev${e}.x; ivy${e} = ev${e}.y; ivz${e} = ev${e}.z;\n if (!ps${e}.worldSpace) {\n ${Fi(`sc${e}`,`b${e}._tempScaleInv`)}\n ${Ci(`q${e}`,`b${e}._tempQInv`)}\n ivx${e} *= sc${e}x; ivy${e} *= sc${e}y; ivz${e} *= sc${e}z;\n ${Pi(`ivx${e}`,`ivy${e}`,`ivz${e}`,`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n }\n ${Vi(`gm${e}`,`b${e}.multiplier`)}`,body:`if (active${e}) {\n ${Ti(`gm${e}`,"m","t")}\n const f = m * delta;\n pos[o3] += ivx${e} * f; pos[o3 + 1] += ivy${e} * f; pos[o3 + 2] += ivz${e} * f;\n }`};default:return null}}const Bi=new Map;function Ei(t,e,i){const s=Bi.get(i);if(void 0!==s)return s??void 0;const n=function(t,e){const i=`\n if (count === 0) return;\n if (store === undefined) {\n store = particles[0].store;\n if (store === undefined) {\n // Particles of some other implementation, without columns: run the behaviors as they are.\n for (const k of [${e.join(", ")}]) {\n const b = behaviors[k];\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n if (p.age < p.life) b.update(p, delta);\n }\n }\n return;\n }\n }\n const pos = store.position, vel = store.velocity;\n const size = store.size, startSize = store.startSize;\n const color = store.color, startColor = store.startColor;\n const scalars = store.scalars;\n const rot = store.rotation, angVel = store.angularVelocity;\n const uvTile = store.uvTile, startSpeed = store.startSpeed;\n const mem = store.memory, ms = store.memoryStride;\n ${t.map(t=>t.setup).join("\n")}\n // The system keeps particles[i] on row i. Anything else (a hand-built\n // list) is caught by its ends and read through each particle's row.\n const mapped = particles[0].storeIndex !== 0 || particles[count - 1].storeIndex !== count - 1;\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n const row = mapped ? p.storeIndex : i;\n const s = row * 3;\n const age = scalars[s], life = scalars[s + 1];\n if (age >= life) continue;\n const t = age / life;\n const o3 = row * 3, o4 = row * 4;\n ${t.map(t=>t.body).join("\n")}\n }`;try{return new Function("deps",`const tmpColor = new deps.Vector4View(new Float32Array(4), 0);\n return function (behaviors, particles, count, delta, store) {${i}};`)(_i)}catch(t){return}}(t,e);return Bi.set(i,n??null),n}function Ni(t){const e=[];let i=[],s=[],n=[],r=0;const o=()=>{if(0===s.length)return;const t=`${r}:${i.map(t=>t.type).join(",")}`,o=Ei(s,n,t);if(void 0!==o)e.push({behaviors:i,run:o});else for(const t of i)e.push({behaviors:[t]});i=[],s=[],n=[]};for(let a=0;a<t.length;a++){const h=t[a],l=Ui(h,a);null!==l?(0===s.length&&(r=a),i.push(h),s.push(l),n.push(a)):(o(),e.push({behaviors:[h]}))}return o(),e}class Di{constructor(t,e,i){this.position=t??new ot,this.rotation=e??new rt,this.scale=i??new ot(1,1,1)}apply(t){t.position.multiply(this.scale).applyQuaternion(this.rotation).add(this.position);const e=t.velocity,i=e.length();if(0===i)return;e.multiply(this.scale).applyQuaternion(this.rotation);const s=e.length();s>0&&e.multiplyScalar(i/s)}isIdentity(){const{position:t,rotation:e,scale:i}=this;return 0===t.x&&0===t.y&&0===t.z&&0===e.x&&0===e.y&&0===e.z&&1===e.w&&1===i.x&&1===i.y&&1===i.z}toJSON(){const t={},{position:e,rotation:i,scale:s}=this;return 0===e.x&&0===e.y&&0===e.z||(t.position=[e.x,e.y,e.z]),0===i.x&&0===i.y&&0===i.z&&1===i.w||(t.rotation=[i.x,i.y,i.z,i.w]),1===s.x&&1===s.y&&1===s.z||(t.scale=[s.x,s.y,s.z]),t}static fromJSON(t){if(!t)return;const{position:e,rotation:i,scale:s}=t;return new Di(e?new ot(e[0],e[1],e[2]):void 0,i?new rt(i[0],i[1],i[2],i[3]):void 0,s?new ot(s[0],s[1],s[2]):void 0)}static toShapeJSON(t){return t&&!t.isIdentity()?{transform:t.toJSON()}:{}}clone(){return new Di(this.position.clone(),this.rotation.clone(),this.scale.clone())}}var ki,Ri;!function(t){t[t.Volume=0]="Volume",t[t.Shell=1]="Shell",t[t.Edge=2]="Edge"}(ki||(ki={}));class Li{constructor(t={}){this.type="box",this._point=[0,0,0],this.width=t.width??1,this.height=t.height??1,this.depth=t.depth??1,this.emitFrom=t.emitFrom??ki.Volume,this.boxThickness=t.boxThickness?[...t.boxThickness]:[0,0,0],this.transform=t.transform}update(t,e){}initialize(t,e){const i=this._point;for(let t=0;t<3;t++)i[t]=2*A()-1;const s=Math.floor(3*A())%3;this.emitFrom===ki.Shell?i[s]=this.onSurface(s):this.emitFrom===ki.Edge&&(i[(s+1)%3]=this.onSurface((s+1)%3),i[(s+2)%3]=this.onSurface((s+2)%3)),t.position.set(i[0]*this.width/2,i[1]*this.height/2,i[2]*this.depth/2),t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}onSurface(t){const e=A()<.5?-1:1,i=this.boxThickness[t];return i<=0||A()<.5?e:e*(1-2*i*A())}toJSON(){return{type:"box",width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:[...this.boxThickness],...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Li({width:t.width,height:t.height,depth:t.depth,emitFrom:t.emitFrom,boxThickness:Array.isArray(t.boxThickness)?t.boxThickness:void 0,transform:Di.fromJSON(t.transform)})}clone(){return new Li({width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:this.boxThickness,transform:this.transform?.clone()})}}function qi(t,e,i,s){let n;switch(t){case Ri.Loop:n=e-Math.floor(e);break;case Ri.PingPong:{const t=e-2*Math.floor(e/2);n=1-Math.abs(t-1);break}case Ri.Burst:n=s.isBursting&&s.burstParticleCount>0?s.burstParticleIndex/s.burstParticleCount:A();break;default:n=A()}return i>0&&(n=Math.floor(n/i)*i),n}!function(t){t[t.Random=0]="Random",t[t.Loop=1]="Loop",t[t.PingPong=2]="PingPong",t[t.Burst=3]="Burst"}(Ri||(Ri={}));class Ji{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="circle",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??Ri.Random,this.spread=t.spread??0,this.speed=t.speed??new Qt(1),this.memory=[],this.transform=t.transform}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=qi(this.mode,this.currentValue,this.spread,e),s=nt.lerp(1-this.thickness,1,A()),n=i*this.arc;t.position.x=Math.cos(n),t.position.y=Math.sin(n),t.position.z=0,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*s),this.transform?.apply(t)}toJSON(){return{type:"circle",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Ji({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Xt(t.speed):void 0,transform:Di.fromJSON(t.transform),spread:t.spread})}clone(){return new Ji({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Wi{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="cone",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.angle=t.angle??Math.PI/6,this.mode=t.mode??Ri.Random,this.spread=t.spread??0,this.speed=t.speed??new Qt(1),this.memory=[],this.transform=t.transform}update(t,e){Ri.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=qi(this.mode,this.currentValue,this.spread,e),s=1-nt.clamp(this.thickness,0,1),n=Math.sqrt(nt.lerp(s*s,1,A())),r=i*this.arc,o=Math.sin(r),a=Math.cos(r);t.position.x=n*a,t.position.y=n*o,t.position.z=0;const h=this.angle*n;t.velocity.set(0,0,Math.cos(h)).addScaledVector(t.position,Math.sin(h)).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius),this.transform?.apply(t)}toJSON(){return{type:"cone",radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Wi({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,mode:t.mode,speed:t.speed?Xt(t.speed):void 0,transform:Di.fromJSON(t.transform),spread:t.spread})}clone(){return new Wi({radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Qi{constructor(t={}){this.type="donut",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.donutRadius=t.donutRadius??.2*this.radius,this.mode=t.mode??Ri.Random,this.spread=t.spread??0,this.speed=t.speed??new Qt(1),this.memory=[],this.transform=t.transform,this._m1=new ut}reset(){this.currentValue=0,this.memory.length=0}update(t,e){Ri.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=qi(this.mode,this.currentValue,this.spread,e),s=A(),n=nt.lerp(1-this.thickness,1,A()),r=i*this.arc,o=s*Math.PI*2,a=Math.sin(r),h=Math.cos(r);if(t.position.x=this.radius*h,t.position.y=this.radius*a,t.position.z=0,t.velocity.z=this.donutRadius*n*Math.sin(o),t.velocity.x=this.donutRadius*n*Math.cos(o)*h,t.velocity.y=this.donutRadius*n*Math.cos(o)*a,t.position.add(t.velocity),t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof rt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Ue,t.velocity,Ie),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"donut",radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Qi({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?Xt(t.speed):void 0,transform:Di.fromJSON(t.transform),spread:t.spread})}clone(){return new Qi({radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Gi{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="edge",this.currentValue=0,this.radius=t.radius??1,this.mode=t.mode??Ri.Random,this.spread=t.spread??0,this.speed=t.speed??new Qt(1),this.memory=[],this.transform=t.transform}update(t,e){Ri.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=qi(this.mode,this.currentValue,this.spread,e);t.position.set((2*i-1)*this.radius,0,0),t.velocity.set(0,t.startSpeed,0),this.transform?.apply(t)}toJSON(){return{type:"edge",radius:this.radius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Gi({radius:t.radius,mode:t.mode,speed:t.speed?Xt(t.speed):void 0,spread:t.spread,transform:Di.fromJSON(t.transform)})}clone(){return new Gi({radius:this.radius,mode:this.mode,speed:this.speed.clone(),spread:this.spread,transform:this.transform?.clone()})}}class ji{constructor(t={}){this.type="grid",this.width=t.width??1,this.height=t.height??1,this.column=t.column??10,this.row=t.row??10,this.transform=t.transform}initialize(t){const e=Math.floor(A()*this.row),i=Math.floor(A()*this.column);t.position.x=i*this.width/this.column-this.width/2,t.position.y=e*this.height/this.row-this.height/2,t.position.z=0,t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"grid",width:this.width,height:this.height,column:this.column,row:this.row,...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new ji({...t,transform:Di.fromJSON(t.transform)})}clone(){return new ji({width:this.width,height:this.height,column:this.column,row:this.row,transform:this.transform?.clone()})}update(t,e){}}class Yi{constructor(t={}){this.type="hemisphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??Ri.Random,this.spread=t.spread??0,this.speed=t.speed??new Qt(1),this.memory=[],this.transform=t.transform,this._m1=new ut}reset(){this.currentValue=0,this.memory.length=0}update(t,e){Ri.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=qi(this.mode,this.currentValue,this.spread,e),s=A(),n=nt.lerp(1-this.thickness,1,A()),r=i*this.arc,o=Math.acos(s),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*n),t.rotation instanceof rt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Ue,t.position,Ie),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"hemisphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Yi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Xt(t.speed):void 0,transform:Di.fromJSON(t.transform),spread:t.spread})}clone(){return new Yi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Hi{constructor(t){this.type="point",this._m1=new ut,this.transform=t}update(t,e){}initialize(t){const e=A(),i=A(),s=e*Math.PI*2,n=2*i-1,r=Math.sqrt(Math.max(0,1-n*n));if(t.velocity.x=r*Math.cos(s),t.velocity.y=r*Math.sin(s),t.velocity.z=n,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof rt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Ue,t.velocity,Ie),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"point",...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Hi(Di.fromJSON(t?.transform))}clone(){return new Hi(this.transform?.clone())}}class Xi{constructor(t={}){this.type="sphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??Ri.Random,this.spread=t.spread??0,this.speed=t.speed??new Qt(1),this.memory=[],this.transform=t.transform,this._m1=new ut}reset(){this.currentValue=0,this.memory.length=0}update(t,e){Ri.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=qi(this.mode,this.currentValue,this.spread,e),s=A(),n=nt.lerp(1-this.thickness,1,A()),r=i*this.arc,o=Math.acos(2*s-1),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*n),t.rotation instanceof rt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Ue,t.position,Ie),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"sphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Xi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?Xt(t.speed):void 0,transform:Di.fromJSON(t.transform),spread:t.spread})}clone(){return new Xi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Zi{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="rectangle",this.currentValue=0,this.width=t.width??10,this.height=t.height??10,this.thickness=t.thickness??1,this.mode=t.mode??Ri.Random,this.spread=t.spread??0,this.speed=t.speed??new Qt(1),this.memory=[],this.transform=t.transform,this._m1=new ut}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=qi(this.mode,this.currentValue,this.spread,e);A();const s=i*(2*(this.width+this.height));let n,r;s<this.width?(n=s-this.width/2,r=-this.height/2):s<this.width+this.height?(n=this.width/2,r=s-this.width-this.height/2):s<2*this.width+this.height?(n=this.width/2-(s-this.width-this.height),r=this.height/2):(n=-this.width/2,r=this.height/2-(s-2*this.width-this.height));const o=A(),a=1-this.thickness*o;if(t.position.x=n*a,t.position.y=r*a,t.position.z=0,t.velocity.x=n,t.velocity.y=r,t.velocity.z=0,t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof rt){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(Ue,t.velocity,Ie),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"rectangle",width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new Zi({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?Xt(t.speed):void 0,transform:Di.fromJSON(t.transform),spread:t.spread})}clone(){return new Zi({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const Ki={box:{type:"box",params:[["width",["number"]],["height",["number"]],["depth",["number"]],["emitFrom",["number"]],["boxThickness",["vec3"]]],constructor:Li,loadJSON:Li.fromJSON},circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Ji,loadJSON:Ji.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Wi,loadJSON:Wi.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Qi,loadJSON:Qi.fromJSON},edge:{type:"edge",params:[["radius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Gi,loadJSON:Gi.fromJSON},point:{type:"point",params:[],constructor:Hi,loadJSON:Hi.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Xi,loadJSON:Xi.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Yi,loadJSON:Yi.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["rows",["number"]],["column",["number"]]],constructor:ji,loadJSON:ji.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Zi,loadJSON:Zi.fromJSON}};function ts(t,e){const i=t?Ki[t.type]:void 0;return i?i.loadJSON(t,e):(qt(`${Wt("emitter shape",t)}; using a point emitter.`),new Hi)}const es=[];function is(t){if(!es.find(e=>e.id===t.id)){t.initialize(),es.push(t);for(const e of t.emitterShapes)Ki[e.type]||(Ki[e.type]=e);for(const e of t.behaviors)Mi[e.type]||(Mi[e.type]=e)}}function ss(t){const e=es.findIndex(e=>e.id===t);if(e<0)return;const i=es[e];es.splice(e,1);for(const t of i.emitterShapes)Ki[t.type]===t&&delete Ki[t.type];for(const t of i.behaviors)Mi[t.type]===t&&delete Mi[t.type]}function ns(t){const i=t;return i._quarksUUID??(i._quarksUUID=e())}class rs{get mesh(){return this._mesh}set mesh(e){if(this._mesh=e,this._positions=void 0,this._indices=void 0,this._triangleIndexToArea.length=0,!e)return;const i=e.getVerticesData(t.PositionKind),s=e.getIndices();if(!i||!s)return;this._positions=new Float32Array(i),this._indices=new Int32Array(s),this._triangleIndexToArea.length=0;let n=0;const r=s.length/3;this._triangleIndexToArea.push(0);const o=new ot,a=new ot,h=new ot;for(let t=0;t<r;t++){const e=s[3*t],r=s[3*t+1],l=s[3*t+2];o.set(i[3*e],i[3*e+1],i[3*e+2]),a.set(i[3*r],i[3*r+1],i[3*r+2]),h.set(i[3*l],i[3*l+1],i[3*l+2]),a.sub(o),h.sub(o);const c=new ot;c.crossVectors(a,h),n+=.5*c.length(),this._triangleIndexToArea.push(n)}}constructor(t,e,i){this.type="mesh_surface",this._triangleIndexToArea=[],this._meshReferenceId=e,this.transform=i,t&&(this.mesh=t)}initialize(t){if(!this._positions||!this._indices)return t.position.set(0,0,0),t.velocity.set(0,0,1).multiplyScalar(t.startSpeed),void this.transform?.apply(t);const e=this._triangleIndexToArea.length-1;let i=0,s=e;const n=A()*this._triangleIndexToArea[e];for(;i+1<s;){const t=Math.floor((i+s)/2);n<this._triangleIndexToArea[t]?s=t:i=t}let r=A(),o=A();r+o>1&&(r=1-r,o=1-o);const a=this._indices[3*i],h=this._indices[3*i+1],l=this._indices[3*i+2],c=this._positions[3*a],u=this._positions[3*a+1],d=this._positions[3*a+2],f=this._positions[3*h]-c,m=this._positions[3*h+1]-u,p=this._positions[3*h+2]-d,y=this._positions[3*l]-c,g=this._positions[3*l+1]-u,v=this._positions[3*l+2]-d;t.position.set(c+f*r+y*o,u+m*r+g*o,d+p*r+v*o);const x=m*v-p*g,w=p*y-f*v,b=f*g-m*y,S=Math.sqrt(x*x+w*w+b*b)||1;t.velocity.set(x/S,w/S,b/S).multiplyScalar(t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"mesh_surface",mesh:this._mesh?ns(this._mesh):this._meshReferenceId??"",...Di.toShapeJSON(this.transform)}}static fromJSON(t){return new rs(void 0,t?.mesh,Di.fromJSON(t?.transform))}clone(){return new rs(this._mesh,this._meshReferenceId,this.transform?.clone())}update(t,e){}}const os={id:"babylon.quarks",initialize:()=>{},emitterShapes:[{type:"mesh_surface",params:[["mesh",["mesh"]]],constructor:rs,loadJSON:t=>rs.fromJSON(t)}],behaviors:[]};function as(t){return"unlit"===t||"scene"===t?t:"fixed"}function hs(t){return"distance"===t||"oldestInFront"===t||"youngestInFront"===t?t:"none"}function ls(t){return"pause"===t||"pauseAndCatchUp"===t?t:"always"}function cs(t){return!t||0===t.x&&0===t.y&&0===t.z?void 0:t.clone()}function us(t){return"number"==typeof t&&t>0?Math.min(t,1):0}function ds(t){return"number"==typeof t&&Number.isFinite(t)&&t>=1?Math.floor(t):1}function fs(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:e}function ms(t){const e=t.count,i="number"==typeof t.time&&Number.isFinite(t.time)&&t.time>0?t.time:0,s="number"==typeof t.cycle&&Number.isFinite(t.cycle)&&t.cycle>=1?t.cycle:1,n="number"==typeof t.interval&&Number.isFinite(t.interval)?Math.max(0,t.interval):.1,r="number"==typeof t.probability&&Number.isFinite(t.probability)?Math.min(1,Math.max(0,t.probability)):1;return{time:i,count:"number"==typeof e?new Qt(e):null!=e?e:new Qt(0),cycle:s,interval:n,probability:r}}function ps(t){return(t??[]).map(ms).sort((t,e)=>t.time-e.time)}function ys(t,e={}){const i=function(t,e){if(i=t,"function"==typeof i?.getDepthMap){const i=t,s=i._storeCameraSpaceZ?"viewZ":i._storeNonLinearDepth?"nonLinear":"linear";return{texture:t.getDepthMap(),encoding:e.encoding??s,packed:e.packed??t.isPacked}}var i;return{texture:t,encoding:e.encoding??"linear",packed:e.packed??!1}}(t,e);if(i.packed&&"viewZ"===i.encoding)throw new Error("[babylon.quarks] A packed view-Z depth cannot be decoded; use a float depth texture");return i}function gs(t,e,i){if("viewZ"===e)return i.set(1,0,0,1);const s=t.getEngine(),n=s.useReverseDepthBuffer,r=s.isNDCHalfZRange,o=t.getProjectionMatrix().m,a=o[10],h=o[11],l=o[14],c=o[15];if("linear"===e){let e,s;t.mode===g.ORTHOGRAPHIC_CAMERA?(e=!n&&r?0:1,s=n&&r?0:1):(e=n&&r?t.minZ:r?0:t.minZ,s=n&&r?0:t.maxZ);const o=n?-1:1,h=e+s;return i.set(o*h/a,(-o*e-l)/a,0,1)}const u=r?1:2,d=r?0:-1;return i.set(-u*c,l-d*c,u*h,d*h-a)}function vs(t,e){const i=e.z*t+e.w,s=Math.abs(i)>1e-8?Math.abs((e.x*t+e.y)/i):0;return s>0?s:1e30}var xs;function ws(){return{direction:new c(.4,-1,.6),color:new l(1,1,1),ambient:new l(.35,.35,.35)}}function bs(t){if(!t||"object"!=typeof t)return;const e=Array.isArray(t.color)?t.color:[1,1,1],i=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e;return{color:[i(e[0],1),i(e[1],1),i(e[2],1)],power:Math.max(.01,i(t.power,2)),strength:Math.max(0,i(t.strength,1)),mode:"mix"===t.mode||"fade"===t.mode?t.mode:"add"}}function Ss(t,e){return t===e||!(!t||!e)&&(t.mode===e.mode&&t.power===e.power&&t.strength===e.strength&&t.color[0]===e.color[0]&&t.color[1]===e.color[1]&&t.color[2]===e.color[2])}function Ms(t,e={}){const i=t&&"object"==typeof t?t:{},s=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,n=(t,e)=>Array.isArray(t)?[s(t[0],e[0]),s(t[1],e[1])]:[e[0],e[1]];return{channel:1===(i.channel??e.channel)?1:0,tiling:n(i.tiling,e.tiling??[1,1]),offset:n(i.offset,e.offset??[0,0]),scroll:n(i.scroll,e.scroll??[0,0])}}function zs(t,e){return t===e||t.channel===e.channel&&t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]}function _s(t,e={}){const i=Ms(void 0,e),s={};return t.channel!==i.channel&&(s.channel=t.channel),t.tiling[0]===i.tiling[0]&&t.tiling[1]===i.tiling[1]||(s.tiling=[...t.tiling]),t.offset[0]===i.offset[0]&&t.offset[1]===i.offset[1]||(s.offset=[...t.offset]),t.scroll[0]===i.scroll[0]&&t.scroll[1]===i.scroll[1]||(s.scroll=[...t.scroll]),Object.keys(s).length>0?s:void 0}!function(t){t[t.BillBoard=0]="BillBoard",t[t.StretchedBillBoard=1]="StretchedBillBoard",t[t.Mesh=2]="Mesh",t[t.Trail=3]="Trail",t[t.HorizontalBillBoard=4]="HorizontalBillBoard",t[t.VerticalBillBoard=5]="VerticalBillBoard",t[t.Beam=6]="Beam"}(xs||(xs={}));const Vs={r:[1,0,0,0],g:[0,1,0,0],b:[0,0,1,0],a:[0,0,0,1],luminance:[.2126,.7152,.0722,0]};function As(t){if(!t||"object"!=typeof t||!t.ramp)return;const e=t.channel;return{ramp:t.ramp,channel:void 0!==e&&e in Vs?e:"r"}}function Ts(t,e){return t===e||!!t&&!!e&&t.ramp===e.ramp&&t.channel===e.channel}const Os=.05;function $s(t){if(!t||"object"!=typeof t)return;const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,i=Array.isArray(t.edgeColor)?t.edgeColor:[1,1,1];return{mask:t.mask??null,maskUV:Ms(t.maskUV),softness:Math.max(1e-4,e(t.softness,Os)),edgeWidth:Math.max(0,e(t.edgeWidth,0)),edgeColor:[e(i[0],1),e(i[1],1),e(i[2],1)]}}function Ps(t,e){return t===e||!(!t||!e)&&(t.mask===e.mask&&zs(t.maskUV,e.maskUV)&&t.softness===e.softness&&t.edgeWidth===e.edgeWidth&&t.edgeColor[0]===e.edgeColor[0]&&t.edgeColor[1]===e.edgeColor[1]&&t.edgeColor[2]===e.edgeColor[2])}const Cs={scroll:[0,.5]},Fs=.05;function Is(t){if(!t||"object"!=typeof t||!t.map)return;const e=t.strength;return{map:t.map,mapUV:Ms(t.mapUV,Cs),strength:Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:Fs)}}function Us(t,e){return t===e||!(!t||!e)&&(t.map===e.map&&t.strength===e.strength&&zs(t.mapUV,e.mapUV))}function Bs(t){if(!t||"object"!=typeof t)return;const e=Ms(t);return void 0===_s(e)?void 0:e}function Es(t,e){return t===e||!!t&&!!e&&zs(t,e)}function Ns(t){const{mapUV:e,uvDistortion:i,erosion:s}=t;return 1===e?.channel||1===i?.mapUV.channel||!!s?.mask&&1===s.maskUV.channel}class Ds{constructor(t,e,i=null){this.visibleSystems=[],this.boundsMin_=new ot,this.boundsMax_=new ot,this.time=0,this.scene=e,this.depth=i,this.maxParticles=1e3,this.systems=new Set,this.settings=Ws(t),this.mesh=new p("vfxBatch",e),this.configureMesh()}configureMesh(){const t=this.mesh;t.alwaysSelectAsActiveMesh=!0,t.doNotSyncBoundingInfo=!0,t.setBoundingInfo(new o(c.Zero(),c.Zero())),t.layerMask=this.settings.layerMask,t.renderingGroupId=this.settings.renderingGroupId,t.alphaIndex=this.settings.renderOrder,t.applyFog=!1,t.isPickable=!1,t.checkCollisions=!1,t.doNotSerialize=!0}refreshBoundingInfo(){const t=this.boundsMin_,e=this.boundsMax_;let i=1/0,s=1/0,n=1/0,r=-1/0,o=-1/0,a=-1/0,h=!1;const l=this.visibleSystems;for(let c=0;c<l.length;c++){const u=l[c];if(0!==u.particleNum&&"function"==typeof u.getWorldBounds){if(!u.getWorldBounds(t,e))return void(this.mesh.alwaysSelectAsActiveMesh=!0);h=!0,t.x<i&&(i=t.x),t.y<s&&(s=t.y),t.z<n&&(n=t.z),e.x>r&&(r=e.x),e.y>o&&(o=e.y),e.z>a&&(a=e.z)}}if(!h)return;const c=this.mesh.getBoundingInfo(),u=c.minimum,d=c.maximum;u.x===i&&u.y===s&&u.z===n&&d.x===r&&d.y===o&&d.z===a||(u.set(i,s,n),d.set(r,o,a),c.reConstruct(u,d)),this.mesh.alwaysSelectAsActiveMesh=!1}static writeBound(t,e){e(t);const i=t.getEffect();i?.isReady()&&e(i)}bindFog(t){if(!this.settings.applyFog)return;const e=this.scene;t.onBindObservable.add(()=>{const i=t.getEffect();if(!i)return;const s=e.fogEnabled?e.fogMode:y.FOGMODE_NONE;i.setFloat4("vFogInfos",s,e.fogStart,e.fogEnd,e.fogDensity),i.setColor3("vFogColor",e.fogColor)})}usesUV1(){return Ns(this.settings)}bindSurface(t){const{mapUV:e,uvDistortion:i,gradientMap:s,erosion:n}=this.settings;if(i?.map&&t.setTexture("distortionMap",i.map),s?.ramp&&t.setTexture("gradientMap",s.ramp),n?.mask&&t.setTexture("erosionMask",n.mask),this.writeSurfaceParams(t),!(e||i||n?.mask||s))return;const r=t=>t-2*Math.floor(t/2),o=new u,a=new u,h=new u,l=new d(0,1),c=(t,e,i)=>i.set(t.tiling[0],t.tiling[1],t.offset[0]+r(t.scroll[0]*e),t.offset[1]+r(t.scroll[1]*e)),f=()=>{const e=this.time,i=t.getEffect(),{mapUV:s,uvDistortion:n,gradientMap:r,erosion:u}=this.settings;if(s&&(c(s,e,o),t.setVector4("mapTransform",o),i?.setVector4("mapTransform",o)),n&&(c(n.mapUV,e,a),t.setVector4("distortionTransform",a),i?.setVector4("distortionTransform",a)),u?.mask&&(c(u.maskUV,e,h),t.setVector4("erosionMaskTransform",h),i?.setVector4("erosionMaskTransform",h)),r?.ramp){const e=r.ramp.getSize().width,s=e>0?.5/e:0;l.set(s,1-s),t.setVector2("gradientMapRange",l),i?.setVector2("gradientMapRange",l)}};f(),t.onBindObservable.add(f)}writeSurfaceParams(t){const{uvDistortion:e,gradientMap:i,erosion:s}=this.settings;if(e?.map&&t.setFloat("distortionStrength",e.strength),i?.ramp){const[e,s,n,r]=Vs[i.channel];t.setVector4("gradientMapChannel",new u(e,s,n,r))}s&&(t.setVector2("erosionParams",new d(s.softness,s.edgeWidth)),t.setVector3("erosionEdgeColor",new c(s.edgeColor[0],s.edgeColor[1],s.edgeColor[2])))}applyLiveSettings(t){Object.assign(this.settings,t);const e=this.mesh.material;e instanceof h&&this.writeLiveUniforms(e)}writeLiveUniforms(t){this.writeSoftParams(t),this.writeSurfaceParams(t)}addSystem(t){this.systems.add(t)}removeSystem(t){this.systems.delete(t)}getVisibleSystems(){const t=this.visibleSystems;let e=0;for(const i of this.systems)i.emitter.visible&&!0!==i.culled&&(t[e++]=i);return t.length=e,t}applyDepthTexture(t){t instanceof a&&(t={texture:t,encoding:"linear",packed:!1});const e=this.depth;if(this.depth=t,!this.settings.softParticles)return;if(!e!=!t||e?.packed!==t?.packed)return void this.rebuildMaterial();const i=this.mesh.material;t&&i instanceof h&&i.setTexture("depthTexture",t.texture)}bindSoft(t){if(this.writeSoftParams(t),this.drawsSoft()){t.setTexture("depthTexture",this.depth.texture);const e=new u(1,0,0,1);t.onBindObservable.add(()=>{const i=this.scene.activeCamera;i&&this.depth&&(gs(i,this.depth.encoding,e),Ds.writeBound(t,t=>t.setVector4("projParams",e)))})}}writeSoftParams(t){this.drawsSoft()&&t.setVector2("softParams",new d(this.settings.softNearFade,1/Math.max(this.settings.softFarFade-this.settings.softNearFade,1e-4))),this.settings.materialAlphaTest>0&&t.setFloat("alphaTest",this.settings.materialAlphaTest)}drawsSoft(){return this.settings.softParticles&&null!==this.depth}applyMeshLighting(t){}dispose(){this.mesh.dispose()}}const ks=new Float32Array(0),Rs=new Uint16Array(0);function Ls(t){return t===xs.BillBoard||t===xs.StretchedBillBoard||t===xs.VerticalBillBoard||t===xs.HorizontalBillBoard}function qs(t){return t.uTileCount>1||t.vTileCount>1}function Js(t){return t.minParticleSize>0||t.maxParticleSize!==1/0}function Ws(t){const e=t.renderMode,i=e===xs.Mesh,s=e===xs.Trail,n=Ls(e),o=t.softParticles,a=t.materialTransparent,h=t.pivot,l=Bs(t.mapUV),c=Is(t.uvDistortion),u=As(t.gradientMap),d=$s(t.erosion),f=ds(t.uTileCount),m=ds(t.vTileCount);var p;return{renderMode:e,instancingGeometry:s?ks:t.instancingGeometry,instancingIndices:s?Rs:t.instancingIndices,instancingUVs:s?void 0:t.instancingUVs,instancingUVs2:i&&Ns({mapUV:l,uvDistortion:c,erosion:d})?t.instancingUVs2:void 0,instancingNormals:i?t.instancingNormals:void 0,renderOrder:t.renderOrder,uTileCount:f,vTileCount:m,blendTiles:!s&&t.blendTiles&&qs({uTileCount:f,vTileCount:m}),softParticles:o,softNearFade:o?fs(t.softNearFade,0):0,softFarFade:o?fs(t.softFarFade,1):0,materialBlendMode:a?t.materialBlendMode:r.ALPHA_DISABLE,materialTransparent:a,materialDepthTest:t.materialDepthTest,materialDepthWrite:t.materialDepthWrite,materialAlphaTest:t.materialAlphaTest>0?t.materialAlphaTest:0,texture:t.texture,reflectionTexture:i?t.reflectionTexture??null:null,reflectionLevel:i?t.reflectionLevel??1:1,reflectionAtlas:i?t.reflectionAtlas??null:null,layerMask:t.layerMask,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,pivot:n&&h&&(0!==h.x||0!==h.y||0!==h.z)?h.clone():void 0,sortMode:t.sortMode??"none",minParticleSize:n?Math.max(0,t.minParticleSize??0):0,maxParticleSize:n?(p=t.maxParticleSize,void 0!==p&&p>0?p:1/0):1/0,lighting:i?t.lighting??"fixed":"fixed",rim:i?bs(t.rim):void 0,mapUV:l,uvDistortion:c,gradientMap:u,erosion:d}}function Qs(t,e){return t.renderMode===e.renderMode&&t.instancingGeometry===e.instancingGeometry&&t.instancingIndices===e.instancingIndices&&t.instancingUVs===e.instancingUVs&&t.instancingUVs2===e.instancingUVs2&&t.instancingNormals===e.instancingNormals&&t.texture===e.texture&&t.reflectionTexture===e.reflectionTexture&&t.reflectionAtlas===e.reflectionAtlas&&t.lighting===e.lighting&&t.rim?.mode===e.rim?.mode&&t.uTileCount===e.uTileCount&&t.vTileCount===e.vTileCount&&t.blendTiles===e.blendTiles&&t.softParticles===e.softParticles&&t.materialBlendMode===e.materialBlendMode&&t.materialTransparent===e.materialTransparent&&t.materialDepthTest===e.materialDepthTest&&t.materialDepthWrite===e.materialDepthWrite&&t.materialAlphaTest>0==e.materialAlphaTest>0&&t.layerMask===e.layerMask&&t.renderingGroupId===e.renderingGroupId&&t.renderOrder===e.renderOrder&&t.applyFog===e.applyFog&&t.sortMode===e.sortMode&&!t.pivot==!e.pivot&&Js(t)===Js(e)&&t.mapUV?.channel===e.mapUV?.channel&&t.uvDistortion?.map===e.uvDistortion?.map&&t.uvDistortion?.mapUV.channel===e.uvDistortion?.mapUV.channel&&!t.gradientMap==!e.gradientMap&&t.gradientMap?.ramp===e.gradientMap?.ramp&&!t.erosion==!e.erosion&&t.erosion?.mask===e.erosion?.mask&&t.erosion?.maskUV.channel===e.erosion?.maskUV.channel}function Gs(t,e){return t.softNearFade===e.softNearFade&&t.softFarFade===e.softFarFade&&t.materialAlphaTest===e.materialAlphaTest&&t.reflectionLevel===e.reflectionLevel&&function(t,e){return(t?.x??0)===(e?.x??0)&&(t?.y??0)===(e?.y??0)&&(t?.z??0)===(e?.z??0)}(t.pivot,e.pivot)&&t.minParticleSize===e.minParticleSize&&t.maxParticleSize===e.maxParticleSize&&function(t,e){if(!t||!e)return!t==!e;return t.power===e.power&&t.strength===e.strength&&Ys(t.color,e.color)}(t.rim,e.rim)&&Hs(t.mapUV,e.mapUV)&&t.uvDistortion?.strength===e.uvDistortion?.strength&&Hs(t.uvDistortion?.mapUV,e.uvDistortion?.mapUV)&&t.gradientMap?.channel===e.gradientMap?.channel&&t.erosion?.softness===e.erosion?.softness&&t.erosion?.edgeWidth===e.erosion?.edgeWidth&&Ys(t.erosion?.edgeColor,e.erosion?.edgeColor)&&Hs(t.erosion?.maskUV,e.erosion?.maskUV)}function js(t,e){return Qs(t,e)&&Gs(t,e)}function Ys(t,e){return t&&e?t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]:!t==!e}function Hs(t,e){return t&&e?t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]:!t==!e}const Xs=2048,Zs=2047;class Ks{constructor(t){this.counts=new Uint32Array(Xs),this.floatView=new Float32Array(1),this.uintView=new Uint32Array(this.floatView.buffer),this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t)}ensure(t){this.keys.length<t&&(this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t))}floatKey(t,e){this.floatView[0]=t;const i=this.uintView[0];return e?~i>>>0:i}}const tn="\n#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";function en(t){return`\n#ifdef FOG\n vFogDistance = ${t};\n#endif\n`}const sn="\n#ifdef FOG\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\n\nfloat quarksFogFactor() {\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n float fogDistance = length(vFogDistance);\n if (vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n";function nn(t){return`\n#ifdef FOG\n {\n float fogFactor = quarksFogFactor();\n#ifdef FOG_ADDITIVE\n ${t} *= fogFactor;\n#else\n ${t} = mix(vFogColor, ${t}, fogFactor);\n#endif\n }\n#endif\n`}const rn="\n#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";function on(t){return`\n#ifdef FOG\n vertexOutputs.vFogDistance = ${t};\n#endif\n`}const an="\n#ifdef FOG\nuniform vFogInfos: vec4f;\nuniform vFogColor: vec3f;\nvarying vFogDistance: vec3f;\n\nfn quarksFog(rgb: vec3f, fogDistanceVector: vec3f) -> vec3f {\n var fogCoeff = 1.0;\n let fogStart = uniforms.vFogInfos.y;\n let fogEnd = uniforms.vFogInfos.z;\n let fogDensity = uniforms.vFogInfos.w;\n let fogDistance = length(fogDistanceVector);\n if (uniforms.vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (uniforms.vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (uniforms.vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n let fogFactor = clamp(fogCoeff, 0.0, 1.0);\n#ifdef FOG_ADDITIVE\n return rgb * fogFactor;\n#else\n return mix(uniforms.vFogColor, rgb, fogFactor);\n#endif\n}\n#endif\n";function hn(t){return`\n#ifdef FOG\n ${t} = vec4f(quarksFog(${t}.rgb, fragmentInputs.vFogDistance), ${t}.a);\n#endif\n`}function ln(t,e,i){const s=e*i,n=cn(Math.floor(t),s);return{column:cn(n,e),row:Math.floor(n/e)}}function cn(t,e){return t-e*Math.floor(t/e)}const un="\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n";function dn(t){return`\n#ifdef UV_TILE\n {\n vec2 tc = vec2(tileCountX, tileCountY);\n float tileTotal = tc.x * tc.y;\n float baseTile = mod(floor(uvTile), tileTotal);\n vec2 tileUV = vec2(mod(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n float nextTile = mod(baseTile + 1.0, tileTotal);\n vec2 nextUV = vec2(mod(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vUV2 = ${t} / tc + nextUV;\n vTileBlend = fract(uvTile);\n#endif\n }\n#else\n vUV = ${t};\n#endif\n`}const fn="\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n\n// A floored modulo, as GLSL's mod: never negative for a positive divisor.\nfn quarksWrap(value: f32, divisor: f32) -> f32 {\n return value - divisor * floor(value / divisor);\n}\n#endif\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n";function mn(t){return`\n#ifdef UV_TILE\n {\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let tileTotal = tc.x * tc.y;\n let baseTile = quarksWrap(floor(vertexInputs.uvTile), tileTotal);\n let tileUV = vec2f(quarksWrap(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vertexOutputs.vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n let nextTile = quarksWrap(baseTile + 1.0, tileTotal);\n let nextUV = vec2f(quarksWrap(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vertexOutputs.vUV2 = ${t} / tc + nextUV;\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n#endif\n }\n#else\n vertexOutputs.vUV = ${t};\n#endif\n`}var pn=`\nattribute vec3 position;\nattribute vec2 uv;\nattribute vec3 normal;\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute vec4 rotation;\nattribute float uvTile;\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${un}\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute vec2 uv2;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\nvec3 applyQuaternion(vec3 v, vec4 q) {\n vec3 qVec = q.xyz;\n float qW = q.w;\n vec3 t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${tn}\nvoid main() {\n vec3 scaledPosition = position * size;\n vec3 rotatedPosition = applyQuaternion(scaledPosition, rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n vec3 safeSize = vec3(\n abs(size.x) > 1e-6 ? size.x : 1e-6,\n abs(size.y) > 1e-6 ? size.y : 1e-6,\n abs(size.z) > 1e-6 ? size.z : 1e-6);\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n vec3 rotatedNormal = normalize(applyQuaternion(normal / safeSize, rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n vec3 localPos = rotatedPosition + offset;\n\n vec4 worldPos = world * vec4(localPos, 1.0);\n vec4 viewPos = view * worldPos;\n gl_Position = projection * viewPos;\n${en("viewPos.xyz")}\n\n vWorldPos = worldPos.xyz;\n vNormal = normalize((world * vec4(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(viewPos.z);\n#endif\n\n${dn("uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vUV1 = uv2;\n#else\n vUV1 = uv;\n#endif\n#endif\n vColor = color;\n}\n`,yn=`\nattribute position: vec3f;\nattribute uv: vec2f;\nattribute normal: vec3f;\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: vec4f;\nattribute uvTile: f32;\n\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${fn}\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute uv2: vec2f;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\nfn applyQuaternion(v: vec3f, q: vec4f) -> vec3f {\n let qVec = q.xyz;\n let qW = q.w;\n let t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${rn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let size = vertexInputs.size;\n let scaledPosition = vertexInputs.position * size;\n let rotatedPosition = applyQuaternion(scaledPosition, vertexInputs.rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n let safeSize = vec3f(\n select(1e-6, size.x, abs(size.x) > 1e-6),\n select(1e-6, size.y, abs(size.y) > 1e-6),\n select(1e-6, size.z, abs(size.z) > 1e-6));\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n let rotatedNormal = normalize(applyQuaternion(vertexInputs.normal / safeSize, vertexInputs.rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n let localPos = rotatedPosition + vertexInputs.offset;\n\n let worldPos = uniforms.world * vec4f(localPos, 1.0);\n let viewPos = uniforms.view * worldPos;\n let clipPosition = uniforms.projection * viewPos;\n vertexOutputs.position = clipPosition;\n${on("viewPos.xyz")}\n\n vertexOutputs.vWorldPos = worldPos.xyz;\n vertexOutputs.vNormal = normalize((uniforms.world * vec4f(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(viewPos.z);\n#endif\n\n${mn("vertexInputs.uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#else\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;const gn="\n#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n\nfloat quarksSceneDepth(vec4 texel) {\n#ifdef SOFT_DEPTH_PACKED\n float d = dot(texel, vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n float d = texel.r;\n#endif\n float denominator = projParams.z * d + projParams.w;\n float depth = abs(denominator) > 1e-8 ? abs((projParams.x * d + projParams.y) / denominator) : 0.0;\n // Nothing drawn there reads as infinitely far.\n return depth > 0.0 ? depth : 1e30;\n}\n#endif\n";function vn(t){return`\n#ifdef SOFT_PARTICLES\n {\n vec2 softUV = 0.5 * (projPosition.xy / projPosition.w) + 0.5;\n float sceneDepth = quarksSceneDepth(texture2D(depthTexture, softUV));\n ${t} *= clamp(softParams.y * ((sceneDepth - softParams.x) - linearDepth), 0.0, 1.0);\n }\n#endif\n`}const xn="\n#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n\nfn quarksSceneDepth(texel: vec4f) -> f32 {\n#ifdef SOFT_DEPTH_PACKED\n let d = dot(texel, vec4f(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n let d = texel.r;\n#endif\n let denominator = uniforms.projParams.z * d + uniforms.projParams.w;\n let depth = select(0.0, abs((uniforms.projParams.x * d + uniforms.projParams.y) / denominator), abs(denominator) > 1e-8);\n // Nothing drawn there reads as infinitely far.\n return select(1e30, depth, depth > 0.0);\n}\n#endif\n";function wn(t){return`\n#ifdef SOFT_PARTICLES\n {\n let softUV = 0.5 * (fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w) + 0.5;\n let sceneDepth = quarksSceneDepth(textureSample(depthTexture, depthTextureSampler, softUV));\n ${t} *= clamp(uniforms.softParams.y * ((sceneDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n }\n#endif\n`}const bn="\n#ifdef MAP_TRANSFORM\nuniform vec4 mapTransform;\n#endif\n#ifdef UV_DISTORTION\nuniform sampler2D distortionMap;\nuniform vec4 distortionTransform;\nuniform float distortionStrength;\n#endif\n#ifdef GRADIENT_MAP\nuniform sampler2D gradientMap;\nuniform vec2 gradientMapRange;\nuniform vec4 gradientMapChannel;\n#endif\n#ifdef EROSION\nuniform vec2 erosionParams;\nuniform vec3 erosionEdgeColor;\n#ifdef EROSION_MASK\nuniform sampler2D erosionMask;\nuniform vec4 erosionMaskTransform;\n#endif\n\nvec4 quarksErode(vec4 color, float level, float mask) {\n float softness = erosionParams.x;\n float edgeWidth = erosionParams.y;\n // At level 1 the cut sits below the lowest mask value by the soft band\n // and the edge band, so nothing is cut and no edge shows; at level 0 above\n // the highest. The edge then grows in as the cut rises, rather than popping.\n float cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n float visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n float edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color.rgb += erosionEdgeColor * edge;\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function Sn(t){return`\n vec4 baseColor = vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV = vUV1 * mapTransform.xy + mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n vec2 mapUV = vUV * mapTransform.xy + mapTransform.zw;\n#else\n vec2 mapUV = vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n vec2 distortionUV = vUV1;\n #else\n vec2 distortionUV = vUV;\n #endif\n vec2 distortion = (texture2D(distortionMap, distortionUV * distortionTransform.xy + distortionTransform.zw).rg - 0.5) * 2.0 * distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n float erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n float erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n vec4 texColor = texture2D(map, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n vec2 mapUV2 = vUV2 * mapTransform.xy + mapTransform.zw;\n #else\n vec2 mapUV2 = vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n vec4 texColor2 = texture2D(map, mapUV2);\n texColor = mix(texColor, texColor2, vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n vec4 texColor = vec4(1.0);\n#endif\n #ifdef GRADIENT_MAP\n float rampAt = clamp(dot(texColor, gradientMapChannel), 0.0, 1.0);\n vec4 ramp = texture2D(gradientMap, vec2(mix(gradientMapRange.x, gradientMapRange.y, rampAt), 0.5));\n texColor = vec4(ramp.rgb, ramp.a * mix(texColor.a, 1.0, gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n vec2 erosionUV = vUV1;\n #else\n vec2 erosionUV = vUV;\n #endif\n erosionMaskValue = texture2D(erosionMask, erosionUV * erosionMaskTransform.xy + erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}const Mn="\n#ifdef MAP_TRANSFORM\nuniform mapTransform: vec4f;\n#endif\n#ifdef UV_DISTORTION\nvar distortionMapSampler: sampler;\nvar distortionMap: texture_2d<f32>;\nuniform distortionTransform: vec4f;\nuniform distortionStrength: f32;\n#endif\n#ifdef GRADIENT_MAP\nvar gradientMapSampler: sampler;\nvar gradientMap: texture_2d<f32>;\nuniform gradientMapRange: vec2f;\nuniform gradientMapChannel: vec4f;\n#endif\n#ifdef EROSION\nuniform erosionParams: vec2f;\nuniform erosionEdgeColor: vec3f;\n#ifdef EROSION_MASK\nvar erosionMaskSampler: sampler;\nvar erosionMask: texture_2d<f32>;\nuniform erosionMaskTransform: vec4f;\n#endif\n\nfn quarksErode(colorIn: vec4f, level: f32, mask: f32) -> vec4f {\n var color = colorIn;\n let softness = uniforms.erosionParams.x;\n let edgeWidth = uniforms.erosionParams.y;\n let cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n let visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n let edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color = vec4f(color.rgb + uniforms.erosionEdgeColor * edge, color.a);\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function zn(t){return`\n var baseColor = fragmentInputs.vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n var mapUV = fragmentInputs.vUV1 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n var mapUV = fragmentInputs.vUV * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#else\n var mapUV = fragmentInputs.vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n let distortionUV = fragmentInputs.vUV1;\n #else\n let distortionUV = fragmentInputs.vUV;\n #endif\n let distortion = (textureSample(distortionMap, distortionMapSampler, distortionUV * uniforms.distortionTransform.xy + uniforms.distortionTransform.zw).rg - 0.5) * 2.0 * uniforms.distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n let erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n var erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n var texColor = textureSample(map, mapSampler, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n let mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n var mapUV2 = fragmentInputs.vUV2 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n #else\n var mapUV2 = fragmentInputs.vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n let texColor2 = textureSample(map, mapSampler, mapUV2);\n texColor = mix(texColor, texColor2, fragmentInputs.vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n var texColor = vec4f(1.0);\n#endif\n #ifdef GRADIENT_MAP\n let rampAt = clamp(dot(texColor, uniforms.gradientMapChannel), 0.0, 1.0);\n let ramp = textureSample(gradientMap, gradientMapSampler, vec2f(mix(uniforms.gradientMapRange.x, uniforms.gradientMapRange.y, rampAt), 0.5));\n texColor = vec4f(ramp.rgb, ramp.a * mix(texColor.a, 1.0, uniforms.gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n let erosionUV = fragmentInputs.vUV1;\n #else\n let erosionUV = fragmentInputs.vUV;\n #endif\n erosionMaskValue = textureSample(erosionMask, erosionMaskSampler, erosionUV * uniforms.erosionMaskTransform.xy + uniforms.erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}var _n=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${sn}\n${gn}\n${bn}\nvoid main() {\n${Sn(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${nn("baseColor.rgb")}\n gl_FragColor = baseColor;\n${vn("gl_FragColor")}\n}\n`,Vn=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${an}\n${xn}\n${Mn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${zn(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${hn("baseColor")}\n${wn("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,An=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifndef MESH_UNLIT\nuniform vec3 lightDirection;\nuniform vec3 lightColor;\nuniform vec3 ambientColor;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform vec3 eyePosition;\n#endif\n\n#ifdef MESH_RIM\nuniform vec3 rimColor;\nuniform vec2 rimParams;\n#endif\n\n// One 3×2 atlas (px py pz / nx ny nz). Avoids samplerCube and multi-face\n// sampler bindings that raise GL_INVALID_OPERATION on iOS WebKit.\n#ifdef USE_ENVMAP_ATLAS\nuniform sampler2D envAtlas;\nuniform float reflectionLevel;\n\nvec3 sampleEnvAtlas(vec3 r) {\n vec3 a = abs(r);\n vec2 localUV;\n float cellX;\n float cellY;\n // Atlas layout: +X +Y +Z on row 0, -X -Y -Z on row 1.\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n vec2 uv = (vec2(cellX, cellY) + clamp(localUV, 0.0, 1.0)) / vec2(3.0, 2.0);\n return texture2D(envAtlas, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${sn}\n${gn}\n${bn}\nvoid main() {\n${Sn(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n vec3 N = normalize(vNormal) * (gl_FrontFacing ? 1.0 : -1.0);\n#ifdef MESH_UNLIT\n vec3 color = baseColor.rgb;\n#else\n vec3 L = normalize(-lightDirection);\n float NdotL = max(dot(N, L), 0.0);\n vec3 litColor = ambientColor + lightColor * NdotL;\n\n vec3 color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n vec3 viewDir = normalize(vWorldPos - eyePosition);\n vec3 reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n vec3 V = normalize(eyePosition - vWorldPos);\n float edgeTerm = pow(1.0 - abs(dot(N, V)), rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, rimColor, clamp(edgeTerm * rimParams.y, 0.0, 1.0));\n #else\n color += rimColor * edgeTerm * rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${nn("color")}\n gl_FragColor = vec4(color, baseColor.a);\n${vn("gl_FragColor")}\n}\n`,Tn=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifndef MESH_UNLIT\nuniform lightDirection: vec3f;\nuniform lightColor: vec3f;\nuniform ambientColor: vec3f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform eyePosition: vec3f;\n#endif\n\n#ifdef MESH_RIM\nuniform rimColor: vec3f;\nuniform rimParams: vec2f;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\nvar envAtlasSampler: sampler;\nvar envAtlas: texture_2d<f32>;\nuniform reflectionLevel: f32;\n\nfn sampleEnvAtlas(r: vec3f) -> vec3f {\n let a = abs(r);\n var localUV: vec2f;\n var cellX: f32;\n var cellY: f32;\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n let uv = (vec2f(cellX, cellY) + clamp(localUV, vec2f(0.0), vec2f(1.0))) / vec2f(3.0, 2.0);\n return textureSample(envAtlas, envAtlasSampler, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${an}\n${xn}\n${Mn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${zn(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n let N = normalize(fragmentInputs.vNormal) * select(-1.0, 1.0, fragmentInputs.frontFacing);\n#ifdef MESH_UNLIT\n var color = baseColor.rgb;\n#else\n let L = normalize(-uniforms.lightDirection);\n let NdotL = max(dot(N, L), 0.0);\n let litColor = uniforms.ambientColor + uniforms.lightColor * NdotL;\n\n var color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n let viewDir = normalize(fragmentInputs.vWorldPos - uniforms.eyePosition);\n let reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * uniforms.reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n let V = normalize(uniforms.eyePosition - fragmentInputs.vWorldPos);\n let edgeTerm = pow(1.0 - abs(dot(N, V)), uniforms.rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - uniforms.rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, uniforms.rimColor, clamp(edgeTerm * uniforms.rimParams.y, 0.0, 1.0));\n #else\n color += uniforms.rimColor * edgeTerm * uniforms.rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n var finalColor = vec4f(color, baseColor.a);\n\n${hn("finalColor")}\n${wn("finalColor")}\n fragmentOutputs.color = finalColor;\n}\n`,On=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${un}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n${tn}\nvoid main() {\n float c = cos(rotation);\n float s = sin(rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n vec4 limitCenter = view * world * vec4(offset, 1.0);\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(limitCenter.z) : 1.0;\n float screenSize = max(abs(size.x), abs(size.y)) * projection[1][1] / (2.0 * limitDepth);\n float sizeScale = screenSize > 0.0 ? clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize : 1.0;\n vec3 limitedSize = size * sizeScale;\n#else\n vec3 limitedSize = size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n vec2 alignedPosition = position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += pivot.xy * abs(limitedSize.xy);\n#endif\n vec2 rotatedPosition;\n rotatedPosition.x = c * alignedPosition.x - s * alignedPosition.y;\n rotatedPosition.y = s * alignedPosition.x + c * alignedPosition.y;\n\n#ifdef HORIZONTAL\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = view * mvPosition;\n#elif defined(VERTICAL)\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n mvPosition.xy += rotatedPosition;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n gl_Position = projection * mvPosition;\n${en("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${dn("uv")}\n\n#ifdef UV1\n vUV1 = uv;\n#endif\n vColor = color;\n}\n`,$n=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${fn}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n${rn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let c = cos(vertexInputs.rotation);\n let s = sin(vertexInputs.rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitCenter = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let limitDepth = select(1.0, abs(limitCenter.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = max(abs(vertexInputs.size.x), abs(vertexInputs.size.y)) * uniforms.projection[1][1] / (2.0 * limitDepth);\n let sizeScale = select(1.0, clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize, screenSize > 0.0);\n let limitedSize = vertexInputs.size * sizeScale;\n#else\n let limitedSize = vertexInputs.size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n var alignedPosition = vertexInputs.position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += uniforms.pivot.xy * abs(limitedSize.xy);\n#endif\n let rotatedPosition = vec2f(\n c * alignedPosition.x - s * alignedPosition.y,\n s * alignedPosition.x + c * alignedPosition.y);\n\n#ifdef HORIZONTAL\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += uniforms.pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = uniforms.view * mvPosition;\n#elif defined(VERTICAL)\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = uniforms.view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.y += rotatedPosition.y;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * uniforms.pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${on("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${mn("vertexInputs.uv")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,Pn=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\nattribute vec4 velocity;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${un}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n\n${tn}\nvoid main() {\n float lengthFactor = velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n float avgSize = (abs(size.x) + abs(size.y)) * 0.5;\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n vec3 viewVelocity = mat3(view * world) * velocity.xyz;\n float vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n vec3 vdir = vlength > 0.000001 ? viewVelocity / vlength : vec3(0.0, 0.0, 1.0);\n // Seen straight along its length a streak has no side to face; any will do.\n vec3 sideRaw = cross(mvPosition.xyz, vdir);\n vec3 side = dot(sideRaw, sideRaw) > 1e-12 ? normalize(sideRaw) : vec3(1.0, 0.0, 0.0);\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(mvPosition.z) : 1.0;\n float screenSize = avgSize * projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize;\n }\n#endif\n mvPosition.xyz += position.y * side * avgSize;\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n mvPosition.xyz += (position.x + 0.5) * viewVelocity;\n#else\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n mvPosition.xyz -= (position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n mvPosition.xyz += (pivot.y * side - pivot.x * vdir) * avgSize;\n#endif\n gl_Position = projection * mvPosition;\n${en("mvPosition.xyz")}\n vec2 quadUV = vec2(size.x < 0.0 ? 1.0 - uv.x : uv.x, size.y < 0.0 ? 1.0 - uv.y : uv.y);\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${dn("quadUV")}\n\n#ifdef UV1\n vUV1 = quadUV;\n#endif\n vColor = color;\n}\n`,Cn=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\nattribute velocity: vec4f;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${fn}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n\n${rn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let lengthFactor = vertexInputs.velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n var avgSize = (abs(vertexInputs.size.x) + abs(vertexInputs.size.y)) * 0.5;\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let viewWorld = uniforms.view * uniforms.world;\n let viewWorld3 = mat3x3f(viewWorld[0].xyz, viewWorld[1].xyz, viewWorld[2].xyz);\n let viewVelocity = viewWorld3 * vertexInputs.velocity.xyz;\n let vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n var vdir = vec3f(0.0, 0.0, 1.0);\n if (vlength > 0.000001) {\n vdir = viewVelocity / vlength;\n }\n // Seen straight along its length a streak has no side to face; any will do.\n let sideRaw = cross(mvPosition.xyz, vdir);\n var side = vec3f(1.0, 0.0, 0.0);\n if (dot(sideRaw, sideRaw) > 1e-12) {\n side = normalize(sideRaw);\n }\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitDepth = select(1.0, abs(mvPosition.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = avgSize * uniforms.projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize;\n }\n#endif\n let widthOffset = vertexInputs.position.y * side * avgSize;\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n var stretched = mvPosition.xyz + widthOffset + (vertexInputs.position.x + 0.5) * viewVelocity;\n#else\n let lengthOffset = (vertexInputs.position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n var stretched = mvPosition.xyz + widthOffset - lengthOffset;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n stretched += (uniforms.pivot.y * side - uniforms.pivot.x * vdir) * avgSize;\n#endif\n mvPosition.x = stretched.x;\n mvPosition.y = stretched.y;\n mvPosition.z = stretched.z;\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${on("mvPosition.xyz")}\n let quadUV = select(vertexInputs.uv, 1.0 - vertexInputs.uv, vertexInputs.size.xy < vec2f(0.0));\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${mn("quadUV")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = quadUV;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,Fn=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${sn}\n${gn}\n${bn}\nvoid main() {\n${Sn(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${nn("baseColor.rgb")}\n gl_FragColor = baseColor;\n${vn("gl_FragColor")}}\n`,In=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${an}\n${xn}\n${Mn}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${zn(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${hn("baseColor")}\n${wn("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,Un=`\nattribute vec3 position;\nattribute vec3 previous;\nattribute vec3 next;\nattribute float side;\nattribute float width;\nattribute vec2 uv;\nattribute vec4 color;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute vec2 uv2;\nvarying vec2 vUV1;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nvec3 trailDirection(vec3 d) {\n float l = dot(d, d);\n return l > 1e-12 ? d * inversesqrt(l) : vec3(0.0);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nvec3 trailSide(vec3 previousPoint, vec3 point, vec3 nextPoint) {\n vec3 incoming = trailDirection(point - previousPoint);\n vec3 outgoing = trailDirection(nextPoint - point);\n vec3 tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = dot(outgoing, outgoing) > 0.0 ? outgoing : incoming;\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n vec3 sight = projection[3][3] > 0.5 ? vec3(0.0, 0.0, 1.0) : point;\n vec3 side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${tn}\nvoid main() {\n vec3 point = (view * vec4(position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (width > 0.0) {\n vec3 previousPoint = (view * vec4(previous, 1.0)).xyz;\n vec3 nextPoint = (view * vec4(next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * width * side);\n }\n gl_Position = projection * vec4(point, 1.0);\n${en("point")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(point.z);\n#endif\n vUV = uv;\n#ifdef UV1\n vUV1 = uv2;\n#endif\n vColor = color;\n}\n`,Bn=`\nattribute position: vec3f;\nattribute previous: vec3f;\nattribute next: vec3f;\nattribute side: f32;\nattribute width: f32;\nattribute uv: vec2f;\nattribute color: vec4f;\n\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute uv2: vec2f;\nvarying vUV1: vec2f;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nfn trailDirection(d: vec3f) -> vec3f {\n let l = dot(d, d);\n return select(vec3f(0.0), d * inverseSqrt(max(l, 1e-24)), l > 1e-12);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nfn trailSide(previousPoint: vec3f, point: vec3f, nextPoint: vec3f) -> vec3f {\n let incoming = trailDirection(point - previousPoint);\n let outgoing = trailDirection(nextPoint - point);\n var tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = select(incoming, outgoing, dot(outgoing, outgoing) > 0.0);\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n let sight = select(point, vec3f(0.0, 0.0, 1.0), uniforms.projection[3][3] > 0.5);\n var side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3f(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3f(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${rn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n var point = (uniforms.view * vec4f(vertexInputs.position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (vertexInputs.width > 0.0) {\n let previousPoint = (uniforms.view * vec4f(vertexInputs.previous, 1.0)).xyz;\n let nextPoint = (uniforms.view * vec4f(vertexInputs.next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * vertexInputs.width * vertexInputs.side);\n }\n let clipPosition = uniforms.projection * vec4f(point, 1.0);\n vertexOutputs.position = clipPosition;\n${on("point")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(point.z);\n#endif\n vertexOutputs.vUV = vertexInputs.uv;\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;const En=["position","uv","offset","color","size","rotation","uvTile"],Nn=["position","previous","next","side","width","uv","color"],Dn=["vFogInfos","vFogColor"];function kn(t){return t===xs.StretchedBillBoard||t===xs.Beam}function Rn(t,e){return t.renderMode===xs.Trail?function(t,e){const i=Ln(t),s=[...Nn],n=["view","projection",...Dn],r=[];null!==t.texture&&(i.push("USE_MAP"),r.push("map"));Jn(t,i,n,r),qn(t,e,i,n,r),Ns(t)&&s.push("uv2");return{name:"quarksTrail",vertex:{glsl:Un,wgsl:Bn},fragment:{glsl:Fn,wgsl:In},defines:i,attributes:s,uniforms:n,samplers:r}}(t,e):function(t,e){const i=t.renderMode,s=i===xs.Mesh,n=`quarksParticle_${i}`;let r,o;s?(r={glsl:pn,wgsl:yn},o={glsl:An,wgsl:Tn}):kn(i)?(r={glsl:Pn,wgsl:Cn},o={glsl:_n,wgsl:Vn}):(r={glsl:On,wgsl:$n},o={glsl:_n,wgsl:Vn});const a=Ln(t),h=[...En],l=["world","view","projection",...Dn],c=[];(function(t){return null!==t.texture||t.renderMode===xs.Mesh})(t)&&(a.push("USE_MAP"),c.push("map"));const u=s&&null!==t.reflectionAtlas&&e.envAtlasReady;u&&(a.push("USE_ENVMAP_ATLAS"),c.push("envAtlas"),l.push("reflectionLevel"));qs(t)&&(a.push("UV_TILE"),l.push("tileCountX","tileCountY"),t.blendTiles&&a.push("TILE_BLEND"));qn(t,e,a,l,c),i===xs.VerticalBillBoard&&a.push("VERTICAL");i===xs.HorizontalBillBoard&&a.push("HORIZONTAL");i===xs.Beam&&a.push("BEAM");Ls(i)&&(t.pivot&&(a.push("PIVOT"),l.push("pivot")),Js(t)&&(a.push("SIZE_LIMITS"),l.push("sizeLimits")));const d=s&&"unlit"!==(t.lighting??"fixed");s&&!d&&a.push("MESH_UNLIT");d&&l.push("lightDirection","lightColor","ambientColor");const f=s?t.rim:void 0;f&&(a.push("MESH_RIM"),"fade"===f.mode?a.push("MESH_RIM_FADE"):"mix"===f.mode&&a.push("MESH_RIM_MIX"),l.push("rimColor","rimParams"));(u||f)&&l.push("eyePosition");Jn(t,a,l,c),s&&(h.push("normal"),Ns(t)&&e.meshUV2&&(a.push("MESH_UV2"),h.push("uv2")));kn(i)&&h.push("velocity");return{name:n,vertex:r,fragment:o,defines:a,attributes:h,uniforms:l,samplers:c}}(t,e)}function Ln(t){return t.applyFog?function(t){return t.materialTransparent&&(t.materialBlendMode===r.ALPHA_ADD||t.materialBlendMode===r.ALPHA_ONEONE)}(t)?["FOG","FOG_ADDITIVE"]:["FOG"]:[]}function qn(t,e,i,s,n){t.softParticles&&null!==e.depth&&(i.push("SOFT_PARTICLES"),e.depth.packed&&i.push("SOFT_DEPTH_PACKED"),s.push("softParams","projParams"),n.push("depthTexture")),t.materialAlphaTest>0&&(i.push("USE_ALPHATEST"),s.push("alphaTest"))}function Jn(t,e,i,s){const{mapUV:n,uvDistortion:r,gradientMap:o,erosion:a}=t;Ns(t)&&e.push("UV1"),n&&(e.push("MAP_TRANSFORM"),1===n.channel&&e.push("MAP_UV1"),i.push("mapTransform")),r&&(e.push("UV_DISTORTION"),1===r.mapUV.channel&&e.push("UV_DISTORTION_UV1"),s.push("distortionMap"),i.push("distortionTransform","distortionStrength")),o&&(e.push("GRADIENT_MAP"),s.push("gradientMap"),i.push("gradientMapRange","gradientMapChannel")),a&&(e.push("EROSION"),i.push("erosionParams","erosionEdgeColor"),a.mask&&(e.push("EROSION_MASK"),1===a.maskUV.channel&&e.push("EROSION_MASK_UV1"),s.push("erosionMask"),i.push("erosionMaskTransform")))}function Wn(t){return t.isWebGPU?S.WGSL:S.GLSL}function Qn(t,e,i,s){if(s===S.WGSL)return w.ShadersStoreWGSL[t+"VertexShader"]=e.wgsl,void(w.ShadersStoreWGSL[t+"FragmentShader"]=i.wgsl);b.ShadersStore[t+"VertexShader"]=e.glsl,b.ShadersStore[t+"FragmentShader"]=i.glsl}class Gn extends Ds{static whiteTexture(t){let e=Gn.whiteTextureByScene.get(t);return e||(e=v.CreateRGBATexture(new Uint8Array([255,255,255,255]),1,1,t),e.name="quarksMeshWhite",Gn.whiteTextureByScene.set(t,e)),e}constructor(t,e,i=null){super(t,e,i),this.shaderMaterial=null,this.cancelAtlasRebuild=null,this.disposed=!1,this.fixedLightDirection=new c,this.fixedLightColor=new c,this.fixedAmbientColor=new c,this.warnedUV2=!1,this.gatherScratch=[],this.vector_=new ot,this.vector2_=new ot,this.vector3_=new ot,this.quaternion_=new rt,this.quaternion2_=new rt,this.quaternion3_=new rt,this.quaternion4_=new rt,this.quaternion5_=new rt,this.rotationMat_=new St,this.rotationMat2_=new St,this.clearedInstanceUploaded=!1,this.beamEnd_=new ot,this.storeFixedLighting(ws()),this.maxParticles=1e3,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh.dispose(),this.mesh=new p("spriteBatch",this.scene),this.configureMesh();const t=new x;t.positions=this.settings.instancingGeometry,t.indices=this.settings.instancingIndices;const e=this.settings.instancingGeometry.length/3,i=this.settings.instancingUVs;i&&i.length>=2*e?t.uvs=i:t.uvs=new Float32Array(2*e),this.meshUV2()&&(t.uvs2=this.settings.instancingUVs2),this.settings.instancingNormals&&(t.normals=this.settings.instancingNormals),t.applyToMesh(this.mesh,!1),this.buildExpandableBuffers()}meshUV2(){const t=this.settings.instancingUVs2;if(this.settings.renderMode!==xs.Mesh||!t||!this.usesUV1())return!1;const e=this.settings.instancingGeometry.length/3*2;return t.length===e||(this.warnedUV2||(this.warnedUV2=!0,console.warn(`[babylon.quarks] instancingUVs2 has ${t.length} values for ${e/2} vertices (two per vertex expected); UV channel 1 reads the first UV set instead.`)),!1)}disposeExpandableBuffers(){this.offsetVB?.dispose(),this.colorVB?.dispose(),this.sizeVB?.dispose(),this.uvTileVB?.dispose(),this.rotationVB?.dispose(),this.velocityVB?.dispose(),this.velocityVB=void 0,this.velocityBuffer=void 0}buildExpandableBuffers(){const e=this.scene.getEngine();this.offsetBuffer=new Float32Array(3*this.maxParticles),this.offsetVB=new t(e,this.offsetBuffer,"offset",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.offsetVB),this.colorBuffer=new Float32Array(4*this.maxParticles),this.colorVB=new t(e,this.colorBuffer,"color",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.colorVB),this.sizeBuffer=new Float32Array(3*this.maxParticles),this.sizeVB=new t(e,this.sizeBuffer,"size",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.sizeVB),this.uvTileBuffer=new Float32Array(this.maxParticles),this.uvTileVB=new t(e,this.uvTileBuffer,"uvTile",!0,!1,1,!0),this.mesh.setVerticesBuffer(this.uvTileVB),this.settings.renderMode===xs.Mesh?(this.rotationBuffer=new Float32Array(4*this.maxParticles),this.rotationVB=new t(e,this.rotationBuffer,"rotation",!0,!1,4,!0)):(this.rotationBuffer=new Float32Array(this.maxParticles),this.rotationVB=new t(e,this.rotationBuffer,"rotation",!0,!1,1,!0)),this.mesh.setVerticesBuffer(this.rotationVB),kn(this.settings.renderMode)&&(this.velocityBuffer=new Float32Array(4*this.maxParticles),this.velocityVB=new t(e,this.velocityBuffer,"velocity",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.velocityVB)),this.mesh.forcedInstanceCount=0,this.mesh.doNotSyncBoundingInfo=!0}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.disposeExpandableBuffers(),this.buildExpandableBuffers(),this.sortScratch=void 0,this.gatherScratch.length=0}sizeLimits(){const{minParticleSize:t,maxParticleSize:e}=this.settings;return Ls(this.settings.renderMode)&&Js(this.settings)?new d(Math.max(0,t),Math.min(e,1e9)):null}sortInstances(t,e,i){if(t<2)return;const s=this.sortScratch??(this.sortScratch=new Ks(this.maxParticles));s.ensure(t);const n=s.keys,r=this.settings.sortMode;if("distance"===r){const e=this.scene.activeCameras?.[0]??this.scene.activeCamera;if(!e)return;const i=e.globalPosition,r=i.x,o=i.y,a=i.z,h=this.offsetBuffer;for(let e=0,i=0;e<t;e++,i+=3){const t=h[i]-r,l=h[i+1]-o,c=h[i+2]-a;n[e]=s.floatKey(t*t+l*l+c*c,!0)}}else{const e="youngestInFront"===r,i=this.visibleSystems;let o=0;for(let t=0;t<i.length;t++){const r=i[t],a=r.particleNum,h=r.store;if(0===a)continue;if(void 0===h){const t=r.particles;for(let i=0;i<a;i++)n[o++]=s.floatKey(t[i].age,e);continue}const l=h.scalars,c=_e.SCALAR_STRIDE;for(let t=0,i=_e.AGE;t<a;t++,i+=c)n[o++]=s.floatKey(l[i],e)}if(o!==t)return}const o=function(t,e){const i=t.keys,s=t.counts;let n=t.orderA,r=t.orderB;for(let t=0;t<e;t++)n[t]=t;for(let t=0;t<32;t+=11){s.fill(0);for(let r=0;r<e;r++)s[i[n[r]]>>>t&Zs]++;if(s[i[n[0]]>>>t&Zs]===e)continue;let o=0;for(let t=0;t<Xs;t++){const e=s[t];s[t]=o,o+=e}for(let o=0;o<e;o++){const e=n[o];r[s[i[e]>>>t&Zs]++]=e}const a=n;n=r,r=a}return n}(s,t);this.offsetBuffer=this.gatherInto(0,this.offsetBuffer,o,t,3),this.sizeBuffer=this.gatherInto(1,this.sizeBuffer,o,t,3),this.colorBuffer=this.gatherInto(2,this.colorBuffer,o,t,4),this.uvTileBuffer=this.gatherInto(3,this.uvTileBuffer,o,t,1),this.rotationBuffer=this.gatherInto(4,this.rotationBuffer,o,t,e?4:1),i&&this.velocityBuffer&&(this.velocityBuffer=this.gatherInto(5,this.velocityBuffer,o,t,4))}gatherInto(t,e,i,s,n){let r=this.gatherScratch[t];return void 0!==r&&r.length===e.length||(r=new Float32Array(e.length)),function(t,e,i,s,n){if(1===n)for(let n=0;n<s;n++)e[n]=t[i[n]];else if(3===n)for(let n=0,r=0;n<s;n++,r+=3){const s=3*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2]}else if(4===n)for(let n=0,r=0;n<s;n++,r+=4){const s=4*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2],e[r+3]=t[s+3]}else for(let r=0;r<s;r++){const s=i[r]*n,o=r*n;for(let i=0;i<n;i++)e[o+i]=t[s+i]}}(e,r,i,s,n),this.gatherScratch[t]=e,r}rebuildMaterial(){const t=this.settings.renderMode===xs.Mesh,e=this.settings.texture??(t?Gn.whiteTexture(this.scene):null),i=this.settings.reflectionAtlas,s=t&&!!i&&!i.isReady();if(this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,s&&i){const t=i.onLoadObservable;if(t){const e=t.addOnce(()=>{this.cancelAtlasRebuild=null,this.disposed||this.rebuildMaterial()});this.cancelAtlasRebuild=()=>t.remove(e)}}const n=this.usesEnvAtlas(),o=Rn(this.settings,{depth:this.depth,envAtlasReady:n,meshUV2:this.meshUV2()}),{defines:a,attributes:l,uniforms:u,samplers:d}=o,f=o.name,m=this.settings.lighting??"fixed",p=t&&"unlit"!==m,y=t?this.settings.rim:void 0,g=n||!!y,v=Wn(this.scene.getEngine());Qn(f,o.vertex,o.fragment,v);const x=new h(f,this.scene,{vertex:f,fragment:f},{attributes:l,uniforms:u,samplers:d,defines:a,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:v});if(e&&x.setTexture("map",e),n&&i&&x.setTexture("envAtlas",i),g){const t=new c;x.setVector3("eyePosition",t),x.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.copyFrom(e.globalPosition),Ds.writeBound(x,e=>e.setVector3("eyePosition",t)))})}if(qs(this.settings)&&(x.setFloat("tileCountX",this.settings.uTileCount),x.setFloat("tileCountY",this.settings.vTileCount)),this.bindSoft(x),this.writeSpriteParams(x,n),p&&(this.writeFixedLighting(x),"scene"===m)){const t=new c,e=new c,i=new c;x.onBindObservable.add(()=>{const s=Gn.readSceneLight(this.scene,t,e,i);Ds.writeBound(x,n=>s?n.setVector3("lightDirection",t).setVector3("lightColor",e).setVector3("ambientColor",i):this.writeFixedLighting(n))})}this.bindFog(x),this.bindSurface(x),x.backFaceCulling=!1,this.settings.materialTransparent?x.alphaMode=this.settings.materialBlendMode:x.alphaMode=r.ALPHA_DISABLE,x.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,x.forceDepthWrite=this.settings.materialDepthWrite,x.disableDepthWrite=!this.settings.materialDepthWrite,x.depthFunction=this.settings.materialDepthTest?0:r.ALWAYS,this.shaderMaterial?.dispose(!1,!1),this.mesh.material=x,this.shaderMaterial=x}writeSpriteParams(t,e){e&&t.setFloat("reflectionLevel",this.settings.reflectionLevel);const i=this.settings.renderMode===xs.Mesh?this.settings.rim:void 0;i&&(t.setVector3("rimColor",new c(i.color[0],i.color[1],i.color[2])),t.setVector2("rimParams",new d(i.power,i.strength)));const s=Ls(this.settings.renderMode)?this.settings.pivot:void 0;s&&t.setVector3("pivot",new c(s.x,s.y,s.z));const n=this.sizeLimits();n&&t.setVector2("sizeLimits",n)}writeLiveUniforms(t){super.writeLiveUniforms(t),this.writeSpriteParams(t,this.usesEnvAtlas())}usesEnvAtlas(){const t=this.settings.reflectionAtlas;return this.settings.renderMode===xs.Mesh&&!!t&&t.isReady()}applyMeshLighting(t){this.storeFixedLighting(t);const e=this.shaderMaterial;null!==e&&this.settings.renderMode===xs.Mesh&&"unlit"!==this.settings.lighting&&this.writeFixedLighting(e)}storeFixedLighting(t){this.fixedLightDirection.copyFrom(t.direction),this.fixedLightColor.set(t.color.r,t.color.g,t.color.b),this.fixedAmbientColor.set(t.ambient.r,t.ambient.g,t.ambient.b)}writeFixedLighting(t){t.setVector3("lightDirection",this.fixedLightDirection),t.setVector3("lightColor",this.fixedLightColor),t.setVector3("ambientColor",this.fixedAmbientColor)}static readSceneLight(t,e,i,s){const n=t.lights;for(let r=0;r<n.length;r++){const o=n[r],a=o.getClassName();if("DirectionalLight"!==a&&"HemisphericLight"!==a||!o.isEnabled())continue;const h=o.intensity,l=o.diffuse,c=t.ambientColor;i.set(l.r*h,l.g*h,l.b*h),s.set(c.r,c.g,c.b);const u=o.direction;if("DirectionalLight"===a)e.copyFrom(u);else{e.copyFrom(u).scaleInPlace(-1);const t=o.groundColor;t&&(s.x+=t.r*h,s.y+=t.g*h,s.z+=t.b*h)}return!0}return!1}update(){let t=0,e=0;const i=this.settings.renderMode,s=i===xs.Mesh,n=i===xs.StretchedBillBoard,r=i===xs.Beam,o=n||r,a=Ls(i),h=this.getVisibleSystems();for(let t=0;t<h.length;t++)e+=h[t].particleNum;e>this.maxParticles&&this.expandBuffers(e);for(let e=0;e<h.length;e++){const i=h[e],o=i.particleNum;if(0===o)continue;const l=i.particles,c=this.quaternion2_,u=this.vector2_,d=this.vector3_,f=i.worldSpace,m=i.emitter.matrixWorld;if(s&&!f)m.decompose(u,c,d);else{const t=m.elements;d.set(Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]),Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}n&&!f&&this.rotationMat_.setFromMatrix4(m);const p=Math.abs(d.x),y=Math.abs(d.y),g=Math.abs(d.z),v=n?i.rendererEmitterSettings:void 0,x=void 0===v||0===v.speedFactor?.001:v.speedFactor,w=v?.lengthFactor??0,b=i.store,S=void 0!==b,M=void 0!==b&&!0!==i.onlyUsedByOther,z=i.simulationResidual??0,_=0===z?0:z/(i.simulationStep??z);S&&(0!==_&&o>0&&b.previousColor!==b.color?Gn.continueColor(this.colorBuffer,4*t,b,o,_):this.colorBuffer.set(b.color.subarray(0,4*o),4*t));let V=!1;if(void 0!==b&&f)0!==_&&o>0?Gn.extrapolate(this.offsetBuffer,3*t,b,o,_):this.offsetBuffer.set(b.position.subarray(0,3*o),3*t),0!==_&&o>0&&b.previousSize!==b.size?Gn.continueVector3(this.sizeBuffer,3*t,b.size,b.previousSize,o,_):this.sizeBuffer.set(b.size.subarray(0,3*o),3*t),V=!0;else if(M&&o>0){const e=3*t,i=e+3*o,s=this.offsetBuffer;0!==_?Gn.extrapolate(s,e,b,o,_):s.set(b.position.subarray(0,3*o),e);const n=m.elements,r=n[0],a=n[1],h=n[2],l=n[3],c=n[4],u=n[5],d=n[6],f=n[7],v=n[8],x=n[9],w=n[10],S=n[11],M=n[12],z=n[13],A=n[14],T=n[15];for(let t=e;t<i;t+=3){const e=s[t],i=s[t+1],n=s[t+2],o=1/(l*e+f*i+S*n+T);s[t]=(r*e+c*i+v*n+M)*o,s[t+1]=(a*e+u*i+x*n+z)*o,s[t+2]=(h*e+d*i+w*n+A)*o}const O=this.sizeBuffer;0!==_&&b.previousSize!==b.size?Gn.continueVector3(O,e,b.size,b.previousSize,o,_):O.set(b.size.subarray(0,3*o),e);for(let t=e;t<i;t+=3)O[t]*=p,O[t+1]*=y,O[t+2]*=g;V=!0}const A=t;if(M&&!s){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),A);const i=this.rotationBuffer;if(i.set(e.rotation.subarray(0,o),A),0!==z){const t=e.angularVelocity;for(let e=0;e<o;e++)i[A+e]+=t[e]*z}n&&this.velocityBuffer&&Gn.writeVelocities(this.velocityBuffer,4*A,e,o,_,f?null:this.rotationMat_,x,w),t+=o}else if(M&&b.rotationQuaternion.length>0){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),A),Gn.writeQuaternions(this.rotationBuffer,4*A,e,o,_,f?null:c),t+=o}else for(let e=0;e<o;e++,t++){const i=l[e];if(s){let e=i.rotation;const s=i.angularVelocity;let n;if(0!==_&&s instanceof rt&&(e=this.quaternion4_.copy(e).multiply(Gn.partialTurn(s,_,this.quaternion5_))),f)n=e;else{let t;t=i.parentMatrix?this.quaternion3_.setFromRotationMatrix(i.parentMatrix):c,n=this.quaternion_,n.copy(t).multiply(e)}const r=4*t;this.rotationBuffer[r]=n.x,this.rotationBuffer[r+1]=n.y,this.rotationBuffer[r+2]=n.z,this.rotationBuffer[r+3]=n.w}else{const e=i.angularVelocity;this.rotationBuffer[t]=i.rotation+("number"==typeof e?e*z:0)}if(!V){const e=i.position,s=i.previousPosition;let n=e.x+(e.x-s.x)*_,r=e.y+(e.y-s.y)*_,o=e.z+(e.z-s.z)*_;if(!f){const t=(i.parentMatrix??m).elements,e=1/(t[3]*n+t[7]*r+t[11]*o+t[15]),s=(t[0]*n+t[4]*r+t[8]*o+t[12])*e,a=(t[1]*n+t[5]*r+t[9]*o+t[13])*e;o=(t[2]*n+t[6]*r+t[10]*o+t[14])*e,n=s,r=a}const a=3*t;this.offsetBuffer[a]=n,this.offsetBuffer[a+1]=r,this.offsetBuffer[a+2]=o;const h=i.size,l=3*t;f||i.parentMatrix?(this.sizeBuffer[l]=h.x,this.sizeBuffer[l+1]=h.y,this.sizeBuffer[l+2]=h.z):(this.sizeBuffer[l]=h.x*p,this.sizeBuffer[l+1]=h.y*y,this.sizeBuffer[l+2]=h.z*g)}if(!S){const e=i.color,s=4*t;this.colorBuffer[s]=e.x,this.colorBuffer[s+1]=e.y,this.colorBuffer[s+2]=e.z,this.colorBuffer[s+3]=e.w}if(this.uvTileBuffer[t]=i.uvTile,n&&this.velocityBuffer){const e=i.velocity,s=i.previousVelocity,n=e.x+(e.x-s.x)*_,r=e.y+(e.y-s.y)*_,o=e.z+(e.z-s.z)*_,a=this.vector_;a.set(n,r,o),f||(i.parentMatrix?(this.rotationMat2_.setFromMatrix4(i.parentMatrix),a.applyMatrix3(this.rotationMat2_)):a.applyMatrix3(this.rotationMat_));const h=4*t;this.velocityBuffer[h]=a.x*x,this.velocityBuffer[h+1]=a.y*x,this.velocityBuffer[h+2]=a.z*x,this.velocityBuffer[h+3]=w}}const T=i.tint;void 0!==T&&t>A&&Gn.applyTint(this.colorBuffer,4*A,t-A,T),a&&void 0!==i.flip&&(void 0!==b?Gn.applyFlip(this.sizeBuffer,3*A,b.flip,o):Gn.applyFlipFromParticles(this.sizeBuffer,3*A,l,o)),r&&this.velocityBuffer&&this.writeBeams(i,A,t-A)}this.mesh.forcedInstanceCount=t,this.refreshBoundingInfo(),0!==t?(this.clearedInstanceUploaded=!1,"none"!==this.settings.sortMode&&this.sortInstances(t,s,o),this.offsetVB.update(this.offsetBuffer.subarray(0,3*t)),this.sizeVB.update(this.sizeBuffer.subarray(0,3*t)),this.colorVB.update(this.colorBuffer.subarray(0,4*t)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,t)),this.rotationVB.update(this.rotationBuffer.subarray(0,s?4*t:t)),o&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4*t))):this.clearedInstanceUploaded||(this.uploadClearedInstance(s,o),this.clearedInstanceUploaded=!0)}writeBeams(t,e,i){const s=this.velocityBuffer,n=this.offsetBuffer,r=this.beamEnd_,o="function"==typeof t.getBeamEnd&&t.getBeamEnd(r);for(let t=e;t<e+i;t++){const e=3*t,i=4*t;s[i]=o?r.x-n[e]:0,s[i+1]=o?r.y-n[e+1]:0,s[i+2]=o?r.z-n[e+2]:0,s[i+3]=0}}static applyTint(t,e,i,s){for(let n=0,r=e;n<i;n++,r+=4)t[r]*=s.x,t[r+1]*=s.y,t[r+2]*=s.z,t[r+3]*=s.w}static applyFlip(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n];0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static applyFlipFromParticles(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n].flip;0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static writeQuaternions(t,e,i,s,n,r){const o=i.rotationQuaternion,a=i.angularVelocityQuaternion,h=null!==r,l=h?r.x:0,c=h?r.y:0,u=h?r.z:0,d=h?r.w:1;for(let i=0,r=0,f=e;i<s;i++,r+=4,f+=4){let e=o[r],i=o[r+1],s=o[r+2],m=o[r+3];if(0!==n){const t=a[r]*n,o=a[r+1]*n,h=a[r+2]*n,l=1+(a[r+3]-1)*n,c=1/Math.sqrt(t*t+o*o+h*h+l*l),u=t*c,d=o*c,f=h*c,p=l*c,y=e*p+m*u+i*f-s*d,g=i*p+m*d+s*u-e*f,v=s*p+m*f+e*d-i*u;m=m*p-e*u-i*d-s*f,e=y,i=g,s=v}if(h){const t=l*m+d*e+c*s-u*i,n=c*m+d*i+u*e-l*s,r=u*m+d*s+l*i-c*e;m=d*m-l*e-c*i-u*s,e=t,i=n,s=r}t[f]=e,t[f+1]=i,t[f+2]=s,t[f+3]=m}}static writeVelocities(t,e,i,s,n,r,o,a){const h=i.velocity,l=i.previousVelocity.length>=3*s?i.previousVelocity:h,c=null!==r?r.elements:null;for(let i=0,r=0,u=e;i<s;i++,r+=3,u+=4){let e=h[r],i=h[r+1],s=h[r+2];if(0!==n&&(e+=(e-l[r])*n,i+=(i-l[r+1])*n,s+=(s-l[r+2])*n),null!==c){const t=c[0]*e+c[3]*i+c[6]*s,n=c[1]*e+c[4]*i+c[7]*s;s=c[2]*e+c[5]*i+c[8]*s,e=t,i=n}t[u]=e*o,t[u+1]=i*o,t[u+2]=s*o,t[u+3]=a}}static partialTurn(t,e,i){const s=t.x*e,n=t.y*e,r=t.z*e,o=1+(t.w-1)*e,a=1/Math.sqrt(s*s+n*n+r*r+o*o);return i.x=s*a,i.y=n*a,i.z=r*a,i.w=o*a,i}static continueVector3(t,e,i,s,n,r){for(let o=0,a=0;o<n;o++,a+=3){const n=i[a]+(i[a]-s[a])*r,o=i[a+1]+(i[a+1]-s[a+1])*r,h=i[a+2]+(i[a+2]-s[a+2])*r;t[e+a]=n>0?n:0,t[e+a+1]=o>0?o:0,t[e+a+2]=h>0?h:0}}static continueColor(t,e,i,s,n){const r=i.color,o=i.previousColor;for(let i=0,a=0;i<s;i++,a+=4){const i=r[a]+(r[a]-o[a])*n,s=r[a+1]+(r[a+1]-o[a+1])*n,h=r[a+2]+(r[a+2]-o[a+2])*n,l=r[a+3]+(r[a+3]-o[a+3])*n;t[e+a]=i>0?i:0,t[e+a+1]=s>0?s:0,t[e+a+2]=h>0?h:0,t[e+a+3]=l>0?l:0}}static extrapolate(t,e,i,s,n){const r=i.position,o=i.previousPosition;for(let i=0,a=0;i<s;i++,a+=3){const i=r[a],s=r[a+1],h=r[a+2];t[e+a]=i+(i-o[a])*n,t[e+a+1]=s+(s-o[a+1])*n,t[e+a+2]=h+(h-o[a+2])*n}}uploadClearedInstance(t,e){this.colorBuffer[3]=0,this.sizeBuffer[0]=0,this.sizeBuffer[1]=0,this.sizeBuffer[2]=0,this.colorVB.update(this.colorBuffer.subarray(0,4)),this.sizeVB.update(this.sizeBuffer.subarray(0,3)),this.offsetVB.update(this.offsetBuffer.subarray(0,3)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,1)),t?this.rotationVB.update(this.rotationBuffer.subarray(0,4)):this.rotationVB.update(this.rotationBuffer.subarray(0,1)),e&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4))}dispose(){this.disposed=!0,this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}Gn.whiteTextureByScene=new WeakMap;const jn=16;function Yn(t){const e=Math.round(Number(t?.tessellation)||0);return Math.min(16,Math.max(0,e))}function Hn(t){const e=Number(t?.curveTension)||0;return Math.min(1,Math.max(0,e))}const Xn=["stretch","tile","distributePerSegment","repeatPerSegment"];function Zn(t){const e=t?.textureMode;return void 0!==e&&Xn.includes(e)?e:"stretch"}function Kn(t){const e=Number(t?.textureScale);return Number.isFinite(e)&&e>0?e:1}function tr(t){const e=Number(t?.minVertexDistance);return Number.isFinite(e)&&e>0?e:0}function er(t){const e=Number(t?.lifetime);return Number.isFinite(e)&&e>0?e:1/0}class ir{constructor(){this.position=new Float32Array(0),this.side=new Float32Array(0),this.size=new Float32Array(0),this.color=new Float32Array(0),this.distance=new Float32Array(0)}reserve(t){if(t>this.size.length){const e=Math.max(t,2*this.size.length,64);this.position=new Float32Array(3*e),this.side=new Float32Array(3*e),this.size=new Float32Array(e),this.color=new Float32Array(4*e),this.distance=new Float32Array(e)}return this}writePoint(t,e,i,s,n){const r=3*t;if(n){const t=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);this.position[r]=(n[0]*e+n[4]*i+n[8]*s+n[12])*t,this.position[r+1]=(n[1]*e+n[5]*i+n[9]*s+n[13])*t,this.position[r+2]=(n[2]*e+n[6]*i+n[10]*s+n[14])*t}else this.position[r]=e,this.position[r+1]=i,this.position[r+2]=s}writeSide(t,e,i,s,n){const r=3*t;n?(this.side[r]=n[0]*e+n[4]*i+n[8]*s,this.side[r+1]=n[1]*e+n[5]*i+n[9]*s,this.side[r+2]=n[2]*e+n[6]*i+n[10]*s):(this.side[r]=e,this.side[r+1]=i,this.side[r+2]=s)}writeColor(t,e,i,s,n){const r=4*t;this.color[r]=e,this.color[r+1]=i,this.color[r+2]=s,this.color[r+3]=n}}function sr(t,e,i){return Math.sqrt(Math.sqrt((t[i]-t[e])**2+(t[i+1]-t[e+1])**2+(t[i+2]-t[e+2])**2))}class nr extends Ds{constructor(t,e,i=null){super(t,e,i),this.uv1Buffer=null,this.drawsNothing=!1,this.vector2_=new ot,this.vector3_=new ot,this.quaternion_=new rt,this.samples_=new ir,this.curve_=new ir,this.cutScratch_=new ir,this.maxParticles=1024,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh.dispose(),this.mesh=new p("trailBatch",this.scene),this.configureMesh(),this.buildGeometryBuffers()}buildGeometryBuffers(){const e=this.maxParticles;this.positionBuffer=new Float32Array(3*e),this.previousBuffer=new Float32Array(3*e),this.nextBuffer=new Float32Array(3*e),this.uvBuffer=new Float32Array(2*e),this.uv1Buffer=this.usesUV1()?new Float32Array(2*e):null,this.sideBuffer=new Float32Array(e),this.widthBuffer=new Float32Array(e),this.colorBuffer=new Float32Array(4*e),this.indexBuffer=new Uint32Array(3*e);for(let t=0;t<this.sideBuffer.length;t+=2)this.sideBuffer[t]=1,this.sideBuffer[t+1]=-1;this.positionBuffer[0]=0,this.positionBuffer[1]=0,this.positionBuffer[2]=0,this.positionBuffer[3]=1,this.positionBuffer[4]=0,this.positionBuffer[5]=0,this.positionBuffer[6]=0,this.positionBuffer[7]=1,this.positionBuffer[8]=0,this.positionBuffer[9]=1,this.positionBuffer[10]=1,this.positionBuffer[11]=0,this.indexBuffer[0]=0,this.indexBuffer[1]=1,this.indexBuffer[2]=2,this.indexBuffer[3]=1,this.indexBuffer[4]=3,this.indexBuffer[5]=2,this.mesh.setVerticesData(t.PositionKind,this.positionBuffer,!0),this.mesh.setVerticesData(t.UVKind,this.uvBuffer,!0),this.uv1Buffer&&this.mesh.setVerticesData(t.UV2Kind,this.uv1Buffer,!0),this.mesh.setVerticesData(t.ColorKind,this.colorBuffer,!0,4),this.mesh.setIndices(this.indexBuffer,null,!0),this.drawsNothing=!1,this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=6);const i=this.scene.getEngine();this.previousVB=new t(i,this.previousBuffer,"previous",!0,!1,3,!1),this.nextVB=new t(i,this.nextBuffer,"next",!0,!1,3,!1),this.sideVB=new t(i,this.sideBuffer,"side",!0,!1,1,!1),this.widthVB=new t(i,this.widthBuffer,"width",!0,!1,1,!1),this.mesh.setVerticesBuffer(this.previousVB),this.mesh.setVerticesBuffer(this.nextVB),this.mesh.setVerticesBuffer(this.sideVB),this.mesh.setVerticesBuffer(this.widthVB),this.mesh.subMeshes&&this.adoptMeshBounds()}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.previousVB?.dispose(),this.nextVB?.dispose(),this.sideVB?.dispose(),this.widthVB?.dispose(),this.buildGeometryBuffers()}rebuildMaterial(){const t=Rn(this.settings,{depth:this.depth,envAtlasReady:!1,meshUV2:!1}),{defines:e,attributes:i,uniforms:s,samplers:n}=t,o=t.name,a=Wn(this.scene.getEngine());Qn(o,t.vertex,t.fragment,a);const l=new h(o,this.scene,{vertex:o,fragment:o},{attributes:i,uniforms:s,samplers:n,defines:e,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:a});this.settings.texture&&l.setTexture("map",this.settings.texture),this.bindFog(l),this.bindSoft(l),this.bindSurface(l),l.backFaceCulling=!1,this.settings.materialTransparent?l.alphaMode=this.settings.materialBlendMode:l.alphaMode=r.ALPHA_DISABLE,l.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,l.forceDepthWrite=this.settings.materialDepthWrite,l.disableDepthWrite=!this.settings.materialDepthWrite,l.depthFunction=this.settings.materialDepthTest?0:r.ALWAYS,this.mesh.material?.dispose(!1,!1),this.mesh.material=l}trailSamples(t){return this.samples_.reserve(t)}cutLastSegment(t,e,i,s,n){const r=e-1-i,o=this.cutScratch_.reserve(i+1);o.position.set(t.position.subarray(3*r,3*e)),o.side.set(t.side.subarray(3*r,3*e)),o.size.set(t.size.subarray(r,e)),o.color.set(t.color.subarray(4*r,4*e)),o.distance.set(t.distance.subarray(r,e));for(let e=1;e<=i;e++){const a=s*e,h=Math.min(i-1,Math.floor(a)),l=a-h,c=r+e;for(let e=0;e<3;e++)t.position[3*c+e]=o.position[3*h+e]*(1-l)+o.position[3*h+3+e]*l,n&&(t.side[3*c+e]=o.side[3*h+e]*(1-l)+o.side[3*h+3+e]*l);t.size[c]=o.size[h]*(1-l)+o.size[h+1]*l,t.distance[c]=o.distance[h]*(1-l)+o.distance[h+1]*l;for(let e=0;e<4;e++)t.color[4*c+e]=o.color[4*h+e]*(1-l)+o.color[4*h+4+e]*l}}tessellate(t,e,i,s,n,r){const o=this.curve_.reserve((i-1)*(s+1)+1),a=t.position,h=t.side,l=o.position,c=o.side,u=1-n;let d=0;for(let n=0;n+1<i;n++){const i=3*n,f=i+3;let m=0,p=0,y=0,g=0,v=0,x=0,w=i,b=f;if(n+1<e){w=3*(n>0?n-1:n),b=3*(n+2<e?n+2:n+1);const t=sr(a,i,f);if(t>1e-6){const e=sr(a,w,i),s=sr(a,f,b);y=u,g=u,e>1e-6&&(m=u*t/e,p=-u*t/(e+t)),s>1e-6&&(v=-u*t/(t+s),x=u*t/s)}}const S=0===m&&0===p&&0===y&&0===g&&0===v&&0===x,M=r?Math.sqrt(h[i]*h[i]+h[i+1]*h[i+1]+h[i+2]*h[i+2]):0,z=r?Math.sqrt(h[f]*h[f]+h[f+1]*h[f+1]+h[f+2]*h[f+2]):0;for(let e=0;e<=s;e++,d++){const u=e/(s+1),_=u*u,V=_*u,A=S?1-u:2*V-3*_+1,T=V-2*_+u,O=S?u:-2*V+3*_,$=V-_,P=3*d;for(let t=0;t<3;t++){const e=a[i+t],s=a[f+t],n=m*(e-a[w+t])+p*(s-a[w+t])+y*(s-e),r=g*(s-e)+v*(a[b+t]-e)+x*(a[b+t]-s);l[P+t]=A*e+T*n+O*s+$*r}if(r){let t=0,e=0,s=0;for(let n=0;n<3;n++){const r=h[i+n],o=h[f+n],a=A*r+T*(m*(r-h[w+n])+p*(o-h[w+n])+y*(o-r))+O*o+$*(g*(o-r)+v*(h[b+n]-r)+x*(h[b+n]-o));0===n?t=a:1===n?e=a:s=a}let n=Math.sqrt(t*t+e*e+s*s);if(n<=1e-6*Math.max(M,z,1e-6)){const r=u<.5?i:f;t=h[r],e=h[r+1],s=h[r+2],n=u<.5?M:z}const r=n>0?(M+(z-M)*u)/n:0;c[P]=t*r,c[P+1]=e*r,c[P+2]=s*r}o.size[d]=t.size[n]+(t.size[n+1]-t.size[n])*u,o.distance[d]=t.distance[n]+(t.distance[n+1]-t.distance[n])*u;const C=4*n,F=4*d;for(let e=0;e<4;e++)o.color[F+e]=t.color[C+e]+(t.color[C+4+e]-t.color[C+e])*u}}const f=3*(i-1),m=3*d;for(let t=0;t<3;t++)l[m+t]=a[f+t],c[m+t]=h[f+t];o.size[d]=t.size[i-1],o.distance[d]=t.distance[i-1];for(let e=0;e<4;e++)o.color[4*d+e]=t.color[4*(i-1)+e];return o}writeSweptPair(t,e,i,s,n,r,o,a){const h=this.positionBuffer;h[t]=e+n*a,h[t+1]=i+r*a,h[t+2]=s+o*a,h[t+3]=e-n*a,h[t+4]=i-r*a,h[t+5]=s-o*a}static ensureWorldMatrix(t){const e=t.emitter;!e.computeWorldMatrix||e.isSynchronized&&e.isSynchronized()||e.computeWorldMatrix(!0)}update(){let t=0,e=0,i=0;const s=this.getVisibleSystems();for(let t=0;t<s.length;t++){const e=s[t],n=e.particles,r=Yn(e.rendererEmitterSettings);for(let t=0;t<e.particleNum;t++){const e=n[t].historyCount;0!==e&&(i+=2*(e*(r+1)+1))}}i>this.maxParticles&&this.expandBuffers(i);for(let i=0;i<s.length;i++){const n=s[i],r=t;nr.ensureWorldMatrix(n);const o=this.quaternion_,a=this.vector2_,h=this.vector3_,l=n.emitter.matrixWorld;l.decompose(a,o,h);const c=n.particles,u=n.particleNum,d=this.settings.uTileCount,f=this.settings.vTileCount,m=1/d,p=1/f,y=n.worldSpace,g=(Math.abs(h.x)+Math.abs(h.y)+Math.abs(h.z))/3,v=n.rendererEmitterSettings,x=Boolean(v.uvFromHead),w=this.uv1Buffer,b=Boolean(v.colorFromParticle),S=y||Boolean(v.recordWorldSpace),M=v.sideAxis,z=v.followLocalOrigin?0:n.simulationResidual??0,_=0===z?0:z/(n.simulationStep??z),V=Math.abs(_)<1e-4?0:_,A=Yn(v),T=Hn(v),O=Zn(v),$="stretch"===O?0:"tile"===O?1:"repeatPerSegment"===O?3:2,P=Kn(v),C=tr(v)>0;for(let i=0;i<u;i++){const s=c[i],n=s.historyCount;if(0===n)continue;const r=s.historyCapacity,o=s.historyPositions,a=s.historySizes,h=s.historyDistances,u=s.historySides,v=void 0!==M&&u.length>=3*r,z=b?s.store.color:s.historyColors,_=4*s.storeIndex,{column:O,row:F}=ln(s.uvTile,d,f),I=(s.parentMatrix??l).elements,U=y||s.parentMatrix?1:g,B=S||s.parentMatrix?1:g,E=s.age<s.life,N=E&&V>0,D=n+(N?1:0),k=this.trailSamples(D);let R=s.getHistoryIndex(0);for(let t=0;t<n;t++){const e=o;if(k.writePoint(t,e[3*R],e[3*R+1],e[3*R+2],S?null:I),v){const e=u;k.writeSide(t,e[3*R],e[3*R+1],e[3*R+2],S?null:I)}k.size[t]=a[R],k.distance[t]=h[R];const i=b?_:4*R;k.writeColor(t,z[i],z[i+1],z[i+2],z[i+3]),R=R+1===r?0:R+1}if(N){const t=s.previousPosition,e=s.position,i=n;let r=e.x+(e.x-t.x)*V,a=e.y+(e.y-t.y)*V,h=e.z+(e.z-t.z)*V;if(k.writePoint(i,r,a,h,y?null:I),S&&!y){const t=1/(I[3]*r+I[7]*a+I[11]*h+I[15]),e=(I[0]*r+I[4]*a+I[8]*h+I[12])*t,i=(I[1]*r+I[5]*a+I[9]*h+I[13])*t;h=(I[2]*r+I[6]*a+I[10]*h+I[14])*t,r=e,a=i}const l=3*s.getHistoryIndex(n-1),c=r-o[l],u=a-o[l+1],d=h-o[l+2];k.distance[i]=k.distance[i-1]+Math.sqrt(c*c+u*u+d*d),v&&k.writeSide(i,M.x,M.y,M.z,I),k.size[i]=k.size[i-1];const f=s.color;k.writeColor(i,f.x,f.y,f.z,f.w)}const L=A>0?this.tessellate(k,n,D,A,T,v):k,q=A>0?(D-1)*(A+1)+1:D,J=A+1,W=E&&V<0&&n>1;let Q=1+V;if(W&&C){const t=L.distance,e=t[q-1]-t[q-1-J];if(e>1e-9){const t=s.previousPosition,i=s.position;let n=i.x-t.x,r=i.y-t.y,o=i.z-t.z;if(S&&!y){const t=I[0]*n+I[4]*r+I[8]*o,e=I[1]*n+I[5]*r+I[9]*o;o=I[2]*n+I[6]*r+I[10]*o,n=t,r=e}const a=Math.sqrt(n*n+r*r+o*o);Q=1+V*Math.min(1,a/e)}}W&&this.cutLastSegment(L,q,J,Q,v);const G=n-1+(N?V:W?Q-1:0),j=1/Math.max(.001,G),Y=(D-2)*J,H=L.position,X=L.distance,Z=X[0],K=X[q-1],tt=0===$&&K-Z>1e-6,et=1/Math.max(1e-6,K-Z),it=B*P,st=Math.floor(Z*it),nt=(f-F-1)*p,rt=(f-F)*p;for(let i=0;i<q;i++,t+=2){const s=3*i,r=i>0?s-3:s,o=i+1<q?s+3:s,a=H[s],h=H[s+1],l=H[s+2],c=L.size[i],u=3*t;if(v){const e=L.side;this.writeSweptPair(u,a,h,l,e[s],e[s+1],e[s+2],.5*c),this.widthBuffer[t]=0,this.widthBuffer[t+1]=0}else this.positionBuffer[u]=a,this.positionBuffer[u+1]=h,this.positionBuffer[u+2]=l,this.positionBuffer[u+3]=a,this.positionBuffer[u+4]=h,this.positionBuffer[u+5]=l,this.widthBuffer[t]=c*U,this.widthBuffer[t+1]=c*U;this.previousBuffer[u]=H[r],this.previousBuffer[u+1]=H[r+1],this.previousBuffer[u+2]=H[r+2],this.previousBuffer[u+3]=H[r],this.previousBuffer[u+4]=H[r+1],this.previousBuffer[u+5]=H[r+2],this.nextBuffer[u]=H[o],this.nextBuffer[u+1]=H[o+1],this.nextBuffer[u+2]=H[o+2],this.nextBuffer[u+3]=H[o],this.nextBuffer[u+4]=H[o+1],this.nextBuffer[u+5]=H[o+2];const d=2*t;let f;if(tt){const t=(X[i]-Z)*et;f=(x?1-t:t)*P}else if(1===$)f=x?(K-X[i])*it:X[i]*it-st;else{let t=i/J;if(i>Y&&(N||W)){const e=(i-Y)/J;t=N?n-1+V*e:n-2+Q*e}if(3!==$){const e=Math.min(1,t*j);f=(x?1-e:e)*P}else f=(x?G-t:t)*P}const p=(f+O)*m;this.uvBuffer[d]=p,this.uvBuffer[d+1]=nt,this.uvBuffer[d+2]=p,this.uvBuffer[d+3]=rt,w&&(w[d]=f,w[d+1]=0,w[d+2]=f,w[d+3]=1);const y=L.color,g=4*i,b=4*t;this.colorBuffer[b]=y[g],this.colorBuffer[b+1]=y[g+1],this.colorBuffer[b+2]=y[g+2],this.colorBuffer[b+3]=y[g+3],this.colorBuffer[b+4]=y[g],this.colorBuffer[b+5]=y[g+1],this.colorBuffer[b+6]=y[g+2],this.colorBuffer[b+7]=y[g+3],i+1<q&&(this.indexBuffer[3*e]=t,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+2,e++,this.indexBuffer[3*e]=t+2,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+3,e++)}}const F=n.tint;if(void 0!==F){const e=this.colorBuffer;for(let i=4*r,s=4*t;i<s;i+=4)e[i]*=F.x,e[i+1]*=F.y,e[i+2]*=F.z,e[i+3]*=F.w}this.measureSystemBounds(n,r,t)}this.refreshBoundingInfo(),this.uploadGeometry(t,e)}measureSystemBounds(t,e,i){if(i<=e||"function"!=typeof t.setWorldBounds)return;const s=this.positionBuffer;let n=1/0,r=1/0,o=1/0,a=-1/0,h=-1/0,l=-1/0;for(let t=3*e,c=3*i;t<c;t+=3){const e=s[t],i=s[t+1],c=s[t+2];e<n&&(n=e),e>a&&(a=e),i<r&&(r=i),i>h&&(h=i),c<o&&(o=c),c>l&&(l=c)}const c=this.widthBuffer;let u=0;for(let t=e;t<i;t+=2){const e=c[t];e>u&&(u=e)}t.setWorldBounds(n,r,o,a,h,l,u)}uploadGeometry(e,i){const s=this.mesh.geometry,n=s?.getIndexBuffer();if(e>0&&i>0){this.mesh.updateVerticesData(t.PositionKind,this.positionBuffer.subarray(0,3*e)),this.mesh.updateVerticesData(t.UVKind,this.uvBuffer.subarray(0,2*e)),this.uv1Buffer&&this.mesh.updateVerticesData(t.UV2Kind,this.uv1Buffer.subarray(0,2*e)),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,3*i),0),this.previousVB.update(this.previousBuffer.subarray(0,3*e)),this.nextVB.update(this.nextBuffer.subarray(0,3*e)),this.widthVB.update(this.widthBuffer.subarray(0,e));const s=this.mesh.getVertexBuffer(t.ColorKind);s&&s.update(this.colorBuffer.subarray(0,4*e)),this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=3*i,this.mesh.subMeshes[0].verticesCount=e),this.drawsNothing=!1}else this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.drawsNothing||(this.indexBuffer.fill(0,0,6),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,6),0),this.drawsNothing=!0),this.mesh.subMeshes[0].indexCount=6,this.mesh.subMeshes[0].verticesCount=1)}adoptMeshBounds(){const t=this.mesh.getBoundingInfo();for(const e of this.mesh.subMeshes)e._boundingInfo=t}dispose(){this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}class rr extends n{constructor(t,e){super(t,e),this.warnedAboutTransform=!1,this.batches=[],this.elapsed=0,this.systemToBatchIndex=new Map,this.depth=null,this.systems=[],this.orderedSystems=[],this.orderedSystemsStale=!0,this.batchEmptyFrames=[],this.adaptivePerformanceState={enabled:!1,targetFrameMs:16.7,minQuality:.35,maxQuality:1,decreaseStep:.08,increaseStep:.02,currentQuality:1,lastFrameCpuMs:0},this.lastAppliedQuality=Number.NaN,this.meshLighting=ws(),this.cullingEnabled=!0,this.catchUpBudgetMs=2,this.simulationBudgetMs=1/0,this.frustumPlanes=[],this.boundsMin=new ot,this.boundsMax=new ot}collectFrustumPlanes(){const t=this.getScene(),e=this.frustumPlanes,n=t.activeCameras,r=t.activeCamera,o=n&&n.length>0?n:r?[r]:[],a=6*o.length;for(;e.length<a;)e.push(new s(0,0,0,0));e.length=a;for(let t=0;t<o.length;t++){const s=o[t];s.getViewMatrix(),s.getProjectionMatrix();const n=s.getTransformationMatrix(),r=0===t?e:e.slice(6*t,6*t+6);if(i.GetPlanesToRef(n,r),0!==t)for(let i=0;i<6;i++)e[6*t+i]=r[i]}return e}isSystemInView(t,e){const i=this.boundsMin,s=this.boundsMax;if(!t.getWorldBounds(i,s))return!0;for(let t=0;t<e.length;t+=6){let n=!0;for(let r=t;r<t+6;r++){const t=e[r],o=t.normal,a=o.x>=0?s.x:i.x,h=o.y>=0?s.y:i.y,l=o.z>=0?s.z:i.z;if(o.x*a+o.y*h+o.z*l+t.d<0){n=!1;break}}if(n)return!0}return!1}static clamp(t,e,i){return Math.max(e,Math.min(i,t))}addSystem(t){if(this.isDisposed())throw new Error("BatchedRenderer.addSystem: the renderer has been disposed");const e=t,i=e._renderer;void 0!==i&&i!==this&&i.deleteSystem(t),e._renderer=this,this.removeFromBatch(t),-1===this.systems.indexOf(t)&&(this.systems.push(t),this.orderedSystemsStale=!0),this.adaptivePerformanceState.enabled&&e.setQualityFactor(this.adaptivePerformanceState.currentQuality),this.assignToBatch(e)}assignToBatch(t){const e=t,i=t.getRendererSettings(),s=Ws(i);for(let t=0;t<this.batches.length;t++)if(js(this.batches[t].settings,s))return this.batches[t].addSystem(e),void this.systemToBatchIndex.set(e,t);let n;const r=this.getScene();switch(i.renderMode){case xs.Trail:n=new nr(i,r,this.depth);break;case xs.Mesh:case xs.BillBoard:case xs.VerticalBillBoard:case xs.HorizontalBillBoard:case xs.StretchedBillBoard:case xs.Beam:n=new Gn(i,r,this.depth);break;default:throw new Error(`Unsupported render mode: ${i.renderMode}`)}n.mesh.parent=this,n.applyMeshLighting(this.meshLighting),n.addSystem(e),this.batches.push(n),this.batchEmptyFrames.push(0),this.systemToBatchIndex.set(e,this.batches.length-1)}deleteSystem(t){const e=this.removeFromBatch(t),i=this.systems.indexOf(t);-1!==i&&(this.systems.splice(i,1),this.orderedSystemsStale=!0);const s=this.orderedSystems.indexOf(t);return-1!==s&&this.orderedSystems.splice(s,1),e}removeFromBatch(t){const e=this.systemToBatchIndex.get(t);return void 0!==e&&(this.batches[e].removeSystem(t),this.systemToBatchIndex.delete(t),!0)}updateSystem(t){const e=this.systemToBatchIndex.get(t);if(void 0!==e){const i=this.batches[e],s=Ws(t.getRendererSettings());if(1===i.systems.size&&Qs(i.settings,s)&&!this.batches.some(t=>t!==i&&js(t.settings,s)))return void i.applyLiveSettings(s)}this.removeFromBatch(t),this.addSystem(t)}setDepthTexture(t,e={}){this.depth=t?ys(t,e):null;for(const t of this.batches)t.applyDepthTexture(this.depth)}get depthTexture(){return this.depth?.texture??null}set depthTexture(t){this.setDepthTexture(t)}get depthEncoding(){return this.depth?.encoding??null}setMeshLighting(t){const e=this.meshLighting;t.direction&&(e.direction=t.direction.clone()),t.color&&(e.color=t.color.clone()),t.ambient&&(e.ambient=t.ambient.clone());for(const t of this.batches)t.applyMeshLighting(e)}getMeshLighting(){const t=this.meshLighting;return{direction:t.direction.clone(),color:t.color.clone(),ambient:t.ambient.clone()}}configureAdaptivePerformance(t={}){const e=this.adaptivePerformanceState,i=rr.clamp(t.minQuality??e.minQuality,.05,1),s=rr.clamp(t.maxQuality??e.maxQuality,i,1);e.targetFrameMs=Math.max(t.targetFrameMs??e.targetFrameMs,.1),e.minQuality=i,e.maxQuality=s,e.decreaseStep=Math.max(t.decreaseStep??e.decreaseStep,.001),e.increaseStep=Math.max(t.increaseStep??e.increaseStep,.001),e.currentQuality=rr.clamp(e.currentQuality,e.minQuality,e.maxQuality),e.enabled=!0,this.lastAppliedQuality=Number.NaN}disableAdaptivePerformance(t=!0){this.adaptivePerformanceState.enabled=!1,t&&(this.adaptivePerformanceState.currentQuality=this.adaptivePerformanceState.maxQuality,this.applyAdaptiveQuality())}getAdaptivePerformanceState(){return{...this.adaptivePerformanceState}}applyAdaptiveQuality(){const t=this.adaptivePerformanceState.currentQuality;if(t!==this.lastAppliedQuality){for(let e=0;e<this.systems.length;e++)this.systems[e].setQualityFactor(t);this.lastAppliedQuality=t}}_invalidateUpdateOrder(){this.orderedSystemsStale=!0}orderSystems(){if(!this.orderedSystemsStale)return this.orderedSystems;const t=[],e=new Set,i=new Set,s=new Set(this.systems),n=r=>{if(!i.has(r)&&!e.has(r)){e.add(r);for(const t of(t=>{const e=[];for(const i of t.behaviors??[]){if("EmitSubParticleSystem"!==i.type)continue;const t=i.subParticleSystem?.system;void 0!==t&&s.has(t)&&e.push(t)}return e})(r))n(t);e.delete(r),i.add(r),t.push(r)}};for(const t of this.systems)n(t);return t.reverse(),this.orderedSystems=t,this.orderedSystemsStale=!1,t}update(t){this.elapsed+=t,this.warnedAboutTransform||this.getWorldMatrix().isIdentity()||(this.warnedAboutTransform=!0,console.warn(`[babylon.quarks] BatchedRenderer "${this.name}" is transformed; particles are placed in the world by their emitters, so the renderer's own transform moves them again. Keep the renderer at the origin.`));const e=this.adaptivePerformanceState,i=e.enabled?performance.now():0;e.enabled&&this.applyAdaptiveQuality();const s=this.orderSystems(),n=this.cullingEnabled?this.collectFrustumPlanes():null,r=this.simulationBudgetMs!==1/0||this.catchUpBudgetMs!==1/0?performance.now():0,o=this.simulationBudgetMs===1/0?1/0:r+this.simulationBudgetMs,a=this.catchUpBudgetMs===1/0?1/0:r+this.catchUpBudgetMs;for(let e=0;e<s.length;e++){const i=s[e];i.emitter.visible&&(i.culled=null!==n&&n.length>0&&"always"!==i.cullingMode&&!0!==i.onlyUsedByOther&&!this.isSystemInView(i,n),i.update(t,o,a)),s[e]!==i&&e--}this.refreshBatches(),e.enabled&&(e.lastFrameCpuMs=performance.now()-i,e.lastFrameCpuMs>e.targetFrameMs?e.currentQuality=rr.clamp(e.currentQuality-e.decreaseStep,e.minQuality,e.maxQuality):e.currentQuality=rr.clamp(e.currentQuality+e.increaseStep,e.minQuality,e.maxQuality))}refreshBatches(){const t=this.batchEmptyFrames;for(let e=0;e<this.batches.length;e++){const i=this.batches[e];if(i.time=this.elapsed,i.systems.size>0){t[e]=0,i.update();continue}const s=(t[e]??0)+1;t[e]=s,1===s?i.update():s>rr.EMPTY_BATCH_GRACE_FRAMES&&(this.removeBatch(e),e--)}}removeBatch(t){this.batches[t].dispose(),this.batches.splice(t,1),this.batchEmptyFrames.splice(t,1);for(const[e,i]of this.systemToBatchIndex)i>t&&this.systemToBatchIndex.set(e,i-1)}getBatchRenderStats(){return this.batches.map((t,e)=>{let i=0;const s=[];for(const e of t.systems){const t=e;i+=t.particleNum,s.push(t.emitter.name)}return{batchIndex:e,renderMode:t.settings.renderMode,instanceCount:t.mesh.forcedInstanceCount??0,particleCount:i,systemNames:s}})}dispose(){for(const t of this.batches)t.dispose();this.batches=[],this.batchEmptyFrames.length=0;for(const t of this.systems)t._renderer===this&&(t._renderer=void 0);this.systems.length=0,this.orderedSystems=[],this.orderedSystemsStale=!0,this.systemToBatchIndex.clear(),super.dispose()}}rr.EMPTY_BATCH_GRACE_FRAMES=120;const or=new WeakMap,ar=new WeakMap;function hr(t,e,i){if(or.has(t))return;const s={textures:new Set(e),materials:i};for(const t of s.textures)ar.set(t,(ar.get(t)??0)+1);or.set(t,s),t.onDisposeObservable.addOnce(()=>lr(t))}function lr(t){const e=or.get(t);if(void 0!==e){or.delete(t);for(const t of e.materials)t.dispose();for(const t of e.textures){const e=(ar.get(t)??1)-1;e>0?ar.set(t,e):(ar.delete(t),t.dispose())}}}function cr(t){t.dispose(),lr(t)}let ur=0;class dr extends n{get matrixWorld(){const t=this.getWorldMatrix(),e=t.updateFlag;if(e===this._matrixWorldFlag)return this._matrixWorld;this._matrixWorldFlag=e;const i=this._matrixWorld.elements,s=t.m;return i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],i[4]=s[4],i[5]=s[5],i[6]=s[6],i[7]=s[7],i[8]=s[8],i[9]=s[9],i[10]=s[10],i[11]=s[11],i[12]=s[12],i[13]=s[13],i[14]=s[14],i[15]=s[15],this._matrixWorld}get visible(){return this.isEnabled()}set visible(t){this.setEnabled(t)}get uuid(){return ns(this)}constructor(t,e){super("particleEmitter",e||void 0),this._matrixWorld=new ut,this._matrixWorldFlag=-1,this.system=t}dispose(t,e=!1){this.isDisposed()||(super.dispose(t,e),ur>0||this.system.dispose?.())}clone(t){const e=this.system.clone().emitter;return e.name=t??this.name,e.position.copyFrom(this.position),e.rotation.copyFrom(this.rotation),e.scaling.copyFrom(this.scaling),this.rotationQuaternion&&(e.rotationQuaternion=this.rotationQuaternion.clone()),e.setEnabled(this.isEnabled(!1)),e}toJSON(t,e={}){return{uuid:ns(this),type:"ParticleEmitter",name:this.name,position:[this.position.x,this.position.y,this.position.z],rotation:[this.rotation.x,this.rotation.y,this.rotation.z],quaternion:this.rotationQuaternion?[this.rotationQuaternion.x,this.rotationQuaternion.y,this.rotationQuaternion.z,this.rotationQuaternion.w]:void 0,scale:[this.scaling.x,this.scaling.y,this.scaling.z],visible:this.isEnabled(),ps:this.system.toJSON(t,e)}}}class fr{static runOnAllParticleEmitters(t,e){fr.traverseNode(t,t=>{t instanceof dr&&e(t)})}static addToBatchRenderer(t,e){fr.runOnAllParticleEmitters(t,t=>{e.addSystem(t.system)})}static play(t){fr.runOnAllParticleEmitters(t,t=>{t.system.play()})}static stop(t){fr.runOnAllParticleEmitters(t,t=>{t.system.stop()})}static pause(t){fr.runOnAllParticleEmitters(t,t=>{t.system.pause()})}static restart(t){fr.runOnAllParticleEmitters(t,t=>{t.system.restart()})}static setAutoDestroy(t,e){fr.runOnAllParticleEmitters(t,t=>{t.system.autoDestroy=e})}static endEmit(t){fr.runOnAllParticleEmitters(t,t=>{t.system.endEmit()})}static isEffectFinished(t){let e=!1,i=!0;return fr.runOnAllParticleEmitters(t,t=>{e=!0,t.system.isFinished()||(i=!1)}),e&&i}static instantiate(t,e){const i=new Map,s=(t,e,r)=>{let o;if(t instanceof dr)o=t.clone(r),i.set(t,o);else{if(!(t instanceof n))return null;o=new n(r??t.name,t.getScene()),o.position.copyFrom(t.position),o.rotation.copyFrom(t.rotation),o.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(o.rotationQuaternion=t.rotationQuaternion.clone()),o.setEnabled(t.isEnabled(!1))}o.parent=e;for(const e of t.getChildren())s(e,o);return o},r=s(t,null,e);!function(t,e){for(let i=t;null!==i;i=i.parent){const t=or.get(i);if(void 0!==t)return void hr(e,t.textures,[])}}(t,r);for(const t of i.values())for(const e of t.system.behaviors)if(e instanceof Le){const t=i.get(e.subParticleSystem);void 0!==t&&(e.subParticleSystem=t)}return r}static getDuration(t){const e=[];fr.runOnAllParticleEmitters(t,t=>{e.push(t.system)});const i=new Map;for(let t=0;t<e.length;t++){const s=e[t];for(const t of s.behaviors){if(!(t instanceof Le))continue;const n=t.subParticleSystem?.system;if(void 0!==n&&"object"==typeof n){e.includes(n)||e.push(n);const t=i.get(n)??[];t.push(s),i.set(n,t)}}}const s=new Map,n=t=>{const e=s.get(t);if(void 0!==e)return e;s.set(t,1/0);const r=t.playbackSpeed,o=fr.maxOf(t.startLife)/r;let a;if(r>0)if(t.onlyUsedByOther){a=0;for(const e of i.get(t)??[])a=Math.max(a,n(e));a+=t.duration/r+o}else a=t.looping?1/0:(fr.maxOf(t.startDelay,0)+t.duration)/r+o;else a=1/0;return s.set(t,a),a};let r=0;for(const t of e)r=Math.max(r,n(t));return r}static maxOf(t,e){if(t instanceof Qt)return t.value;if(t instanceof Gt)return Math.max(t.a,t.b);let i=-1/0;for(let s=0;s<=32;s++){const n=[];t.startGen(n);const r="function"===t.type?t.genValue(n,e??s/32):t.genValue(n);i=Math.max(i,r)}return i}static traverseNode(t,e){e(t);const i=t.getChildren();for(const t of i)fr.traverseNode(t,e)}}class mr{constructor(t,e){this.template=t,this.options=e,this.idle=[],this.playing=new Set,this.systemsOf=new Map,this.disposed=!1,this.onSystemFinished=t=>{const e=t.particleSystem;for(const t of this.playing){const i=this.systemsOf.get(t);if(void 0!==i&&i.includes(e))return void(fr.isEffectFinished(t)&&this.release(t))}};for(let t=0;t<(e.prewarm??0);t++){const t=this.makeCopy();if(null===t)break;this.idle.push(t)}}get activeCount(){return this.playing.size}get idleCount(){return this.idle.length}acquire(t,e=null){if(this.disposed)return null;const i=this.idle.pop()??this.makeCopy();return null===i?null:(i.parent=e,void 0!==t&&i.position.copyFrom(t),i.setEnabled(!0),this.playing.add(i),fr.restart(i),fr.play(i),i)}stop(t){this.playing.has(t)&&fr.endEmit(t)}release(t){this.playing.delete(t)&&(fr.stop(t),t.setEnabled(!1),t.parent=null,this.disposed||this.idle.push(t))}dispose(){this.disposed=!0;for(const t of[...this.playing,...this.idle])this.playing.delete(t),this.disposeCopy(t);this.idle.length=0}makeCopy(){if(this.idle.length+this.playing.size>=(this.options.maxSize??1/0))return null;const t=fr.instantiate(this.template),e=[];return fr.runOnAllParticleEmitters(t,t=>{const i=t.system;i.autoDestroy=!1,i.addEventListener("finished",this.onSystemFinished),e.push(i)}),this.systemsOf.set(t,e),fr.addToBatchRenderer(t,this.options.renderer),t.setEnabled(!1),t.parent=null,t}disposeCopy(t){const e=this.systemsOf.get(t)??[];for(const t of e)t.removeEventListener("finished",this.onSystemFinished),this.options.renderer.deleteSystem(t),t.dispose();this.systemsOf.delete(t),cr(t)}}const pr=new WeakMap,yr=new WeakMap,gr=new WeakSet,vr=new WeakSet,xr=new WeakSet;function wr(t){if(!t?.isCube)return null;const e=t.files??t._files;return 6===e?.length?e.slice():null}function br(t){return t.getScene?.()??null}function Sr(t,e=br(t)){return e&&pr.get(t)?.get(e)||null}function Mr(t,e){const i=br(e)??br(t);i?_r(t,i,e):console.warn("[babylon.quarks] cacheEnvAtlas: neither the atlas nor the cube has a scene; not cached")}function zr(t,e){const i=pr.get(t);if(i)for(const[t,s]of[...i])e&&t!==e||(i.delete(t),gr.has(s)&&s.dispose())}function _r(t,e,i){let s=pr.get(t);s||(s=new Map,pr.set(t,s)),s.set(e,i),!vr.has(i)&&i.onDisposeObservable&&(vr.add(i),i.onDisposeObservable.addOnce(()=>{pr.get(t)?.get(e)===i&&pr.get(t).delete(e)})),!xr.has(t)&&t.onDisposeObservable&&(xr.add(t),t.onDisposeObservable.addOnce(()=>{xr.delete(t),zr(t)}))}async function Vr(t,e){if("undefined"==typeof document||"undefined"==typeof Image)throw new Error("createEnvAtlasFromFaceUrls requires a DOM Image/canvas environment");const i=await Promise.all(t.map(t=>function(t){return new Promise((e,i)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>e(s),s.onerror=()=>i(new Error(`Failed to load env face ${t}`)),s.src=t})}(t))),s=i[0].width||i[0].naturalWidth;if(!s)throw new Error("Env atlas face image has zero size");const n=document.createElement("canvas");n.width=3*s,n.height=2*s;const r=n.getContext("2d");if(!r)throw new Error("Could not create env atlas canvas");for(let t=0;t<6;t++)r.drawImage(i[t],t%3*s,Math.floor(t/3)*s,s,s);const o=new M(n.toDataURL("image/jpeg",.92),e,{noMipmap:!0,invertY:!1,samplingMode:M.LINEAR_LINEAR});return o.name="quarksEnvAtlas",o}const Ar={createFromFaceUrls:Vr};function Tr(t,e,i){const s=Sr(t,e);if(s)return i(s),s;let n=yr.get(t);n||(n=new Map,yr.set(t,n));const r=n,o=()=>{const s=r.get(e);if(s)return void s.then(t=>{t&&i(t)});const n=wr(t);if(!n)return;let o=!1;const a=t.onDisposeObservable?.addOnce(()=>o=!0),h=()=>{r.delete(e),a&&t.onDisposeObservable.remove(a)},l=Ar.createFromFaceUrls(n,e).then(s=>(h(),o||e.isDisposed?(s.dispose(),null):(gr.add(s),_r(t,e,s),i(s),s))).catch(t=>(h(),console.warn("[babylon.quarks] Failed to build env atlas from cubemap faces",t),null));r.set(e,l)};if(t.isReady())o();else{const e=t.onLoadObservable;e?e.addOnce(()=>o()):o()}return Sr(t,e)}function Or(t,e){if(e&&e.length>0)return e;const i=t.length/3,s=new Uint32Array(i);for(let t=0;t<i;t++)s[t]=t;return s}const $r=new Set(["SizeOverLife","SizeBySpeed"]),Pr=new Set(["ColorOverLife","ColorBySpeed"]),Cr=new Set(["ApplyForce","Noise","TurbulenceField","GravityForce","RotationOverLife","Rotation3DOverLife","RotationBySpeed","SpeedOverLife","FrameOverLife","ForceOverLife","VelocityOverLife","InheritVelocity","OrbitOverLife","WidthOverLength","ChangeEmitDirection","EmitSubParticleSystem","LimitSpeedOverLife","ApplyCollision"]);class Fr{constructor(){this.fusionSteps=[],this.changesSize=!0,this.changesColor=!0}steps(t){const e=this.plan;if(void 0!==e&&e.length===t.length){let i=!0;for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}if(i)return this.fusionSteps}this.plan=t.slice(),this.fusionSteps=Ni(t);let i=!1,s=!1;for(let e=0;e<t.length;e++){const n=t[e].type;$r.has(n)?i=!0:Pr.has(n)?s=!0:Cr.has(n)||(i=!0,s=!0)}return this.changesSize=i,this.changesColor=s,this.fusionSteps}}function Ir(t){return Math.sqrt(Math.max(t[0]*t[0]+t[1]*t[1]+t[2]*t[2],t[4]*t[4]+t[5]*t[5]+t[6]*t[6],t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}class Ur{constructor(){this.min=new ot,this.max=new ot,this.padding=0,this.valid=!1,this.stepsSince=0,this.maxSize=0,this.maxSpeedSq=0,this.inWorld=!1,this.geometryRadius=1}get due(){return this.stepsSince>=4||!this.valid}store(t,e,i,s,n,r,o,a,h,l,c,u,d,f){if(0===t)return void(this.valid=!1);this.stepsSince=e?0:this.stepsSince+1,this.maxSize=h,this.maxSpeedSq=l;const m=Math.sqrt(l),p=c.renderMode;let y=m*f*(this.stepsSince+1);if(p===xs.Mesh)y+=h*this.meshGeometryRadius(c.instancingGeometry);else if(p===xs.StretchedBillBoard){const t=u;y+=h*(1+(t.lengthFactor??0)+m*(t.speedFactor??0))}else{const t=c.pivot;y+=h*(.75+(void 0===t?0:Math.abs(t.x)+Math.abs(t.y)+Math.abs(t.z)))}this.min.set(i,s,n),this.max.set(r,o,a),this.padding=y,this.inWorld=d,this.valid=!0}setWorld(t,e,i,s,n,r,o){this.min.set(t,e,i),this.max.set(s,n,r),this.padding=o,this.inWorld=!0,this.valid=!0}worldPadding(t){return this.inWorld?this.padding:this.padding*Ir(t.matrixWorld.elements)}toWorld(t,e,i){if(!this.valid)return!1;const s=this.min,n=this.max;if(this.inWorld){const i=this.padding;return t.set(s.x-i,s.y-i,s.z-i),e.set(n.x+i,n.y+i,n.z+i),!0}const r=i.matrixWorld.elements,o=this.padding*Ir(r);let a=1/0,h=1/0,l=1/0,c=-1/0,u=-1/0,d=-1/0;for(let t=0;t<8;t++){const e=1&t?n.x:s.x,i=2&t?n.y:s.y,o=4&t?n.z:s.z,f=1/(r[3]*e+r[7]*i+r[11]*o+r[15]),m=(r[0]*e+r[4]*i+r[8]*o+r[12])*f,p=(r[1]*e+r[5]*i+r[9]*o+r[13])*f,y=(r[2]*e+r[6]*i+r[10]*o+r[14])*f;m<a&&(a=m),m>c&&(c=m),p<h&&(h=p),p>u&&(u=p),y<l&&(l=y),y>d&&(d=y)}return t.set(a-o,h-o,l-o),e.set(c+o,u+o,d+o),!0}meshGeometryRadius(t){if(t!==this.geometryRadiusFor){let e=0;for(let i=0;i+2<t.length;i+=3){const s=t[i]*t[i]+t[i+1]*t[i+1]+t[i+2]*t[i+2];s>e&&(e=s)}this.geometryRadius=Math.sqrt(e),this.geometryRadiusFor=t}return this.geometryRadius}}function Br(t){return t.cycle>=1?Math.floor(t.cycle):1}function Er(t){return t.interval>0?t.interval:0}class Nr{constructor(t,e){this.system=t,this.spawner=e,this.memory=[],this.pathMatrix=new ut,this.temp=new ot}rollGenerators(){const t=this.system,e=this.memory;t.emissionBursts.forEach(t=>t.count.startGen(e)),t.emissionOverDistance.startGen(e),t.startDelay.startGen(e);const i=t.startDelay.genValue(e,0);return t.emissionOverTime.startGen(e),i}hasPendingEmission(){const t=this.system;if(t.isEmitEnded)return!1;if(t.looping)return!0;if(t.onlyUsedByOther)return!1;const e=t.emissionState;if(e.waitEmiting>0)return!0;if(e.burstIndex<t.emissionBursts.length)return!0;if(this.hasPendingBurstWaves(e))return!0;if(e.time>=t.duration)return!1;const i=e.time/t.duration;return this.emitsFrom(t.emissionOverTime,i)||this.emitsFrom(t.emissionOverDistance,i)}emitsFrom(t,e){if(t.genValue(this.memory,e)>0)return!0;if("function"!==t.type)return!1;if(t instanceof Ht){for(let i=0;i<t.functions.length;i++)if(t.getEndX(i)>e&&t.functions[i][0].p.some(t=>t>0))return!0;return!1}for(let i=1;i<=64;i++)if(t.genValue(this.memory,e+(1-e)*i/64)>0)return!0;return!1}hasPendingBurstWaves(t){const e=t.burstWaves;if(void 0===e)return!1;const i=this.system.emissionBursts,s=this.system.duration;for(let n=0;n<t.burstIndex&&n<i.length;n++){const t=i[n],r=e[n]??0;if(r<Br(t)&&(0===r||t.time+r*Er(t)<=s))return!0}return!1}emit(t,e,i){const s=this.system;if(s.isDisposed)return;const n=s.duration,r=s.isEmitEnded&&e===s.emissionState;if(e.time>n)if(s.looping){e.time-=n,e.burstIndex=0,void 0!==e.burstWaves&&(e.burstWaves.length=0);const t=s.behaviors;for(let e=0;e<t.length;e++)t[e].reset()}else s.isEmitEnded||s.onlyUsedByOther||s.endEmit();s.worldSpace&&this.spawner.normalMatrix.getNormalMatrix(i);const o=s.emissionFactor();s.emissionBursts.length>0&&!r&&this.emitBursts(e,i);let a=0,h=0,l=0,c=0;const u=e.previousWorldPos;if(!s.isEmitEnded){const r=e.time/n;if(e.waitEmiting+=t*s.emissionOverTime.genValue(this.memory,r)*o,void 0!==u){this.temp.set(i.elements[12],i.elements[13],i.elements[14]),c=u.distanceTo(this.temp);const t=s.emissionOverDistance.genValue(this.memory,r)*o;if(t>0){l=e.travelDistance,e.travelDistance+=c;const i=Math.floor(e.travelDistance*t);i>0&&(e.travelDistance-=i/t,s.worldSpace&&c>0?(a=i,h=1/t):e.waitEmiting+=i)}else e.travelDistance=0}}const d=Math.floor(e.waitEmiting);d>0&&(this.spawner.spawn(d,e,i),e.waitEmiting-=d),a>0&&this.spawnAlongPath(a,e,i,u,l,h,c),void 0===e.previousWorldPos&&(e.previousWorldPos=new ot),e.previousWorldPos.set(i.elements[12],i.elements[13],i.elements[14]),e.time+=t}emitBursts(t,e){const i=this.system.emissionBursts,s=this.system.duration,n=i.length,r=t.time,o=t.burstWaves??(t.burstWaves=[]);for(;t.burstIndex<n&&i[t.burstIndex].time<=r;)o[t.burstIndex]=0,t.burstIndex++;const a=t.burstIndex;for(let n=0;n<a;n++){const a=i[n],h=Br(a);let l=o[n]??0;if(l>=h)continue;const c=Er(a);for(;l<h;){const i=a.time+l*c;if(l>0&&i>s){l=h;break}if(i>r)break;t.burstWaveIndex=l,this.fireBurstWave(a,t,e),l++}o[n]=l}}fireBurstWave(t,e,i){if(A()>=t.probability)return;const s=t.count.genValue(this.memory,e.time/this.system.duration),n=this.system.emissionFactor(),r=Math.abs(n-1)<.001?s:Math.floor(s*n+A());e.isBursting=!0,e.burstParticleCount=r,this.spawner.spawn(r,e,i),e.isBursting=!1}spawnAlongPath(t,e,i,s,n,r,o){const a=this.pathMatrix.copy(i),h=i.elements,l=a.elements,c=h[12],u=h[13],d=h[14];for(let i=1;i<=t;i++){const t=i*r-n,h=t<=0?0:t>=o?1:t/o;l[12]=s.x+(c-s.x)*h,l[13]=s.y+(u-s.y)*h,l[14]=s.z+(d-s.z)*h,this.spawner.spawn(1,e,a)}}}class Dr{constructor(){this.listeners={}}add(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}removeAll(t){this.listeners[t]&&(this.listeners[t]=[])}remove(t,e){if(this.listeners[t]){const i=this.listeners[t].indexOf(e);-1!==i&&this.listeners[t].splice(i,1)}}has(t){const e=this.listeners[t];return void 0!==e&&e.length>0}fire(t){const e=this.listeners[t.type];if(void 0!==e)for(let i=0;i<e.length;i++)e[i](t)}}const kr=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),Rr=new Float32Array([0,0,1,0,1,1,0,1]),Lr=new Uint32Array([0,1,2,0,2,3]),qr=new WeakMap,Jr=new WeakMap;function Wr(t){let e=qr.get(t);return void 0!==e&&e.length===t.length/3*2||(e=new Float32Array(t.length/3*2),qr.set(t,e)),e}function Qr(t){let e=Jr.get(t);if(!e){e=new Float32Array(t.length);for(let t=2;t<e.length;t+=3)e[t]=1;Jr.set(t,e)}return e}const Gr=1/60;class jr{constructor(){this.accumulator=0,this.pendingCatchUp=0,this.delayLeft=0}reset(){this.accumulator=0,this.pendingCatchUp=0}setStartDelay(t){this.delayLeft=t>0?t:0}get delaying(){return this.delayLeft>0}static frameSeconds(t,e){if(!(t>0))return 0;return(t>.1?.1:t)*e}consumeStartDelay(t){if(this.delayLeft<=0)return t;if(this.delayLeft-=t,this.delayLeft>=0)return 0;const e=Math.min(-this.delayLeft,.1);return this.delayLeft=0,e}accrue(t,e=1){this.accumulator+=t;const i=e>1?Math.ceil(8*e):8,s=Math.min(i,Math.max(0,Math.round(this.accumulator/Gr-1e-9)));return this.accumulator-=s*Gr,s}get residual(){return this.accumulator>Gr?Gr:this.accumulator<-Gr?-Gr:this.accumulator}deferCatchUp(t){this.pendingCatchUp=Math.min(2,this.pendingCatchUp+t)}get owesCatchUp(){return this.pendingCatchUp>0}takeCatchUpSteps(){const t=Math.floor(this.pendingCatchUp/Gr);return this.pendingCatchUp=0,t}}const Yr=new ot;function Hr(t,e,i,s){const n=t[i],r=t[s];return t[i]=r,t[s]=n,i!==s&&(e.swapRows(i,s),r.setStoreIndex(i),n.setStoreIndex(s)),n}function Xr(t){return t?.getScene()?t:null}const Zr=new ot(0,0,1),Kr=new rt,to=new rt,eo=new ot,io=new ot;class so{constructor(t){this.system=t,this.normalMatrix=new St}rebind(){const t=this.system.particles;for(let e=0;e<t.length;e++)t[e].rebind()}grow(t){const e=this.system,i=e.particles.length;e.store.ensureCapacity(i+1)&&this.rebind(),e.particles.push(t?new Ce(e.store,i):new Oe(e.store,i))}spawn(t,e,i){const s=this.system,n=eo,r=io;i.decompose(n,to,r);const o=s.behaviors,a=o.length,h=s.rendererSettings.renderMode,l=h===xs.Trail,c=!l,u=h===xs.Mesh,d=s.startRotation,f=s.startSize,m="rotation"===d.type,p="vec3function"===f.type,y=e.time/s.duration,g=l?s.rendererEmitterSettings:void 0,v=Boolean(g?.followLocalOrigin),x=s.worldSpace,w="hierarchy"===s.scalingMode,b=s.particles;void 0!==s.maxParticles&&(t=Math.min(t,Math.max(0,s.maxParticles-s.particleNum)));for(let n=0;n<t;n++){e.burstParticleIndex=n,s.particleNum++,b.length<s.particleNum&&this.grow(l);const t=b[s.particleNum-1];if(t.reset(),t.serial=(t.serial??0)+1,t.speedModifier=1,s.finishedEventFired=!1,s.startColor.startGen(t.memory),s.startColor.genColor(t.memory,t.startColor,y),t.color.copy(t.startColor),s.startSpeed.startGen(t.memory),t.startSpeed=s.startSpeed.genValue(t.memory,y),s.startLife.startGen(t.memory),t.life=s.startLife.genValue(t.memory,y),t.age=0,f.startGen(t.memory),p)f.genValue(t.memory,t.startSize,y);else{const e=f.genValue(t.memory,y);t.startSize.set(e,e,e)}if(s.startTileIndex.startGen(t.memory),t.uvTile=s.startTileIndex.genValue(t.memory),t.size.copy(t.startSize),c){const e=t;if(d.startGen(t.memory),u)e.rotation instanceof rt||(e.rotation=Kr),e.angularVelocity instanceof rt&&e.angularVelocity.set(0,0,0,1),m?d.genValue(t.memory,e.rotation,1,y):e.rotation.setFromAxisAngle(Zr,d.genValue(e.memory,y));else{e.rotation=m?0:d.genValue(e.memory,y),e.angularVelocity=0;const t=s.flip;e.flip=void 0===t?0:(A()<t.x?1:0)|(A()<t.y?2:0)}}else if(g){const e=t;g.startLength.startGen(e.memory),e.length=g.startLength.genValue(e.memory,y),e.ensureHistoryCapacity(Math.max(1,Math.ceil(e.length))),e.resetHistory()}s.emitterShape.initialize(t,e),s.alignToDirection&&c&&no(t,u);const h=e.particle,S=e.inherit;if(void 0!==h&&void 0!==S&&0!==S&&ro(t,h,S,c),l&&v){const e=t;e.localPosition||(e.localPosition=new ot),e.localPosition.copy(e.position)}x?(t.position.applyMatrix4(i),t.startSize.multiply(r).abs(),t.size.copy(t.startSize),w?t.velocity.multiply(s.hierarchyScale).applyQuaternion(to):t.velocity.multiply(r).applyMatrix3(this.normalMatrix),t.rotation&&t.rotation instanceof rt&&t.rotation.multiplyQuaternions(to,t.rotation)):s.onlyUsedByOther&&(t.parentMatrix=i);for(let e=0;e<a;e++)o[e].initialize(t,s);s.store.recordMemory(t.storeIndex,t.memory)}}}function no(t,e){const i=t.velocity,s=i.x*i.x+i.y*i.y+i.z*i.z;if(0!==s)if(e){const e=t.rotation;eo.copy(i).divideScalar(Math.sqrt(s)),to.setFromUnitVectors(Zr,eo),e.multiplyQuaternions(to,e)}else 0===i.x&&0===i.y||(t.rotation=t.rotation+Math.atan2(-i.x,i.y))}function ro(t,e,i,s){if(i&ke.color&&(t.startColor.multiply(e.color),t.color.copy(t.startColor)),i&ke.size&&(t.startSize.multiply(e.size),t.size.copy(t.startSize)),i&ke.rotation&&s){const i=t,s=e.rotation;"number"==typeof i.rotation?"number"==typeof s&&(i.rotation+=s):s instanceof rt&&i.rotation.multiplyQuaternions(s,i.rotation)}i&ke.lifetime&&e.life>0&&(t.life*=Math.max(0,1-e.age/e.life))}function oo(t,e,i,s,n={}){return{param:t,json:n.json,get:e,isDefault:t=>t===i,toJSON:t=>t,fromJSON:s,clone:t=>t}}function ao(t){return"number"==typeof t?t:void 0}function ho(t){return"number"==typeof t?ds(t):void 0}function lo(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:void 0}function co(t){return"number"==typeof t?0!==t:"boolean"==typeof t?t:void 0}function uo(t,e,i,s,n=!0){const r=JSON.stringify(i().toJSON());return{param:t,always:n,get:e,isDefault:t=>JSON.stringify(t.toJSON())===r,toJSON:t=>t.toJSON(),fromJSON:t=>"number"==typeof t?new Qt(t):s(t),clone:t=>t.clone()}}function fo(t){const e=t;if(void 0!==e)return void 0===e.z?[e.x,e.y]:[e.x,e.y,e.z]}const mo=[oo("autoDestroy",t=>t.autoDestroy,!1,co),oo("looping",t=>t.looping,!0,co),oo("prewarm",t=>t.prewarm,!1,co),oo("prewarmTime",t=>t.prewarmTime,0,ao),oo("duration",t=>t.duration,1,ao),uo("startDelay",t=>t.startDelay,()=>new Qt(0),Xt,!1),uo("startLife",t=>t.startLife,()=>new Qt(5),Xt),uo("startSpeed",t=>t.startSpeed,()=>new Qt(0),Xt),uo("startRotation",t=>t.startRotation,()=>new Qt(0),t=>fe(t)),uo("startSize",t=>t.startSize,()=>new Qt(1),t=>fe(t)),uo("startColor",t=>t.startColor,()=>new oe(new Pt(1,1,1,1)),t=>ae(t)),uo("emissionOverTime",t=>t.emissionOverTime,()=>new Qt(10),Xt),uo("emissionOverDistance",t=>t.emissionOverDistance,()=>new Qt(0),Xt),{param:"emissionBursts",get:t=>t.emissionBursts,isDefault:t=>0===t.length,toJSON:t=>t.map(t=>({time:t.time,count:t.count.toJSON(),probability:t.probability,interval:t.interval,cycle:t.cycle})),fromJSON:t=>Array.isArray(t)?ps(t.map(t=>({time:t.time,count:"number"==typeof t.count?new Qt(t.count):Xt(t.count),probability:t.probability,interval:t.interval,cycle:t.cycle??t.cycleCount}))):void 0,clone:t=>t.map(t=>({...t,count:t.count.clone()}))},oo("maxParticles",t=>t.maxParticles,void 0,ao),oo("onlyUsedByOther",t=>t.onlyUsedByOther,!1,co),oo("renderMode",t=>t.renderMode,xs.BillBoard,ao),oo("renderOrder",t=>t.renderOrder,0,ao),oo("renderingGroupId",t=>t.renderingGroupId,0,ao),oo("applyFog",t=>t.applyFog,!0,t=>!1!==t),oo("playbackSpeed",t=>t.playbackSpeed,1,ao),oo("cullingMode",t=>t.cullingMode,"always",ls),oo("scalingMode",t=>t.scalingMode,"shape",t=>"hierarchy"===t?"hierarchy":"shape"),oo("seed",t=>t.seed,void 0,ao),oo("sortMode",t=>t.sortMode,"none",hs),oo("alignToDirection",t=>t.alignToDirection,!1,t=>!0===t),oo("minParticleSize",t=>t.minParticleSize,0,ao),oo("maxParticleSize",t=>t.maxParticleSize,1/0,ao),oo("layerMask",t=>t.layers.mask,268435455,ao,{json:"layers"}),uo("startTileIndex",t=>t.startTileIndex,()=>new Qt(0),Xt),oo("uTileCount",t=>t.uTileCount,1,ho),oo("vTileCount",t=>t.vTileCount,1,ho),oo("blendTiles",t=>t.blendTiles,!1,co),oo("softParticles",t=>t.softParticles,!1,co),oo("softFarFade",t=>t.softFarFade,1,lo),oo("softNearFade",t=>t.softNearFade,0,lo),oo("blendMode",t=>t.blending,r.ALPHA_ADD,ao,{json:"blending"}),oo("transparent",t=>t.transparent,!0,co),oo("depthTest",t=>t.depthTest,!0,co),oo("depthWrite",t=>t.depthWrite,!1,co),oo("alphaTest",t=>t.alphaTest,0,ao),oo("worldSpace",t=>t.worldSpace,!1,co),{param:"pivot",get:t=>t.pivot,isDefault:t=>void 0===t,toJSON:fo,fromJSON:t=>Array.isArray(t)?new ot(t[0]??0,t[1]??0,t[2]??0):void 0,clone:t=>t?.clone()},{param:"flip",get:t=>t.flip,isDefault:t=>void 0===t,toJSON:fo,fromJSON:t=>Array.isArray(t)?new At(t[0]??0,t[1]??0):void 0,clone:t=>t?.clone()}];function po(t){return t.json??t.param}function yo(t){const e={};for(const i of mo){const s=i.get(t);!i.always&&i.isDefault(s)||(e[po(i)]=i.toJSON(s))}return e}function go(t){const e={};for(const i of mo)e[i.param]=i.clone(i.get(t));return e}const vo=new WeakMap,xo=new WeakMap,wo=new WeakMap;function bo(t,e){const i=(vo.get(t)??0)+1;return vo.set(t,i),`${e}_${i}`}function So(t){const e={};return t?.uvFromHead&&(e.uvFromHead=!0),t?.colorFromParticle&&(e.colorFromParticle=!0),t?.dieWithParticle&&(e.dieWithParticle=!0),t?.recordWorldSpace&&(e.recordWorldSpace=!0),e}function Mo(t){const e={},i=Yn(t),s=Hn(t);return i>0&&(e.tessellation=i),s>0&&(e.curveTension=s),e}function zo(t){const e={},i=Zn(t),s=Kn(t),n=tr(t),r=er(t);return"stretch"!==i&&(e.textureMode=i),1!==s&&(e.textureScale=s),n>0&&(e.minVertexDistance=n),r!==1/0&&(e.lifetime=r),e}function _o(t){return t?.followLocalOrigin?{followLocalOrigin:!0}:{}}function Vo(t){const e=t?.sideAxis;return e?{sideAxis:[e.x,e.y,e.z]}:{}}function Ao(t){if(null==t)return{};let e,i,s;Array.isArray(t)?[e,i,s]=t:"object"==typeof t&&({x:e,y:i,z:s}=t);const n=t=>"number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):NaN,[r,o,a]=[n(e),n(i),n(s)];return Number.isFinite(r)&&Number.isFinite(o)&&Number.isFinite(a)&&r*r+o*o+a*a>0?{sideAxis:new ot(r,o,a)}:(console.warn(`[quarks] sideAxis ${JSON.stringify(t)} is not a direction and is ignored`),{})}function To(t,e){const i=void 0===e||"string"==typeof e?{geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}}:e,s=function(t,e){const i=t.rendererSettings,s=[i.instancingGeometry,i.instancingIndices,i.instancingUVs,i.instancingUVs2,i.instancingNormals];let n=xo.get(e);void 0===n&&(n=[],xo.set(e,n));const r=n.find(t=>t.arrays.every((t,e)=>t===s[e]));if(void 0!==r)return r.uuid;const o=bo(e,"quarks_geometry");return n.push({arrays:s,uuid:o}),e.geometries[o]={uuid:o,type:"QuarksGeometry",positions:Array.from(t.rendererSettings.instancingGeometry),indices:Array.from(t.rendererSettings.instancingIndices),uvs:t.rendererSettings.instancingUVs?Array.from(t.rendererSettings.instancingUVs):void 0,...t.rendererSettings.instancingUVs2?{uvs2:Array.from(t.rendererSettings.instancingUVs2)}:{},normals:t.rendererSettings.instancingNormals?Array.from(t.rendererSettings.instancingNormals):void 0},o}(t,i),n=function(t,e){let i=wo.get(e);void 0===i&&(i=new Map,wo.set(e,i));const s=i,n=(t,i=!1,n="texture")=>{if(!(t instanceof M||i&&t))return void(t&&console.warn(`[quarks] ${n} is not a url-backed Texture and is not written to the file`));let r=s.get(t);return void 0===r&&(r=bo(e,"quarks_texture"),s.set(t,r),e.textures[r]=t),r},r=n(t.rendererSettings.texture,!0),o=n(t.rendererSettings.reflectionAtlas),a=t.erosion,h=t.uvDistortion,l=t.gradientMap,c=(t,e)=>void 0!==e?{[t]:e}:{},u=bo(e,"quarks_material");return e.materials[u]={uuid:u,type:"QuarksMaterial",transparent:t.rendererSettings.materialTransparent,alphaMode:t.rendererSettings.materialBlendMode,depthTest:t.rendererSettings.materialDepthTest,depthWrite:t.rendererSettings.materialDepthWrite,alphaTest:t.rendererSettings.materialAlphaTest,texture:r,reflectionAtlas:o,reflectionLevel:t.rendererSettings.reflectionLevel,..."fixed"!==t.lighting?{lighting:t.lighting}:{},...t.rim?{rim:{...t.rim,color:[...t.rim.color]}}:{},...c("mapUV",t.mapUV?_s(t.mapUV):void 0),...l?{gradientMap:{ramp:n(l.ramp,!1,"gradientMap.ramp"),..."r"!==l.channel?{channel:l.channel}:{}}}:{},...a?{erosion:{...c("mask",n(a.mask,!1,"erosion.mask")),...c("maskUV",_s(a.maskUV)),...a.softness!==Os?{softness:a.softness}:{},...0!==a.edgeWidth?{edgeWidth:a.edgeWidth}:{},...a.edgeColor.some(t=>1!==t)?{edgeColor:[...a.edgeColor]}:{}}}:{},...h?{uvDistortion:{map:n(h.map,!1,"uvDistortion.map"),...c("mapUV",_s(h.mapUV,Cs)),...h.strength!==Fs?{strength:h.strength}:{}}}:{},sourceMaterial:t.material??void 0},u}(t,i),r=function(t){if(t.renderMode===xs.Trail){const e=t.rendererEmitterSettings;return{startLength:e.startLength.toJSON(),..._o(e),...So(e),...Mo(e),...zo(e),...Vo(e)}}if(t.renderMode===xs.StretchedBillBoard)return{speedFactor:t.rendererEmitterSettings.speedFactor,lengthFactor:t.rendererEmitterSettings.lengthFactor};return{}}(t);return{version:"3.0",shape:t.emitterShape.toJSON(),...yo(t),instancingGeometry:s,...Object.keys(r).length>0?{rendererEmitterSettings:r}:{},material:n,behaviors:t.behaviors.map(t=>t.toJSON())}}function Oo(t,e,i){const s=t.shape?ts(t.shape,e):void 0;let n;if(t.renderMode===xs.Trail){const e=t.rendererEmitterSettings;n={startLength:void 0!==e?.startLength?Xt(e.startLength):new Qt(30),followLocalOrigin:Boolean(e?.followLocalOrigin),...So(e),...Mo(e),...zo(e),...Ao(e?.sideAxis)}}else t.renderMode===xs.StretchedBillBoard?(n={...t.rendererEmitterSettings??{}},void 0!==t.speedFactor&&(n.speedFactor=t.speedFactor)):n={};const o=t.material?e.materials?.[t.material]:void 0,a=o?.texture??t.texture,h="string"==typeof a?e.textures?.[a]??null:a??null,l=t=>"string"==typeof t?e.textures?.[t]??null:t??null,c=o?.erosion,u=o?.gradientMap,d=o?.uvDistortion,f=function(t){if(t?.positions){const e=t.positions instanceof Float32Array?t.positions:new Float32Array(t.positions);return{positions:e,indices:Or(e,t.indices instanceof Uint16Array||t.indices instanceof Uint32Array?t.indices:t.indices?new Uint32Array(t.indices):void 0),uvs:t.uvs?t.uvs instanceof Float32Array?t.uvs:new Float32Array(t.uvs):void 0,uvs2:t.uvs2?t.uvs2 instanceof Float32Array?t.uvs2:new Float32Array(t.uvs2):void 0,normals:t.normals?t.normals instanceof Float32Array?t.normals:new Float32Array(t.normals):void 0}}const e=t?.data??t;if(e?.attributes?.position?.array){const t=new Float32Array(e.attributes.position.array);let i;return e.index?.array&&(i=new("Uint16Array"===e.index.type?Uint16Array:Uint32Array)(e.index.array)),{positions:t,indices:Or(t,i),uvs:e.attributes.uv?.array?new Float32Array(e.attributes.uv.array):void 0,uvs2:(e.attributes.uv1??e.attributes.uv2)?.array?new Float32Array((e.attributes.uv1??e.attributes.uv2).array):void 0,normals:e.attributes.normal?.array?new Float32Array(e.attributes.normal.array):void 0}}return{positions:kr,indices:Lr,uvs:Rr}}("string"==typeof t.instancingGeometry?e.geometries?.[t.instancingGeometry]:t.instancingGeometry),m=function(t){const e={},i=t;for(const t of mo){const s=i[po(t)];if(null==s)continue;const n=t.fromJSON(s);void 0!==n&&(e[t.param]=n)}return e}(t);return{...m,scene:i,shape:s,instancingGeometry:f.positions,instancingIndices:f.indices,instancingUVs:f.uvs,instancingUVs2:f.uvs2,instancingNormals:f.normals,rendererEmitterSettings:n,texture:h,material:o?.sourceMaterial??o,blendMode:o?.alphaMode??m.blendMode??r.ALPHA_ADD,transparent:o?.transparent??m.transparent??!0,depthTest:o?.depthTest??m.depthTest??!0,depthWrite:o?.depthWrite??m.depthWrite??!1,alphaTest:o?.alphaTest??m.alphaTest??0,behaviors:[],lighting:o?.lighting,rim:o?.rim,mapUV:o?.mapUV,gradientMap:u&&"object"==typeof u?{...u,ramp:l(u.ramp)}:void 0,erosion:c&&"object"==typeof c?{...c,mask:l(c.mask)}:void 0,uvDistortion:d&&"object"==typeof d?{...d,map:l(d.map)}:void 0}}const $o=new ot,Po=new rt,Co=new ot,Fo=new ot,Io=new rt,Uo=new ot,Bo=new ot,Eo=new rt,No=new ot;class Do{get prewarmTime(){return this.prewarmTimeValue}set prewarmTime(t){this.prewarmTimeValue=t>0?t:0}get duration(){return this.durationValue}set duration(t){this.durationValue=t>Gr?t:Gr}set time(t){const e=this.duration;let i=Number.isFinite(t)&&t>0?t:0;i>=e&&(i=this.looping?i%e:e);const s=this.emissionState;s.time=i,s.isBursting=!1,s.burstIndex=0,s.burstWaveIndex=0,s.burstWaves=void 0,this.markBurstsBefore(i)}get time(){return this.emissionState.time}get isEmitEnded(){return this.emitEnded}hasPendingEmission(){return this.emission.hasPendingEmission()}isFinished(){return!(this.particleNum>0)&&(!!this.onlyUsedByOther||(this.looping?this.emitEnded:!this.hasPendingEmission()))}get layers(){return this.layerMaskProxy}get texture(){return this.rendererSettings.texture}set texture(t){this.rendererSettings.texture=t,this.neededToUpdateRender=!0}get material(){return this.materialRef}set material(t){this.materialRef=t,this.applyMaterialSettings(t)}get uTileCount(){return this.rendererSettings.uTileCount}set uTileCount(t){this.rendererSettings.uTileCount=ds(t),this.neededToUpdateRender=!0}get vTileCount(){return this.rendererSettings.vTileCount}set vTileCount(t){this.rendererSettings.vTileCount=ds(t),this.neededToUpdateRender=!0}get blendTiles(){return this.rendererSettings.blendTiles}set blendTiles(t){this.rendererSettings.blendTiles=t,this.neededToUpdateRender=!0}get softParticles(){return this.rendererSettings.softParticles}set softParticles(t){this.rendererSettings.softParticles=t,this.neededToUpdateRender=!0}get sortMode(){return this.rendererSettings.sortMode??"none"}set sortMode(t){this.rendererSettings.sortMode=hs(t),this.neededToUpdateRender=!0}get minParticleSize(){return this.rendererSettings.minParticleSize??0}set minParticleSize(t){this.rendererSettings.minParticleSize=Math.max(0,t),this.neededToUpdateRender=!0}get maxParticleSize(){return this.rendererSettings.maxParticleSize??1/0}set maxParticleSize(t){this.rendererSettings.maxParticleSize=t>0?t:1/0,this.neededToUpdateRender=!0}get pivot(){return this.rendererSettings.pivot}set pivot(t){this.rendererSettings.pivot=cs(t),this.neededToUpdateRender=!0}get lighting(){return this.rendererSettings.lighting??"fixed"}set lighting(t){this.rendererSettings.lighting=as(t),this.neededToUpdateRender=!0}get rim(){return this.rendererSettings.rim}set rim(t){this.rendererSettings.rim=bs(t),this.neededToUpdateRender=!0}get mapUV(){return this.rendererSettings.mapUV}set mapUV(t){this.rendererSettings.mapUV=Bs(t),this.neededToUpdateRender=!0}get gradientMap(){return this.rendererSettings.gradientMap}set gradientMap(t){this.rendererSettings.gradientMap=As(t),this.neededToUpdateRender=!0}get erosion(){return this.rendererSettings.erosion}set erosion(t){this.rendererSettings.erosion=$s(t),this.neededToUpdateRender=!0}get uvDistortion(){return this.rendererSettings.uvDistortion}set uvDistortion(t){this.rendererSettings.uvDistortion=Is(t),this.neededToUpdateRender=!0}measureMotionScale(t){if("hierarchy"!==this.scalingMode||!this.worldSpace)return this.hierarchyScale.set(1,1,1),1;const e=t.elements,i=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),s=Math.sqrt(e[4]*e[4]+e[5]*e[5]+e[6]*e[6]),n=Math.sqrt(e[8]*e[8]+e[9]*e[9]+e[10]*e[10]);return this.hierarchyScale.set(i,s,n),(i+s+n)/3}get softNearFade(){return this.rendererSettings.softNearFade}set softNearFade(t){this.rendererSettings.softNearFade=fs(t,0),this.neededToUpdateRender=!0}get softFarFade(){return this.rendererSettings.softFarFade}set softFarFade(t){this.rendererSettings.softFarFade=fs(t,1),this.neededToUpdateRender=!0}get instancingGeometry(){return this.rendererSettings.instancingGeometry}set instancingGeometry(t){this.restartKeepingPause();const e=this.rendererSettings,i=t.length/3*2,s=e.instancingGeometry;var n,r;e.instancingGeometry=t,t.length===s.length&&function(t,e){for(let i=0;i<t.length;i++)if(t[i]>=e)return!1;return!0}(e.instancingIndices,t.length/3)||(e.instancingIndices=Or(t)),e.instancingUVs?.length===i&&(n=e.instancingUVs,r=s,void 0===n||n!==qr.get(r))||(e.instancingUVs=Wr(t)),e.instancingNormals&&(e.instancingNormals.length!==t.length||function(t,e){return void 0!==t&&t===Jr.get(e)}(e.instancingNormals,s))&&(e.instancingNormals=Qr(t)),e.instancingUVs2&&e.instancingUVs2.length!==i&&(e.instancingUVs2=void 0),this.ensureMeshNormals(),this.neededToUpdateRender=!0}ensureMeshNormals(){const t=this.rendererSettings;t.renderMode!==xs.Mesh||t.instancingNormals||(t.instancingNormals=Qr(t.instancingGeometry))}restartKeepingPause(){const t=this.paused;this.restart(),this.particles.length=0,this.paused=t}get instancingIndices(){return this.rendererSettings.instancingIndices}set instancingIndices(t){this.rendererSettings.instancingIndices=t,this.neededToUpdateRender=!0}get instancingUVs(){return this.rendererSettings.instancingUVs??Wr(this.rendererSettings.instancingGeometry)}set instancingUVs(t){this.rendererSettings.instancingUVs=t,this.neededToUpdateRender=!0}get instancingUVs2(){return this.rendererSettings.instancingUVs2}set instancingUVs2(t){this.rendererSettings.instancingUVs2=t,this.neededToUpdateRender=!0}get blending(){return this.rendererSettings.materialBlendMode}set blending(t){this.rendererSettings.materialBlendMode=t,this.neededToUpdateRender=!0}get transparent(){return this.rendererSettings.materialTransparent}set transparent(t){this.rendererSettings.materialTransparent=t,this.neededToUpdateRender=!0}get depthTest(){return this.rendererSettings.materialDepthTest}set depthTest(t){this.rendererSettings.materialDepthTest=t,this.neededToUpdateRender=!0}get depthWrite(){return this.rendererSettings.materialDepthWrite}set depthWrite(t){this.rendererSettings.materialDepthWrite=t,this.neededToUpdateRender=!0}get alphaTest(){return this.rendererSettings.materialAlphaTest}set alphaTest(t){this.rendererSettings.materialAlphaTest=us(t),this.neededToUpdateRender=!0}get renderMode(){return this.rendererSettings.renderMode}set renderMode(t){if(this.rendererSettings.renderMode!==t){let e=!1;switch(this.rendererSettings.renderMode===xs.Trail&&(e=!0),this.rendererSettings.renderMode===xs.Mesh&&(this.startRotation=new Qt(0)),t){case xs.Trail:this.rendererEmitterSettings={startLength:new Qt(30),followLocalOrigin:!1},e=!0;break;case xs.Mesh:this.rendererEmitterSettings={},this.startRotation=new Zt(new ot(0,1,0),new Qt(0));break;case xs.StretchedBillBoard:this.rendererEmitterSettings={speedFactor:0,lengthFactor:2};break;case xs.BillBoard:case xs.VerticalBillBoard:case xs.HorizontalBillBoard:case xs.Beam:this.rendererEmitterSettings={}}this.rendererSettings.renderMode=t,e&&this.restartKeepingPause(),this.ensureMeshNormals(),this.neededToUpdateRender=!0}}get renderOrder(){return this.rendererSettings.renderOrder}set renderOrder(t){this.rendererSettings.renderOrder=t,this.neededToUpdateRender=!0}get renderingGroupId(){return this.rendererSettings.renderingGroupId}set renderingGroupId(t){this.rendererSettings.renderingGroupId=t,this.neededToUpdateRender=!0}get applyFog(){return this.rendererSettings.applyFog}set applyFog(t){this.rendererSettings.applyFog=t,this.neededToUpdateRender=!0}get playbackSpeed(){return this.playbackSpeedValue}set playbackSpeed(t){this.playbackSpeedValue=t>0&&t<1/0?t:0}get emissionMultiplier(){return this.emissionMultiplierValue}set emissionMultiplier(t){this.emissionMultiplierValue=Number.isFinite(t)&&t>=0?t:0}get seed(){return this.seedValue}set seed(t){this.seedValue=t,this.rng=void 0===t?void 0:$(t),void 0!==this.emissionState&&0===this.emissionState.time&&0===this.particleNum&&(this.emission.memory.length=0,this.initSystemGenerators())}constructor(t){var e,i;if(this.prewarmTimeValue=0,this.durationValue=1,this.store=new _e(64),this.emitterVelocity=new ot,this.finishedEventFired=!1,this.clock=new jr,this.tempEmitterPos=new ot,this.stepMatrix=new ut,this.spawner=new so(this),this.emission=new Nr(this,this.spawner),this.events=new Dr,this.materialRef=null,this.qualityFactor=1,this.destroyed=!1,this.behaviorPlan=new Fr,this.hierarchyScale=new ot(1,1,1),this.playbackSpeedValue=1,this.emissionMultiplierValue=1,this.cullingMode="always",this.scalingMode="shape",this.motionScale=1,this.alignToDirection=!1,this.culled=!1,this.bounds=new Ur,this.firstTimeUpdate=!0,this.beamEndScratch=new ot,this.rebindParticles=()=>this.spawner.rebind(),this.fireParticleDied=t=>{this.events.fire({type:"particleDied",particleSystem:this,particle:t})},this.sceneRef=t.scene,this.layerMaskProxy={mask:t.layerMask??268435455},Object.defineProperty(this.layerMaskProxy,"mask",{enumerable:!0,get:()=>this.rendererSettings.layerMask,set:t=>{this.rendererSettings.layerMask=t,this.neededToUpdateRender=!0}}),this.autoDestroy=t.autoDestroy??!1,this.duration=t.duration??1,this.startDelay=t.startDelay??new Qt(0),this.looping=t.looping??!0,this.prewarm=t.prewarm??!1,this.prewarmTime=t.prewarmTime??0,this.startLife=t.startLife??new Qt(5),this.startSpeed=t.startSpeed??new Qt(0),this.startRotation=t.startRotation??new Qt(0),this.startSize=t.startSize??new Qt(1),this.startColor=t.startColor??new oe(new Pt(1,1,1,1)),this.emissionOverTime=t.emissionOverTime??new Qt(10),this.emissionOverDistance=t.emissionOverDistance??new Qt(0),this.emissionBursts=ps(t.emissionBursts),this.maxParticles="number"==typeof(e=t.maxParticles)&&e>=0&&e<1/0?Math.floor(e):void 0,this.onlyUsedByOther=t.onlyUsedByOther??!1,this.emitterShape=t.shape??new Xi,this.behaviors=t.behaviors??[],this.worldSpace=t.worldSpace??!1,this.rendererEmitterSettings=t.rendererEmitterSettings??{},t.renderMode===xs.Trail){const t={...this.rendererEmitterSettings};this.rendererEmitterSettings=t,t.startLength=t.startLength??new Qt(30),t.followLocalOrigin=t.followLocalOrigin??!1}if(t.renderMode===xs.StretchedBillBoard){const e={...this.rendererEmitterSettings};this.rendererEmitterSettings=e,void 0!==t.speedFactor&&(e.speedFactor=t.speedFactor),e.speedFactor=e.speedFactor??0,e.lengthFactor=e.lengthFactor??0}this.rendererSettings={instancingGeometry:t.instancingGeometry??kr,instancingIndices:t.instancingIndices??Lr,instancingUVs:t.instancingUVs??(t.instancingGeometry?Wr(t.instancingGeometry):Rr),instancingUVs2:t.instancingUVs2,instancingNormals:t.instancingNormals,renderMode:t.renderMode??xs.BillBoard,renderOrder:t.renderOrder??0,uTileCount:ds(t.uTileCount),vTileCount:ds(t.vTileCount),blendTiles:t.blendTiles??!1,softParticles:t.softParticles??!1,softNearFade:fs(t.softNearFade,0),softFarFade:fs(t.softFarFade,1),materialBlendMode:t.blendMode??r.ALPHA_ADD,materialTransparent:t.transparent??!0,materialDepthTest:t.depthTest??!0,materialDepthWrite:t.depthWrite??!1,materialAlphaTest:us(t.alphaTest),texture:t.texture??null,reflectionTexture:null,reflectionLevel:1,reflectionAtlas:null,layerMask:t.layerMask??268435455,pivot:cs(t.pivot),sortMode:hs(t.sortMode),minParticleSize:Math.max(0,t.minParticleSize??0),maxParticleSize:t.maxParticleSize??1/0,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,lighting:as(t.lighting),rim:bs(t.rim),mapUV:Bs(t.mapUV),gradientMap:As(t.gradientMap),erosion:$s(t.erosion),uvDistortion:Is(t.uvDistortion)},this.flip=(i=t.flip)&&(i.x>0||i.y>0)?i.clone():void 0,this.playbackSpeed=t.playbackSpeed??1,this.cullingMode=ls(t.cullingMode),this.scalingMode="hierarchy"===t.scalingMode?"hierarchy":"shape",this.alignToDirection=!0===t.alignToDirection,this.seed=t.seed,this.ensureMeshNormals(),this.materialRef=t.material??null,this.applyMaterialSettings(this.materialRef,{blendMode:t.blendMode,transparent:t.transparent,depthTest:t.depthTest,depthWrite:t.depthWrite,alphaTest:t.alphaTest,texture:t.texture,layerMask:t.layerMask}),this.neededToUpdateRender=!0,this.particles=[],this.startTileIndex=t.startTileIndex||new Qt(0),this.emitter=new dr(this,t.scene),this.paused=!1,this.particleNum=0,this.emissionState={isBursting:!1,burstParticleIndex:0,burstParticleCount:0,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,travelDistance:0},this.initSystemGenerators(),this.emitEnded=!1,this.prewarmed=!1}watchEnvAtlas(t,e){t?.onDisposeObservable.addOnce(()=>{if(this.destroyed||this.rendererSettings.reflectionAtlas!==t)return;this.rendererSettings.reflectionAtlas=null,e?.reflectionAtlas===t&&(e.reflectionAtlas=null),this.neededToUpdateRender=!0;const i=this.rendererSettings.reflectionTexture;i?.isCube&&i.getScene()&&this.sceneRef&&Tr(i,this.sceneRef,t=>{this.destroyed||this.rendererSettings.reflectionTexture!==i||(this.rendererSettings.reflectionAtlas=t,e&&null==e.reflectionAtlas&&(e.reflectionAtlas=t),this.watchEnvAtlas(t,e),this.neededToUpdateRender=!0)})})}applyMaterialSettings(t,e={}){if(!this.rendererSettings)return;const i=function(t,e,i){const s=void 0!==e.texture?e.texture:t?.albedoTexture??t?.diffuseTexture??t?.emissiveTexture??t?.opacityTexture??t?.baseTexture??i.texture??null,n=t?.reflectionTexture??t?.environmentTexture??i.reflectionTexture??null,r="number"==typeof n?.level?n.level:1,o=e.blendMode??("number"==typeof t?.alphaMode?t.alphaMode:i.materialBlendMode),a=e.transparent??("function"==typeof t?.needAlphaBlending?t.needAlphaBlending():"number"==typeof t?.alpha?t.alpha<1:i.materialTransparent),h=e.depthTest??("boolean"==typeof t?.disableDepthTest?!t.disableDepthTest:i.materialDepthTest),l=e.depthWrite??("boolean"==typeof t?.disableDepthWrite?!t.disableDepthWrite:"boolean"==typeof t?.forceDepthWrite?t.forceDepthWrite:i.materialDepthWrite),c=e.alphaTest??(()=>{const e=t?.transparencyMode,s=1===e||3===e;return s&&"number"==typeof t?.alphaCutOff?t.alphaCutOff:s&&"number"==typeof t?.alphaCutOffValue?t.alphaCutOffValue:t?0:i.materialAlphaTest})();return{texture:s,reflectionTexture:n,reflectionLevel:"number"==typeof t?.reflectionLevel?t.reflectionLevel:r,reflectionAtlas:Xr(t?.reflectionAtlas)??Xr(e.reflectionAtlas)??Xr(i.reflectionAtlas),blendMode:o,transparent:a,depthTest:h,depthWrite:l,alphaTest:c}}(t,e,this.rendererSettings);this.rendererSettings.texture=i.texture,this.rendererSettings.reflectionTexture=i.reflectionTexture,this.rendererSettings.reflectionLevel=i.reflectionLevel;let s=i.reflectionAtlas;const n=i.reflectionTexture;!s&&n?.isCube&&(s=Sr(n,this.sceneRef),!s&&this.sceneRef&&(Tr(n,this.sceneRef,e=>{this.rendererSettings.reflectionAtlas!==e&&(this.rendererSettings.reflectionAtlas=e,t&&!Xr(t.reflectionAtlas)&&(t.reflectionAtlas=e),this.watchEnvAtlas(e,t),this.neededToUpdateRender=!0)}),s=Sr(n,this.sceneRef))),this.rendererSettings.reflectionAtlas=s,this.watchEnvAtlas(s,t),this.rendererSettings.materialBlendMode=i.blendMode,this.rendererSettings.materialTransparent=i.transparent,this.rendererSettings.materialDepthTest=i.depthTest,this.rendererSettings.materialDepthWrite=i.depthWrite,this.rendererSettings.materialAlphaTest=us(i.alphaTest),void 0!==e.layerMask&&(this.rendererSettings.layerMask=e.layerMask),this.neededToUpdateRender=!0}pause(){this.paused=!0}play(){this.paused=!1,this.previousEmitterMatrix=void 0}stop(){this.restart(),this.pause()}clear(){this.particleNum=0,this.bounds.valid=!1;for(const t of this.behaviors)t instanceof Le&&t.clearEmissions()}clearTrails(){if(this.rendererSettings.renderMode===xs.Trail)for(let t=0;t<this.particleNum;t++)this.particles[t].resetHistory()}setQualityFactor(t){this.qualityFactor=Math.max(.1,Math.min(1,t))}emissionFactor(){return this.qualityFactor*this.emissionMultiplierValue}endEmit(){this.emitEnded=!0,this.events.fire({type:"emitEnd",particleSystem:this})}get isDisposed(){return this.destroyed}dispose(){this.destroyed||(this.destroyed=!0,this.particleNum=0,this._renderer&&this._renderer.deleteSystem(this),function(t){ur++;try{t.dispose()}finally{ur--}}(this.emitter),this.events.fire({type:"destroy",particleSystem:this}))}initSystemGenerators(){const t=this.rng,e=void 0===t?void 0:O(t);try{this.clock.setStartDelay(this.emission.rollGenerators())}finally{void 0!==t&&O(e??null)}}restart(){this.destroyed||(this.emission.memory.length=0,this.paused=!1,this.particleNum=0,this.bounds.valid=!1,this.clock.reset(),void 0!==this.seedValue&&(this.rng=$(this.seedValue)),this.emissionState.isBursting=!1,this.emissionState.burstIndex=0,this.emissionState.burstWaveIndex=0,this.emissionState.burstWaves=void 0,this.emissionState.time=0,this.emissionState.waitEmiting=0,this.emissionState.travelDistance=0,this.emissionState.previousWorldPos=void 0,this.emissionState.burstParticleIndex=0,this.emissionState.burstParticleCount=0,this.emissionBursts.forEach(t=>Object.assign(t,ms(t))),this.emissionBursts.sort((t,e)=>t.time-e.time),this.behaviors.forEach(t=>{t.reset(),t instanceof Le&&t.clearEmissions()}),this.emitterShape.reset?.(),this.emitEnded=!1,this.finishedEventFired=!1,this.prewarmed=!1,this.initSystemGenerators(),this.previousEmitterPos=void 0,this.previousEmitterMatrix=void 0,this.emitterVelocity.set(0,0,0))}update(t,e=1/0,i){if(this.paused||this.destroyed)return;const s=this.playbackSpeed;if(t=jr.frameSeconds(t,s),this.culled)return"pauseAndCatchUp"===this.cullingMode&&this.clock.deferCatchUp(t),void(this.previousEmitterMatrix=void 0);if(this.clock.owesCatchUp){if(this.catchUp(i??performance.now()+Do.catchUpBudgetMs),this.paused||this.destroyed)return;(this.previousEmitterMatrix??(this.previousEmitterMatrix=new ut)).copy(this.emitter.matrixWorld)}if(this.firstTimeUpdate&&(this.firstTimeUpdate=!1,this.emitter.computeWorldMatrix(!0)),!this.looping&&this.finishedEventFired&&0===this.particleNum)return void this.clock.accrue(t,s);if(this.looping&&this.prewarm&&!this.prewarmed&&(this.runPrewarm(),this.paused||this.destroyed))return;this.neededToUpdateRender&&(this._renderer&&this._renderer.updateSystem(this),this.neededToUpdateRender=!1);const n=this.emitter.matrixWorld.elements;if(this.tempEmitterPos.set(n[12],n[13],n[14]),void 0!==this.previousEmitterPos&&t>0&&this.emitterVelocity.copy(this.tempEmitterPos).sub(this.previousEmitterPos).divideScalar(t),(this.previousEmitterPos??(this.previousEmitterPos=new ot)).copy(this.tempEmitterPos),this.clock.delaying&&(!this.prewarm||!this.looping)&&0===(t=this.clock.consumeStartDelay(t)))return;const r=this.clock.accrue(t,s);if(0===r)return;const o=this.emitter.matrixWorld,a=this.previousEmitterMatrix,h=r>1&&void 0!==a&&!a.equals(o);h&&(a.decompose($o,Po,Co),o.decompose(Fo,Io,Uo));let l=o;for(let t=0;t<r;t++){if(h&&t+1<r){const e=(t+1)/r;Bo.copy($o).lerp(Fo,e),Eo.copy(Po).slerp(Io,e),No.copy(Co).lerp(Uo,e),l=this.stepMatrix.compose(Bo,Eo,No)}else l=o;if(this.simulateStep(Gr,l),this.paused||this.destroyed)break;if(e!==1/0&&t+1<r&&performance.now()>=e)break}this.destroyed||(this.previousEmitterMatrix??(this.previousEmitterMatrix=new ut)).copy(l)}catchUp(t){let e=this.clock.takeCatchUpSteps();for(;e-- >0&&(this.simulateStep(Gr),!this.paused&&!this.destroyed)&&!(e>0&&performance.now()>=t););}markBurstsBefore(t){const e=this.emissionState,i=this.emissionBursts,s=e.burstWaves??(e.burstWaves=[]);for(;e.burstIndex<i.length&&i[e.burstIndex].time<t;){const n=i[e.burstIndex],r=Br(n),o=Er(n);let a=0;if(o>0)for(;a<r&&n.time+a*o<t;)a++;else a=r;s[e.burstIndex]=a,e.burstIndex++}}runPrewarm(){this.prewarmed=!0;const t=this.prewarmTime>0?this.prewarmTime:this.duration,e=Math.min(this.duration,t,Math.max(0,Do.maxPrewarmSeconds)),i=Math.round(e/Gr);if(e<this.duration){const t=this.emissionState;t.time=this.duration-i*Gr,this.markBurstsBefore(t.time)}for(let t=0;t<i;t++)if(this.simulateStep(Gr),this.paused||this.destroyed)return}getWorldBounds(t,e){if(!this.bounds.toWorld(t,e,this.emitter))return!1;if(this.rendererSettings.renderMode===xs.Beam){const i=this.beamEndScratch;if(!this.getBeamEnd(i))return!0;const s=this.bounds.worldPadding(this.emitter);t.set(Math.min(t.x,i.x-s),Math.min(t.y,i.y-s),Math.min(t.z,i.z-s)),e.set(Math.max(e.x,i.x+s),Math.max(e.y,i.y+s),Math.max(e.z,i.z+s))}return!0}getBeamEnd(t){const e=this.beamEnd;if(void 0===e)return!1;const i=e;if("function"==typeof i.getAbsolutePosition){const e=i.getAbsolutePosition();t.set(e.x,e.y,e.z)}else{const i=e;t.set(i.x,i.y,i.z)}return!0}setWorldBounds(t,e,i,s,n,r,o){this.bounds.setWorld(t,e,i,s,n,r,o)}get simulationStep(){return Gr}get simulationResidual(){return this.paused?0:this.clock.residual}simulateStep(t,e=this.emitter.matrixWorld){const i=this.rng;if(void 0===i)return void this.stepOnce(t,e);const s=O(i);try{this.stepOnce(t,e)}finally{O(s)}}stepOnce(t,e){if(this.destroyed)return;this.motionScale=this.measureMotionScale(e),this.onlyUsedByOther||this.emission.emit(t,this.emissionState,e);const i=this.particles,s=this.behaviors,n=this.particleNum,r=this.store,o=this.rendererSettings.renderMode,a=o===xs.Trail,h=this.behaviorPlan.steps(s),l=this.behaviorPlan.changesSize,c=this.behaviorPlan.changesColor;!function(t,e,i,s,n,r){const o=3*e;t.useSizeSnapshot(i),t.useColorSnapshot(s),t.previousPosition.set(t.position.subarray(0,o)),i&&t.previousSize.set(t.size.subarray(0,o)),n&&(t.keepPreviousVelocity()&&r(),t.previousVelocity.set(t.velocity.subarray(0,o))),s&&t.previousColor.set(t.color.subarray(0,4*e))}(r,n,l,c,o===xs.StretchedBillBoard,this.rebindParticles),this.emitterShape.update(this,t),function(t,e,i,s,n,r){for(let o=0;o<t.length;o++){const a=t[o],h=a.behaviors;for(let t=0;t<h.length;t++)h[t].frameUpdate(n);if(0===s)continue;if(void 0!==a.run){a.run(e,i,s,n,r);continue}const l=h[0];if(void 0===l.updateAll)for(let t=0;t<s;t++){const e=i[t];e.age<e.life&&l.update(e,n)}else l.updateAll(i,s,n)}}(h,s,i,n,t,r);const u=this.events.has("particleDied")?this.fireParticleDied:void 0;let d=this.particleNum;if(a){const s=this.rendererEmitterSettings;!function(t,e,i,s){const n=t.scalars,r=_e.SCALAR_STRIDE,o=t.previousSize,a=t.size,h=t.previousColor,l=t.color;for(let t=0,c=0,u=0,d=0;t<e;t++,c+=3,u+=4,d+=r)0===n[d+_e.AGE]&&(i&&(o[c]=a[c],o[c+1]=a[c+1],o[c+2]=a[c+2]),s&&(h[u]=l[u],h[u+1]=l[u+1],h[u+2]=l[u+2],h[u+3]=l[u+3]))}(r,n,l,c),function(t,e,i,s,n,r){if(n){for(let i=0;i<s;i++){const s=e[i];s.localPosition?(s.position.copy(s.localPosition),s.position.applyMatrix4(s.parentMatrix??r)):s.position.addScaledVector(s.velocity,t*s.speedModifier),s.age+=t}return}const o=i.scalars,a=_e.SCALAR_STRIDE,h=i.position,l=i.velocity;for(let e=0,i=0,n=0;e<s;e++,i+=3,n+=a){const e=t*o[n+_e.SPEED_MODIFIER];h[i]+=l[i]*e,h[i+1]+=l[i+1]*e,h[i+2]+=l[i+2]*e,o[n+_e.AGE]+=t}}(t,i,r,n,Boolean(s.followLocalOrigin),e),function(t,e,i,s,n){const r=i.dieWithParticle,o=i.recordWorldSpace&&!s,a=i.sideAxis,h=s||Boolean(i.recordWorldSpace),l=tr(i),c=er(i);for(let i=0;i<e;i++){const e=t[i],s=e.age<e.life;if(r&&!s){e.resetHistory();continue}let u=!1;if(l>0&&s&&e.historyCount>1){const t=e.historyDistances,i=e.historyCount;u=t[e.getHistoryIndex(i-1)]-t[e.getHistoryIndex(i-2)]<l}if(e.update(u,!o),o&&s){const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,i=e.historyPositions;Yr.set(i[t],i[t+1],i[t+2]),Yr.applyMatrix4(e.parentMatrix??n),i[t]=Yr.x,i[t+1]=Yr.y,i[t+2]=Yr.z,e.measureHeadDistance()}if(c!==1/0){const t=e.historyAges,i=e.age;for(;e.historyCount>0&&i-t[e.getHistoryIndex(0)]>c;)e.dropOldest()}if(a&&s){e.ensureSideHistory();const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,i=e.historySides;let s=a.x,r=a.y,o=a.z;if(h){const t=(e.parentMatrix??n).elements,i=t[0]*s+t[4]*r+t[8]*o,a=t[1]*s+t[5]*r+t[9]*o;o=t[2]*s+t[6]*r+t[10]*o,s=i,r=a}i[t]=s,i[t+1]=r,i[t+2]=o}}}(i,n,s,this.worldSpace,e),d=function(t,e,i,s){const n=e.scalars,r=_e.SCALAR_STRIDE;for(let o=0;o<i;o++){const a=t[o],h=o*r;n[h+_e.AGE]>=n[h+_e.LIFE]&&0===a.historyCount&&(Hr(t,e,o,i-1),i--,o--,void 0!==s&&s(a))}return i}(i,r,d,u)}else d=function(t,e,i,s,n,r,o,a,h){const l=i.scalars,c=_e.SCALAR_STRIDE,u=i.position,d=i.velocity,f=i.previousSize,m=i.size,p=i.previousColor,y=i.color,g=o.due,v=o.min,x=o.max;let w=g?1/0:v.x,b=g?1/0:v.y,S=g?1/0:v.z,M=g?-1/0:x.x,z=g?-1/0:x.y,_=g?-1/0:x.z,V=g?0:o.maxSize,A=g?0:o.maxSpeedSq;for(let o=0;o<s;o++){const a=o*c;let v=l[a+_e.AGE];const x=3*o,T=g||0===v;if(0===v&&(n&&(f[x]=m[x],f[x+1]=m[x+1],f[x+2]=m[x+2]),r)){const t=4*o;p[t]=y[t],p[t+1]=y[t+1],p[t+2]=y[t+2],p[t+3]=y[t+3]}const O=t*l[a+_e.SPEED_MODIFIER],$=d[x],P=d[x+1],C=d[x+2],F=u[x]+$*O,I=u[x+1]+P*O,U=u[x+2]+C*O;if(u[x]=F,u[x+1]=I,u[x+2]=U,T&&(w=Math.min(w,F),M=Math.max(M,F),b=Math.min(b,I),z=Math.max(z,I),S=Math.min(S,U),_=Math.max(_,U),V=Math.max(V,Math.max(m[x],Math.max(m[x+1],m[x+2])))),A=Math.max(A,$*$+P*P+C*C),v+=t,l[a+_e.AGE]=v,v>=l[a+_e.LIFE]){const t=Hr(e,i,o,s-1);s--,o--,void 0!==h&&h(t)}}return o.store(s,g,w,b,S,M,z,_,V,A,a.rendererSettings,a.rendererEmitterSettings,a.worldSpace,Gr),s}(t,i,r,d,l,c,this.bounds,this,u);this.particleNum=this.destroyed?0:d,this.notifyFinished()}notifyFinished(){this.isFinished()&&(this.finishedEventFired||(this.finishedEventFired=!0,this.events.fire({type:"finished",particleSystem:this})),this.autoDestroy&&this.dispose())}emit(t,e,i){this.emission.emit(t,e,i)}toJSON(t,e={}){return To(this,t)}static fromJSON(t,e,i={},s){const n=new Do(Oo(t,e,s));return n.behaviors=(t.behaviors??[]).map(t=>{const e=zi(t,n);return e&&"EmitSubParticleSystem"===e.type&&(i[t.subParticleSystem]=e),e}).filter(t=>null!==t),n}addBehavior(t){this.behaviors.push(t),this._renderer?._invalidateUpdateOrder()}getRendererSettings(){return this.rendererSettings}addEventListener(t,e){this.events.add(t,e)}removeAllEventListeners(t){this.events.removeAll(t)}removeEventListener(t,e){this.events.remove(t,e)}clone(){const t=this.behaviors.map(t=>t.clone());let e;if(this.renderMode===xs.Trail){const t=this.rendererEmitterSettings;e={startLength:t.startLength.clone(),followLocalOrigin:Boolean(t.followLocalOrigin),...So(t),...Mo(t),...zo(t),...t.sideAxis?{sideAxis:t.sideAxis.clone()}:{}}}else e=this.renderMode===xs.StretchedBillBoard?{lengthFactor:this.rendererEmitterSettings.lengthFactor,speedFactor:this.rendererEmitterSettings.speedFactor}:{};const i=new Do({...go(this),shape:this.emitterShape.clone(),instancingGeometry:this.rendererSettings.instancingGeometry,instancingIndices:this.rendererSettings.instancingIndices,instancingUVs:this.rendererSettings.instancingUVs,instancingUVs2:this.rendererSettings.instancingUVs2,instancingNormals:this.rendererSettings.instancingNormals,rendererEmitterSettings:e,material:this.materialRef,texture:this.rendererSettings.texture,behaviors:t,lighting:this.lighting,rim:this.rim,mapUV:this.mapUV,gradientMap:this.gradientMap,erosion:this.erosion,uvDistortion:this.uvDistortion,scene:this.emitter.getScene()});for(const e of t)e instanceof Le&&(e.particleSystem=i);this.tint&&(i.tint=this.tint.clone()),i.emissionMultiplier=this.emissionMultiplier;const s=this.beamEnd;return s&&(i.beamEnd="function"==typeof s.getAbsolutePosition?s:{x:s.x,y:s.y,z:s.z}),i}}Do.catchUpBudgetMs=2,Do.maxPrewarmSeconds=10;class ko extends n{constructor(t="QuarksPrefab",e){super(t,e),this.type="QuarksPrefab",this.animationData=[],this.isPlaying=!1,this.currentTime=-1e-5,this.timeScale=1,this.duration=0,this._lastUpdateTimeMs=Date.now(),this._tempAnimationJSON=[]}registerBatchedRenderer(t){this._batchedRenderer=t}addParticleSystemAnimation(t,e=0,i=0,s=!1){const n={startTime:e,duration:i>0?i:t.system.duration,type:"ps",loop:s,target:t};return this.animationData.push(n),this.pause(),this.updateDuration(),n}addThreeAnimation(t,e,i=0,s=e?.duration??0,n=!1,r){const o={startTime:i,duration:s>0?s:e?.duration??0,type:"three",loop:n,target:t,clip:e,clipUUID:r??e?.uuid};return this.animationData.push(o),this.updateDuration(),o}removeAnimation(t){this.animationData.splice(t,1),this.updateDuration()}play(){this.isPlaying||(this.isPlaying=!0,this._lastUpdateTimeMs=Date.now(),this.animationData.forEach(t=>{this.currentTime>=t.startTime&&this.currentTime<=t.startTime+t.duration&&("ps"===t.type&&t.target instanceof dr?t.target.system.play():t.clip?.play?.())}))}pause(){this.isPlaying&&(this.isPlaying=!1,this.animationData.forEach(t=>{"ps"===t.type&&t.target instanceof dr?t.target.system.pause():t.clip?.pause?.()}))}stop(){this.pause(),this.currentTime=-1e-5,this.animationData.forEach(t=>{"ps"===t.type&&t.target instanceof dr?t.target.system.stop():t.clip?.stop?.()})}update(t){if(!this.isPlaying)return;const e=Date.now(),i=t??Math.max((e-this._lastUpdateTimeMs)/1e3,0);this._lastUpdateTimeMs=e;const s=this.currentTime;this.currentTime+=i*this.timeScale,this.currentTime>this.duration?this.stop():this.animationData.forEach(t=>{const e=t.startTime,i=t.startTime+t.duration,n=this.currentTime>=e&&this.currentTime<=i,r=s>=e&&s<=i;if(!n||r){if(!n&&r){if(t.loop&&"ps"===t.type&&t.target instanceof dr)return void t.target.system.restart();"ps"===t.type&&t.target instanceof dr?t.target.system.endEmit():t.loop?t.clip?.play?.():t.clip?.stop?.()}}else"ps"===t.type&&t.target instanceof dr?(t.target.system.restart(),this._batchedRenderer&&this._batchedRenderer.addSystem(t.target.system)):t.clip?.play?.()})}setTime(t){const e=this.currentTime;this.currentTime=t,this.animationData.forEach(i=>{const s=i.startTime,n=i.startTime+i.duration,r=this.currentTime>=s&&this.currentTime<n,o=e>=s&&e<n;!r||o?r||!o?r&&"three"===i.type&&i.clip?.setTime?.(Math.max(t-s,0)):"ps"===i.type&&i.target instanceof dr?i.target.system.endEmit():i.clip?.stop?.():"ps"===i.type&&i.target instanceof dr?i.target.system.restart():i.clip?.play?.()})}getDuration(){return this.duration}resolveReferences(t){const e={},i=t=>{var s;const r=t._quarksUUID;r?e[r]=t:e[s=t.uniqueId.toString()]??(e[s]=t);const o=t.getChildren();for(const t of o)t instanceof n&&i(t)};i(t),this._tempAnimationJSON.forEach(t=>{const i=e[t.targetUUID];if("ps"===t.type&&i instanceof dr)this.addParticleSystemAnimation(i,t.startTime,t.duration,t.loop);else if("three"===t.type&&i){const e=this.resolveTimelineClip(i,t.clipUUID);this.addThreeAnimation(i,e,t.startTime,t.duration,t.loop,t.clipUUID)}}),this.updateDuration(),this._tempAnimationJSON=[]}toJSON(){return{type:this.type,name:this.name,...1!==this.timeScale?{timeScale:this.timeScale}:{},animationData:this.animationData.map(t=>({startTime:t.startTime,duration:t.duration,type:t.type,targetUUID:ns(t.target),clipUUID:"three"===t.type?t.clipUUID??t.clip?.uuid:void 0,loop:t.loop}))}}static fromJSON(t,e){const i=new ko(t.name||"QuarksPrefab",e);return"number"==typeof t.timeScale&&(i.timeScale=t.timeScale),Array.isArray(t.animationData)&&(i._tempAnimationJSON=t.animationData.filter(t=>"ps"===t?.type||"three"===t?.type)),i}resolveTimelineClip(t,e){const i=[t.animations,t.animationGroups,t.metadata?.animations,t.metadata?.animationGroups];for(const t of i){if(!Array.isArray(t))continue;if(!e)return t[0];const i=t.find(t=>t?.uuid===e);if(i)return i}}updateDuration(){let t=0;this.animationData.forEach(e=>{const i=e.startTime+e.duration;i>t&&(t=i)}),this.duration=t}}const Ro=new WeakMap;function Lo(t,e,i){Ro.set(t,{source:e,loaded:i})}function qo(t){const e=Ro.get(t);return void 0!==e&&t.url===e.loaded?e.source:void 0}const Jo=1,Wo={[M.WRAP_ADDRESSMODE]:1e3,[M.CLAMP_ADDRESSMODE]:1001,[M.MIRROR_ADDRESSMODE]:1002};function Qo(t){return!!t&&(!/^blob:/i.test(t)&&(!/^data:/i.test(t)||t.includes(",")))}function Go(t){const e=t.rotationQuaternion??m.FromEulerVector(t.rotation);return Array.from(f.Compose(t.scaling,e,t.position).asArray())}class jo{constructor(t){this.options=t,this.meta={geometries:{},materials:{},textures:{}},this.meshGeometries=new Map,this.geometryIds=new Map,this.meshMaterials=[],this.meshMaterialIds=new Map,this.extraTextures=new Map,this.nextId=0}warnDanglingLinks(t){const e=new Set,i=[],s=t=>{e.add(t.uuid),i.push(t),t.children?.forEach(s)};s(t);for(const t of i)for(const[i,s]of Yo(t))""===s||e.has(s)||this.warn(`"${t.name}" has ${i} on node "${s}", which is not in what is written; it loads without that link.`)}warn(t){(this.options.onWarning??(t=>console.warn(`[quarks] ${t}`)))(t)}node(t){const e=t.getChildren(t=>t instanceof n,!0).filter(t=>!1!==this.options.filter?.(t)).map(t=>this.node(t)),i={uuid:ns(t),type:"Group",name:t.name,matrix:Go(t)};if(t.isEnabled(!1)||(i.visible=!1),t instanceof p&&!t.isVisible&&(i.isVisible=!1),t instanceof dr)i.type="ParticleEmitter",i.ps=t.system.toJSON(this.meta);else if(t instanceof ko){const{type:e,name:s,...n}=t.toJSON();Object.assign(i,n),i.type="QuarksPrefab"}else t instanceof p?(i.type="Mesh",i.geometry=this.meshGeometry(t),i.material=this.meshMaterial(t)):t instanceof _&&this.warn(`"${t.name}" is an instance of "${t.sourceMesh.name}"; it is written as a group.`);return e.length>0&&(i.children=e),i}id(t){return this.nextId+=1,`${t}_${this.nextId}`}meshGeometry(e){const i=e.geometry?this.geometryIds.get(e.geometry):void 0;if(void 0!==i)return i;const s=e.getVerticesData(t.PositionKind);if(!s||0===s.length)return void this.warn(`Mesh "${e.name}" has no vertices; it is written without geometry.`);const n=e.getIndices(),r=Or(s instanceof Float32Array?s:new Float32Array(s),n&&n.length>0?Uint32Array.from(n):void 0),o=t=>{const i=e.getVerticesData(t);return i?Array.from(i):void 0},a={uuid:this.id("quarks_mesh_geometry"),type:"QuarksGeometry",positions:Array.from(s),indices:Array.from(r)},h=o(t.UVKind),l=o(t.UV2Kind),c=o(t.NormalKind);return h&&(a.uvs=h),l&&(a.uvs2=l),c&&(a.normals=c),this.meshGeometries.set(a.uuid,a),e.geometry&&this.geometryIds.set(e.geometry,a.uuid),a.uuid}meshMaterial(t){const e=t.material;if(!e)return;if(!(e instanceof z))return void this.warn(`Mesh "${t.name}" has a ${e.getClassName()}; only a StandardMaterial's blend, culling and diffuse texture are written, so it loads without a material.`);let i=this.meshMaterialIds.get(e);if(void 0!==i)return i;i=this.id("quarks_mesh_material"),this.meshMaterialIds.set(e,i);const s=1===e.diffuseColor.r&&1===e.diffuseColor.g&&1===e.diffuseColor.b,n=0===e.emissiveColor.r&&0===e.emissiveColor.g&&0===e.emissiveColor.b;1===e.alpha&&s&&n||this.warn(`Mesh "${t.name}": its material's alpha and colours are not written; it loads opaque white.`);const o={uuid:i,type:"MeshBasicMaterial"};return e.alphaMode!==r.ALPHA_COMBINE&&(o.alphaMode=e.alphaMode),e.backFaceCulling&&(o.side=0),0!==e.alphaCutOff&&(o.alphaTest=e.alphaCutOff),e.disableDepthWrite||(o.depthWrite=!0),this.meshMaterials.push({json:o,map:e.diffuseTexture}),i}texture(t){for(const[e,i]of Object.entries(this.meta.textures))if(i===t)return e;let e=this.extraTextures.get(t);return void 0===e&&(e=this.id("quarks_mesh_texture"),this.extraTextures.set(t,e)),e}finish(t){const e=this.meshMaterials.map(({json:t,map:e})=>e?{...t,map:this.texture(e)}:t);this.warnDanglingLinks(t);const i=[],s=new Map,n=[],r=[...Object.entries(this.meta.textures),...[...this.extraTextures].map(([t,e])=>[e,t])];for(const[t,e]of r){if(null===e)continue;const r={uuid:t},o=e instanceof M?this.options.imageUrl?this.options.imageUrl(e):qo(e)??e.url:null;if(Qo(o)){let t=s.get(o);void 0===t&&(t=`quarks_image_${s.size+1}`,s.set(o,t),i.push({uuid:t,url:o})),r.image=t}else this.warn(`Texture "${e.name}" has no url a file can point at (made in code, a blob: url, or an image embedded in a glTF); it is written without its image and loads as no texture. Give it a file url or a data: URI before saving.`);e instanceof M&&Object.assign(r,Ho(e)),n.push(r)}const o=Object.values(this.meta.materials).map(t=>{const{sourceMaterial:e,...i}=t;return i});return{metadata:{version:4.5,type:"Object3D",generator:this.options.generator??"babylon.quarks",quarksFormat:1},geometries:[...Object.values(this.meta.geometries),...this.meshGeometries.values()],materials:[...o,...e],textures:n,images:i,object:t}}}function*Yo(t){const e=t.ps;for(const t of e?.behaviors??[])"EmitSubParticleSystem"===t.type&&"string"==typeof t.subParticleSystem&&(yield["a sub emitter",t.subParticleSystem]);"mesh_surface"===e?.shape?.type&&"string"==typeof e.shape.mesh&&(yield["a mesh surface shape",e.shape.mesh]);for(const e of t.animationData??[])"string"==typeof e.targetUUID&&(yield["a prefab animation",e.targetUUID])}function Ho(t){const e={};return t.invertY||(e.invertY=!1),t.noMipmap&&(e.noMipmap=!0),t.samplingMode!==r.TEXTURE_TRILINEAR_SAMPLINGMODE&&(e.samplingMode=t.samplingMode),t.wrapU===M.WRAP_ADDRESSMODE&&t.wrapV===M.WRAP_ADDRESSMODE||(e.wrap=[Wo[t.wrapU]??1e3,Wo[t.wrapV]??1e3]),1===t.uScale&&1===t.vScale||(e.repeat=[t.uScale,t.vScale]),0===t.uOffset&&0===t.vOffset||(e.offset=[t.uOffset,t.vOffset]),0!==t.wAng&&(e.rotation=t.wAng),e}function Xo(t,e={}){const i=new jo(e);let s;if(Array.isArray(t)){const n=e.name??"effect";s={uuid:`${n}-root`,type:"Group",name:n,matrix:f.Identity().asArray().slice(),children:t.map(t=>i.node(t))}}else s=i.node(t);return i.finish(s)}const Zo=new WeakMap,Ko=new WeakMap,ta=new WeakMap;function ea(t,e){let i=t.get(e);return void 0===i&&(i=new Map,t.set(e,i)),i}const ia=new WeakMap,sa=new WeakMap;class na extends Error{constructor(t){super(t),this.name="QuarksFormatError"}}function ra(t){if(null===t||"object"!=typeof t)return t;const e={...t};return Array.isArray(t.images)&&(e.images=t.images.map(t=>{if(!t||"object"!=typeof t)return t;const e={...t};if(ia.get(t)===e.url&&"string"==typeof e.url){ia.set(e,e.url);const i=sa.get(t);void 0!==i&&sa.set(e,i)}return e})),Array.isArray(t.geometries)&&(e.geometries=t.geometries.map(t=>t&&"object"==typeof t?{...t}:t)),e}const oa=new WeakMap,aa=t=>t.reason??new Error("[QuarksLoader] The load was aborted."),ha=()=>new Error("[QuarksLoader] The scene was disposed while the effect loaded.");function la(t,e){if(e?.aborted)throw aa(e);if(t.isDisposed)throw ha()}function ca(t,e,i){return la(e,i),new Promise((s,n)=>{const r=()=>n(aa(i));i?.addEventListener("abort",r,{once:!0});const o=e.onDisposeObservable.addOnce(()=>n(ha()));t.then(s,n).finally(()=>{i?.removeEventListener("abort",r),e.onDisposeObservable.remove(o)})})}class ua{constructor(t,e={}){this.scene=t,this.options=e}async load(t,e={}){const{json:i,baseUrl:s}=await ca(this.fetchEffectDocument(t,e.signal),this.scene,e.signal);return this.loadFromJSON(i,s,e)}async loadFromJSON(t,e,i={}){const s=i.signal;la(this.scene,s);const n=e??this.options.baseUrl??"";t=ra(t),await ca(this.resolveResources(t,n),this.scene,s);const r=this.parseDocument(t,"");return await this.finishLoad(r,s),r.root}static disposeEffect(t){cr(t)}async finishLoad(t,e){try{if(this.options.waitForTextures){for(const e of t.textures)e.delayLoadState===r.DELAYLOADSTATE_NOTLOADED&&e.delayLoad();await ca(Promise.all(t.textures.map(t=>oa.get(t))),this.scene,e)}la(this.scene,e)}catch(e){throw this.scene.isDisposed||cr(t.root),e}}async loadAll(t,e={}){la(this.scene,e.signal);const i=ua.mapPool(t,e.concurrency,async(i,s)=>{la(this.scene,e.signal);try{return await this.fetchEffectDocument(i,e.signal)}catch(n){if(!e.continueOnError||e.signal?.aborted||this.scene.isDisposed)throw n;return console.warn(`[QuarksLoader] Failed to fetch effect "${i}" (${s+1}/${t.length}):`,n),null}}),s=await ca(i,this.scene,e.signal);return this.loadDocuments(s,e)}async loadFromJSONAll(t,e={}){const i=t.map(t=>{if(null!==t&&"object"==typeof t&&"json"in t){const e=t;return{json:ra(e.json),baseUrl:e.baseUrl??this.options.baseUrl??""}}return{json:ra(t),baseUrl:this.options.baseUrl??""}});return this.loadDocuments(i,e)}async resolveResources(t,e=""){await ua.resolveLinkedResources(t,{baseUrl:e,resolver:this.options.resolver,scene:this.scene,onResourceError:this.options.onResourceError})}static async resolveLinkedResources(t,e={}){const i=e.baseUrl??"",s=e.resolver,n=e.scene;await ua.inlineGeometryEntries(t,async t=>{const e=await ua.resolveWith(s,t,"geometry",i);return ua.fetchJsonWith(s,e,n)},e.onResourceError);const r=Array.isArray(t?.images)?t.images:[];await Promise.all(r.map(async t=>{if("string"!=typeof t?.url||!t.url)return;if(ia.get(t)===t.url)return;const e=t.url;t.url=await ua.resolveWith(s,t.url,"image",i),ia.set(t,t.url),/^(data|blob):/i.test(t.url)||sa.set(t,e)}))}static async resolveExternalGeometries(t,e){await ua.inlineGeometryEntries(t,e)}parse(t,e=""){return this.parseDocument(t,e).root}parseDocument(t,e){if(null===t||"object"!=typeof t||null===t.object||"object"!=typeof t.object)throw new na('[QuarksLoader] Not an effect document: it has no "object" to load.');const i=t.metadata?.quarksFormat;"number"==typeof i&&i>1&&console.warn(`[QuarksLoader] This effect was written in format ${i}, newer than the 1 this version of babylon.quarks reads; settings it does not know are left out.`);const s={ownedMaterials:[],images:{},imageSources:{},textures:{},geometries:{},materials:{}};t.geometries&&this.parseGeometries(t.geometries,s),t.images&&this.parseImages(t.images,e,s),t.textures&&this.parseTextures(t.textures,s),t.materials&&this.parseMaterials(t.materials,s);const n=this.parseObject(t.object,s);this.linkReferences(n);const r=[...new Set(Object.values(s.textures).filter(t=>null!==t))];return hr(n,r,s.ownedMaterials),{root:n,textures:r}}parseGeometries(t,e){for(const i of t)if("PlaneGeometry"===i.type){const t=(i.width||1)/2,s=(i.height||1)/2;e.geometries[i.uuid]={positions:new Float32Array([-t,-s,0,t,-s,0,t,s,0,-t,s,0]),indices:new Uint32Array([0,1,2,0,2,3]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),normals:new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1])}}else if("SphereGeometry"===i.type)e.geometries[i.uuid]=this.parseSphereGeometry(i);else if("BufferGeometry"===i.type&&i.data){const t=this.parseBufferGeometry(i.data);e.geometries[i.uuid]=t}else"QuarksGeometry"===i.type&&("string"!=typeof i.url||i.positions||console.warn(`[QuarksLoader] Geometry "${i.url}" is an external file; use load(), loadFromJSON(), or resolveResources() before parse().`),e.geometries[i.uuid]=this.share({positions:new Float32Array(i.positions??[]),indices:i.indices?new Uint32Array(i.indices):new Uint32Array(0),uvs:i.uvs?new Float32Array(i.uvs):void 0,uvs2:i.uvs2?new Float32Array(i.uvs2):void 0,normals:i.normals?new Float32Array(i.normals):void 0}))}share(t){if(!1===this.options.shareResources)return t;const e=ea(Ko,this.scene),i=function(t){let e=2166136261,i=2654435769;const s=[t.positions,t.indices,t.uvs,t.uvs2,t.normals];let n="";for(const t of s){if(void 0===t){n+="-,";continue}const s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n+=s.length+",";for(let t=0;t<s.length;t++)e=Math.imul(e^s[t],16777619),i=Math.imul(i^s[t],1540483477)^i>>>15}return`${n}${(e>>>0).toString(16)}${(i>>>0).toString(16)}`}(t),s=e.get(i);return void 0!==s?s:(e.set(i,t),t)}static clearSharedResources(t){Zo.delete(t),Ko.delete(t),ta.delete(t)}static joinUrl(t,e){return/^(data|blob):/i.test(e)||/^[a-z][a-z0-9+.-]*:\/\//i.test(e)||e.startsWith("/")?e:t+e}parseSphereGeometry(t){const e=t.radius??.5,i=Math.max(3,Math.floor(t.widthSegments??16)),s=Math.max(2,Math.floor(t.heightSegments??8)),n=t.phiStart??0,r=t.phiLength??2*Math.PI,o=t.thetaStart??0,a=t.thetaLength??Math.PI,h=[],l=[],c=[],u=[],d=[];let f=0;for(let t=0;t<=s;t++){const u=[],m=t/s,p=o+m*a;for(let t=0;t<=i;t++){const s=t/i,o=n+s*r,a=-e*Math.cos(o)*Math.sin(p),d=e*Math.cos(p),y=e*Math.sin(o)*Math.sin(p);h.push(a,d,y);const g=Math.hypot(a,d,y)||1;l.push(a/g,d/g,y/g),c.push(s,1-m),u.push(f++)}d.push(u)}const m=o<=0,p=o+a>=Math.PI;for(let t=0;t<s;t++)for(let e=0;e<i;e++){const i=d[t][e+1],n=d[t][e],r=d[t+1][e],o=d[t+1][e+1];0===t&&m||u.push(i,n,o),t===s-1&&p||u.push(n,r,o)}const y=h.length/3>65535?new Uint32Array(u):new Uint16Array(u);return{positions:new Float32Array(h),indices:y,uvs:new Float32Array(c),normals:new Float32Array(l)}}parseBufferGeometry(t){let e,i,s,n=new Float32Array(0),r=new Uint32Array(0);const o=t.attributes?.uv1??t.attributes?.uv2;if(t.interleavedBuffers&&t.arrayBuffers){const r={};for(const[e,i]of Object.entries(t.interleavedBuffers)){const s=t.arrayBuffers[i.buffer];if(s){const t=new Float32Array(Array.isArray(s)?this.int32ArrayToFloat32(s):s);r[e]={data:t,stride:i.stride}}}if(t.attributes){if(t.attributes.position?.isInterleavedBufferAttribute){const e=t.attributes.position,i=r[e.data];i&&(n=this.extractInterleavedAttribute(i.data,i.stride,e.offset,e.itemSize))}if(t.attributes.uv?.isInterleavedBufferAttribute){const i=t.attributes.uv,s=r[i.data];s&&(e=this.extractInterleavedAttribute(s.data,s.stride,i.offset,i.itemSize))}if(o?.isInterleavedBufferAttribute){const t=r[o.data];t&&(i=this.extractInterleavedAttribute(t.data,t.stride,o.offset,o.itemSize))}if(t.attributes.normal?.isInterleavedBufferAttribute){const e=t.attributes.normal,i=r[e.data];i&&(s=this.extractInterleavedAttribute(i.data,i.stride,e.offset,e.itemSize))}}}else t.attributes&&(t.attributes.position?.array&&(n=new Float32Array(t.attributes.position.array)),t.attributes.uv?.array&&(e=new Float32Array(t.attributes.uv.array)),o?.array&&(i=new Float32Array(o.array)),t.attributes.normal?.array&&(s=new Float32Array(t.attributes.normal.array)));return t.index&&(r="Uint16Array"===t.index.type?new Uint16Array(t.index.array):new Uint32Array(t.index.array)),r=Or(n,r),{positions:n,indices:r,uvs:e,uvs2:i,normals:s}}extractInterleavedAttribute(t,e,i,s){const n=Math.floor(t.length/e),r=new Float32Array(n*s);for(let o=0;o<n;o++)for(let n=0;n<s;n++)r[o*s+n]=t[o*e+i+n];return r}int32ArrayToFloat32(t){const e=new ArrayBuffer(4*t.length),i=new Int32Array(e);for(let e=0;e<t.length;e++)i[e]=t[e];return new Float32Array(e)}async resolveResourceUrl(t,e,i){return ua.resolveWith(this.options.resolver,t,e,i)}async fetchEffectDocument(t,e){const i=this.options.baseUrl||t.substring(0,t.lastIndexOf("/")+1),s=await this.resolveResourceUrl(t,"effect",i);return{json:await ua.fetchJsonWith(this.options.resolver,s,void 0,e),baseUrl:i}}async loadDocuments(t,e){if(0===t.length)return[];la(this.scene,e.signal);const i=new AbortController,s=()=>i.abort(aa(e.signal));e.signal?.addEventListener("abort",s,{once:!0});try{return await this.loadResolvedDocuments(t,e,i)}finally{e.signal?.removeEventListener("abort",s)}}async loadResolvedDocuments(t,e,i){const s=t.length,n=i.signal,r=new Array(s).fill(null),o=new Array(s).fill(!1);let a=0;const h=(t,i)=>{o[t]||n.aborted||(o[t]=!0,r[t]=i,a++,e.onProgress?.(a,s))};await ca(Promise.all(t.map(async(i,n)=>{if(i)try{await this.resolveResources(i.json,i.baseUrl)}catch(i){if(!e.continueOnError)throw i;console.warn(`[QuarksLoader] Failed to resolve resources for effect ${n+1}/${s}:`,i),t[n]=null,h(n,null)}})),this.scene,n);const l=[],c=[];try{for(let i=0;i<s;i++){if(o[i])continue;const r=t[i];if(!r){h(i,null);continue}let a;try{a=this.parseDocument(r.json,"")}catch(t){if(!e.continueOnError)throw t;console.warn(`[QuarksLoader] Failed to parse effect ${i+1}/${s}:`,t),h(i,null);continue}l.push(a),c.push(this.finishLoad(a,n).then(()=>h(i,a.root)))}await Promise.all(c)}catch(t){throw n.aborted||i.abort(t),Promise.allSettled(c),this.scene.isDisposed||l.forEach(t=>cr(t.root)),t}return r}static async mapPool(t,e,i){if(0===t.length)return[];const s=void 0!==e&&e>0?e:t.length,n=new Array(t.length);let r=0;const o=Math.min(s,t.length);return await Promise.all(Array.from({length:o},()=>(async()=>{for(;r<t.length;){const e=r++;n[e]=await i(t[e],e)}})())),n}static async resolveWith(t,e,i,s){return t?.resolve?t.resolve(e,i,s):ua.joinUrl(s,e)}static fetchJsonWith(t,e,i,s){const n=async()=>{if(t?.fetchJson)return s?t.fetchJson(e,{signal:s}):t.fetchJson(e);const i=await(s?fetch(e,{signal:s}):fetch(e));if(!i.ok)throw new Error(`HTTP ${i.status}`);return i.json()};if(!i)return n();const r=ea(ta,i),o=`json|${e}`;let a=r.get(o);return void 0===a&&(a=n().catch(t=>{throw r.get(o)===a&&r.delete(o),t}),r.set(o,a)),a}static async inlineGeometryEntries(t,e,i=ua.warnResourceError){const s=Array.isArray(t?.geometries)?t.geometries:[];await Promise.all(s.filter(t=>"string"==typeof t?.url&&!t.positions).map(async t=>{try{const i=await e(t.url);for(const e of["positions","indices","uvs","uvs2","normals"]){const s=i?.[e];void 0!==s&&(t[e]=Array.isArray(s)?s.slice():s)}delete t.url}catch(e){i("geometry",t.url,e)}}))}static warnResourceError(t,e,i){console.warn(`[QuarksLoader] Could not load ${t} "${e}":`,i)}reportResourceError(t,e,i){(this.options.onResourceError??ua.warnResourceError)(t,e,i)}parseImages(t,e,i){for(const s of t){s.url&&ua.warnIfNotAnImageUrl(s.url),i.images[s.uuid]=s.url?ua.joinUrl(e,s.url):null;const t=sa.get(s)??s.url;t&&!/^(data|blob):/i.test(t)&&(i.imageSources[s.uuid]=t)}}static warnIfNotAnImageUrl(t){/^(data|blob):/i.test(t)||/\.(png|jpe?g|webp|gif|bmp|ktx2?|dds|env|basis)(\?|#|$)/i.test(t)||console.warn(`[QuarksLoader] Image "${t}" does not look like an image; its texture will fail to load. This usually means the effect was exported without embedding that texture.`)}parseTextures(t,e){for(const i of t){const t=e.images[i.image];if(t){const s=void 0===i.invertY||!!i.invertY,n=!!i.noMipmap,r=!1!==this.options.shareResources,o=r?[s,n,i.samplingMode,i.wrap,i.repeat,i.offset,i.rotation].join("|")+"|"+t:"",a=r?ea(Zo,this.scene):void 0,h=a?.get(o);if(void 0!==h){e.textures[i.uuid]=h;continue}let l;const c=new Promise(t=>l=t);let u,d=!1;const f={noMipmap:n,invertY:s,samplingMode:"number"==typeof i.samplingMode?i.samplingMode:void 0,onLoad:()=>l(),onError:(e,i)=>{d=!0,void 0!==a&&a.get(o)===u&&a.delete(o),this.reportResourceError("image",t,i??e),l()}};try{u=new M(t,this.scene,f)}catch{e.textures[i.uuid]=null;continue}oa.set(u,c);const m=e.imageSources[i.image];void 0!==m&&Lo(u,m,t),u.onDisposeObservable.addOnce(()=>l()),Array.isArray(i.wrap)&&(u.wrapU=this.mapWrapMode(i.wrap[0]),u.wrapV=this.mapWrapMode(i.wrap[1]??i.wrap[0])),Array.isArray(i.repeat)&&(u.uScale=i.repeat[0]??1,u.vScale=i.repeat[1]??1),Array.isArray(i.offset)&&(u.uOffset=i.offset[0]??0,u.vOffset=i.offset[1]??0),"number"==typeof i.rotation&&(u.wAng=i.rotation),void 0===a||d||(a.set(o,u),u.onDisposeObservable.addOnce(()=>{a.get(o)===u&&a.delete(o)})),e.textures[i.uuid]=u}else e.textures[i.uuid]=null}}mapWrapMode(t){switch(t){case 1001:return M.CLAMP_ADDRESSMODE;case 1002:return M.MIRROR_ADDRESSMODE;default:return M.WRAP_ADDRESSMODE}}parseMaterials(t,e){for(const i of t){const t={uuid:i.uuid,transparent:i.transparent??!0,blending:i.blending??1,side:i.side??2,depthTest:i.depthTest??!0,depthWrite:i.depthWrite??!1,alphaTest:i.alphaTest??0,texture:null},s=i.map??i.texture;s&&(t.texture=e.textures[s]||null);const n=i.reflectionAtlas;if(n&&(t.reflectionAtlas=e.textures[n]||null),"number"==typeof i.reflectionLevel&&(t.reflectionLevel=i.reflectionLevel),"unlit"!==i.lighting&&"fixed"!==i.lighting&&"scene"!==i.lighting||(t.lighting=i.lighting),i.rim&&"object"==typeof i.rim&&(t.rim=i.rim),i.mapUV&&"object"==typeof i.mapUV&&(t.mapUV=i.mapUV),i.gradientMap&&"object"==typeof i.gradientMap&&(t.gradientMap={...i.gradientMap,ramp:i.gradientMap.ramp&&e.textures[i.gradientMap.ramp]||null}),i.erosion&&"object"==typeof i.erosion&&(t.erosion={...i.erosion,mask:i.erosion.mask&&e.textures[i.erosion.mask]||null}),i.uvDistortion&&"object"==typeof i.uvDistortion&&(t.uvDistortion={...i.uvDistortion,map:i.uvDistortion.map&&e.textures[i.uvDistortion.map]||null}),"number"==typeof i.alphaMode)t.alphaMode=i.alphaMode;else{const e={1:r.ALPHA_COMBINE,2:r.ALPHA_ADD,3:r.ALPHA_SUBTRACT,4:r.ALPHA_MULTIPLY};t.alphaMode=e[i.blending]||r.ALPHA_COMBINE}e.materials[i.uuid]=t}}getGeometry(t,e){if(e)return t.geometries[e]}getMaterial(t,e){if(!e)return;const i=Array.isArray(e)?e[0]:e;return t.materials[i]}createPlaceholderNode(t,e){const i=new n(e||t||"node",this.scene);return i.quarksOriginalType=t,i}createMeshNode(t,e){const i=new p(t.name||t.type||"mesh",this.scene),s=this.getGeometry(e,t.geometry);if(s&&s.positions.length>0&&s.indices.length>0){const t=new x;t.positions=s.positions,t.indices=s.indices,s.uvs&&s.uvs.length>0&&(t.uvs=s.uvs),s.uvs2&&s.uvs2.length>0&&(t.uvs2=s.uvs2),s.normals&&s.normals.length>0&&(t.normals=s.normals),t.applyToMesh(i,!0)}const n=this.getMaterial(e,t.material);if(n){const t=new z(`quarks_loader_material_${n.uuid}`,this.scene);e.ownedMaterials.push(t),t.alphaMode=n.alphaMode??r.ALPHA_COMBINE,t.backFaceCulling=2!==n.side,t.alphaCutOff=n.alphaTest??0,t.disableDepthWrite=!n.depthWrite,n.texture&&(t.diffuseTexture=n.texture,t.opacityTexture=n.texture),i.material=t}return i}parseObject(t,e){let i;switch(t.type){case"QuarksPrefab":i=ko.fromJSON(t,this.scene);break;case"ParticleEmitter":if(t.ps){i=this.parseParticleSystem(t.ps,e).emitter;break}i=this.createPlaceholderNode(t.type,t.name);break;case"Mesh":case"SkinnedMesh":case"InstancedMesh":case"BatchedMesh":i=this.createMeshNode(t,e);break;case"Scene":case"Group":case"Object3D":case"PerspectiveCamera":case"OrthographicCamera":case"AmbientLight":case"DirectionalLight":case"PointLight":case"RectAreaLight":case"SpotLight":case"HemisphereLight":case"LightProbe":case"LOD":case"Line":case"LineSegments":case"LineLoop":case"PointCloud":case"Points":case"Sprite":case"Bone":i=this.createPlaceholderNode(t.type,t.name);break;default:i=new n(t.name||t.type||"node",this.scene)}if(t.uuid&&(i._quarksUUID=t.uuid),t.name&&(i.name=t.name),t.matrix){const e=f.FromArray(t.matrix),s=new c(1,1,1),n=m.Identity(),r=new c(0,0,0);e.decompose(s,n,r),i.position.copyFrom(r),i.scaling.copyFrom(s),i.rotationQuaternion=n}else t.position&&i.position.set(t.position[0],t.position[1],t.position[2]),t.scale&&i.scaling.set(t.scale[0],t.scale[1],t.scale[2]),t.quaternion?i.rotationQuaternion=new m(t.quaternion[0],t.quaternion[1],t.quaternion[2],t.quaternion[3]):t.rotation&&i.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]);if(void 0!==t.visible&&i.setEnabled(t.visible),!1===t.isVisible&&i instanceof p&&(i.isVisible=!1),t.children)for(const s of t.children){this.parseObject(s,e).parent=i}return i}parseParticleSystem(t,e){const i=Do.fromJSON(t,e,{},this.scene);return i._meshSurfaceReferenceUUID="mesh_surface"===t?.shape?.type?t?.shape?.mesh:void 0,i}linkReferences(t){const e={},i=t=>{t._quarksUUID&&(e[t._quarksUUID]=t);for(const e of t.getChildren())e instanceof n&&i(e)};i(t);const s=i=>{if(i instanceof ko&&i.resolveReferences(t),i instanceof dr){const t=i.system,s=t._meshSurfaceReferenceUUID;if(s&&"mesh_surface"===t.emitterShape.type){const n=e[s];n instanceof p?t.emitterShape.mesh=n:console.warn(`[QuarksLoader] Emitter "${i.name}" has a mesh surface shape on "${s}", `+(n?"which is not a mesh":"which is not in the effect")+"; it emits nothing until a mesh is set.")}for(let s=0;s<t.behaviors.length;s++)if(t.behaviors[s]instanceof Le){const n=t.behaviors[s],r=n.subParticleSystem;if("string"!=typeof r)continue;const o=e[r];o instanceof dr?(n.subParticleSystem=o,o.system.onlyUsedByOther=!0):(n.subParticleSystem=void 0,""!==r&&console.warn(`[QuarksLoader] Emitter "${i.name}" has a sub emitter targeting "${r}", `+(o?"which is not a particle emitter":"which is not in the effect")+"; that sub emitter is skipped."))}}for(const t of i.getChildren())t instanceof n&&s(t)};s(t)}}const da={};const fa={name:""},ma=[{name:"billboard",settings:{renderMode:xs.BillBoard}},{name:"vertical billboard",settings:{renderMode:xs.VerticalBillBoard}},{name:"horizontal billboard",settings:{renderMode:xs.HorizontalBillBoard}},{name:"stretched",settings:{renderMode:xs.StretchedBillBoard}},{name:"beam",settings:{renderMode:xs.Beam}},{name:"mesh",settings:{renderMode:xs.Mesh}},{name:"mesh scene lit",settings:{renderMode:xs.Mesh,lighting:"scene"}},{name:"mesh unlit",settings:{renderMode:xs.Mesh,lighting:"unlit"}},{name:"mesh rim",settings:{renderMode:xs.Mesh,rim:bs({mode:"add"})}},{name:"mesh unlit rim mix",settings:{renderMode:xs.Mesh,lighting:"unlit",rim:bs({mode:"mix"})}},{name:"mesh unlit rim fade",settings:{renderMode:xs.Mesh,lighting:"unlit",rim:bs({mode:"fade"})}},{name:"mesh reflecting",settings:{renderMode:xs.Mesh,reflectionAtlas:da},context:{envAtlasReady:!0}},{name:"mesh unlit reflecting rim fade",settings:{renderMode:xs.Mesh,lighting:"unlit",reflectionAtlas:da,rim:bs({mode:"fade"})},context:{envAtlasReady:!0}},{name:"trail",settings:{renderMode:xs.Trail}}],pa=[fa,{name:"pivot",settings:{pivot:new ot(.5,0,0)}},{name:"size limits",settings:{minParticleSize:.01}},{name:"pivot size limits",settings:{pivot:new ot(0,.5,.5),maxParticleSize:.5}}],ya=[fa,{name:"sheet",settings:{uTileCount:4,vTileCount:2}},{name:"sheet blend",settings:{uTileCount:4,vTileCount:2,blendTiles:!0}}],ga=[fa,{name:"map",settings:{texture:da}}],va=[fa,{name:"soft",settings:{softParticles:!0},context:{depth:{packed:!1}}},{name:"soft packed",settings:{softParticles:!0},context:{depth:{packed:!0}}}],xa=[fa,{name:"alpha test",settings:{materialAlphaTest:.5}}],wa=[fa,{name:"fog",settings:{applyFog:!0}},{name:"fog additive",settings:{applyFog:!0,materialBlendMode:r.ALPHA_ADD}}],ba=(()=>{const t=Bs({tiling:[2,2]}),e=Bs({channel:1,tiling:[2,2]}),i=Is({map:da}),s=Is({map:da,mapUV:{channel:1}}),n=As({ramp:da}),r=$s({}),o=$s({mask:da}),a=$s({mask:da,maskUV:{channel:1}});return[{name:"map transform",settings:{mapUV:t}},{name:"map transform uv1",settings:{mapUV:e}},{name:"gradient map",settings:{gradientMap:n}},{name:"erosion",settings:{erosion:r}},{name:"erosion mask",settings:{erosion:o}},{name:"erosion mask uv1",settings:{erosion:a}},{name:"distortion",settings:{uvDistortion:i}},{name:"distortion uv1",settings:{uvDistortion:s}},{name:"map transform distortion gradient erosion mask",settings:{mapUV:t,uvDistortion:i,gradientMap:n,erosion:o}},{name:"map transform uv1 distortion gradient erosion",settings:{mapUV:e,uvDistortion:i,gradientMap:n,erosion:r}},{name:"every effect on uv1",settings:{mapUV:e,uvDistortion:s,gradientMap:n,erosion:a}}]})(),Sa=["billboard","stretched","beam","mesh","mesh unlit","mesh unlit rim mix","mesh reflecting","trail"],Ma={name:"uv2",context:{meshUV2:!0}},za={name:"soft packed alpha test fog additive",settings:{softParticles:!0,materialAlphaTest:.5,applyFog:!0,materialBlendMode:r.ALPHA_ADD},context:{depth:{packed:!0}}};function _a(){const t=new Set,e=[],i=i=>{const s={renderMode:n=xs.BillBoard,texture:null,reflectionAtlas:null,uTileCount:1,vTileCount:1,blendTiles:!1,softParticles:!1,materialAlphaTest:0,materialTransparent:!0,materialBlendMode:r.ALPHA_COMBINE,applyFog:!1,pivot:void 0,minParticleSize:0,maxParticleSize:1/0,lighting:n===xs.Mesh?"fixed":void 0,rim:void 0,mapUV:void 0,uvDistortion:void 0,gradientMap:void 0,erosion:void 0};var n;const o={depth:null,envAtlasReady:!1,meshUV2:!1};for(const t of i)Object.assign(s,t.settings),Object.assign(o,t.context);const a=Rn(s,o),h=a.name+" "+a.defines.join(",");if(t.has(h))return;t.add(h);const l=i.map(t=>t.name).filter(t=>""!==t);e.push({name:`${l.join(", ")} [${a.defines.join(",")||"none"}]`,program:a})};for(const t of ma)for(const e of pa)for(const s of ya)for(const n of ga)for(const r of va)for(const o of xa)for(const a of wa)i([t,e,s,n,r,o,a]);for(const t of ma.filter(t=>Sa.includes(t.name)))for(const e of t.settings?.renderMode===xs.Mesh?[fa,Ma]:[fa])for(const s of ba)for(const n of ga)for(const r of[fa,ya[2]])for(const o of[fa,za])i([t,e,s,n,r,o]);return e}is(os);export{Nt as ApplyCollision,ge as ApplyForce,we as ApplySequences,Zt as AxisAngleGenerator,rr as BatchedRenderer,zi as BehaviorFromJSON,Mi as BehaviorTypes,jt as Bezier,ki as BoxEmitFrom,Li as BoxEmitter,be as ChangeEmitDirection,Ji as CircleEmitter,Me as ColorBySpeed,ae as ColorGeneratorFromJSON,ze as ColorOverLife,Kt as ColorRange,Wi as ConeEmitter,oe as ConstantColor,Qt as ConstantValue,I as DEG2RAD,Qi as DonutEmitter,Os as EROSION_DEFAULT_SOFTNESS,Gi as EdgeEmitter,mr as EffectPool,Le as EmitSubParticleSystem,ye as EmitterFrame,ts as EmitterFromJSON,Ri as EmitterMode,Ki as EmitterShapes,bt as Euler,he as EulerGenerator,qe as ForceOverLife,Je as FrameOverLife,Vs as GRADIENT_MAP_WEIGHTS,fe as GeneratorFromJSON,ie as Gradient,We as GravityForce,ji as GridEmitter,Yi as HemisphereEmitter,Qe as InheritVelocity,Gt as IntervalValue,Ge as LimitSpeedOverLife,jn as MAX_TRAIL_TESSELLATION,nt as MathUtils,St as Matrix3,ut as Matrix4,rs as MeshSurfaceEmitter,os as MeshSurfaceEmitterPlugin,Te as NodeParticle,hi as Noise,li as OrbitOverLife,dr as ParticleEmitter,_e as ParticleStore,Do as ParticleSystem,Ht as PiecewiseBezier,Yt as PiecewiseFunction,es as Plugins,Hi as PointEmitter,Jo as QUARKS_FORMAT_VERSION,na as QuarksFormatError,ua as QuarksLoader,ko as QuarksPrefab,fr as QuarksUtil,rt as Quaternion,_t as QuaternionView,U as RAD2DEG,se as RandomColor,re as RandomColorBetweenGradient,le as RandomQuatGenerator,Pe as RecordState,Zi as RectangleEmitter,xs as RenderMode,ci as Rotation3DOverLife,ui as RotationBySpeed,ce as RotationGeneratorFromJSON,di as RotationOverLife,xe as SequencerFromJSON,Di as ShapeTransform,fi as SizeBySpeed,mi as SizeOverLife,pi as SpeedOverLife,Xi as SphereEmitter,Oe as SpriteParticle,ke as SubEmitterInheritMask,De as SubParticleEmitMode,ve as TextureSequencer,Ce as TrailParticle,gi as TurbulenceField,Fs as UV_DISTORTION_DEFAULT_STRENGTH,Cs as UV_DISTORTION_DEFAULT_UV,Ds as VFXBatch,Xt as ValueGeneratorFromJSON,At as Vector2,ot as Vector3,ue as Vector3Function,de as Vector3GeneratorFromJSON,Ot as Vector3View,Pt as Vector4,Ft as Vector4View,bi as VelocityOverLife,lt as WebGLCoordinateSystem,ct as WebGPUCoordinateSystem,Si as WidthOverLength,Mr as cacheEnvAtlas,K as ceilPowerOfTwo,E as clamp,Vr as createEnvAtlasFromFaceUrls,$ as createSeededRandom,wr as cubeFaceUrls,L as damp,vs as decodeSoftDepth,ws as defaultMeshLighting,H as degToRad,it as denormalize,zr as disposeEnvAtlas,Tr as ensureEnvAtlasFromCube,Ps as erosionEqual,N as euclideanModulo,tt as floorPowerOfTwo,B as generateUUID,Sr as getCachedEnvAtlas,Et as getPhysicsResolver,T as getRandomSource,qi as getValueFromEmitterMode,Ts as gradientMapEqual,k as inverseLerp,Z as isPowerOfTwo,R as lerp,is as loadPlugin,D as mapLinear,Es as mapUVEqual,Ss as meshRimEqual,st as normalize,$s as normalizeErosion,As as normalizeGradientMap,Bs as normalizeMapUV,bs as normalizeMeshRim,Ms as normalizeTextureUV,Is as normalizeUVDistortion,q as pingpong,Ni as planBehaviorFusion,ns as quarksNodeId,X as radToDeg,G as randFloat,j as randFloatSpread,Q as randInt,A as random,me as readBehaviorSpace,Ns as readsUV1,Y as seededRandom,Xo as serializeEffect,Bt as setPhysicsResolver,et as setQuaternionFromProperEuler,O as setRandomSource,Rn as shaderProgram,_a as shaderVariants,W as smootherstep,J as smoothstep,gs as softDepthParams,Se as speedFraction,Re as subEmitterInheritMask,qo as textureSourceUrl,zs as textureUVEqual,_s as textureUVToJSON,Hn as trailCurveTension,er as trailLifetime,tr as trailMinVertexDistance,Yn as trailTessellation,Zn as trailTextureMode,Kn as trailTextureScale,ss as unloadPlugin,Us as uvDistortionEqual,P as withRandomSource};
1
+ import{VertexBuffer as t}from"@babylonjs/core/Buffers/buffer.js";import{RandomGUID as e}from"@babylonjs/core/Misc/guid.js";import{Frustum as i}from"@babylonjs/core/Maths/math.frustum.js";import{Plane as s}from"@babylonjs/core/Maths/math.plane.js";import{TransformNode as n}from"@babylonjs/core/Meshes/transformNode.js";import{Constants as r}from"@babylonjs/core/Engines/constants.js";import{Color3 as o}from"@babylonjs/core/Maths/math.color.js";import{Vector3 as a,Matrix as h,Vector4 as l,Vector2 as c,Quaternion as u}from"@babylonjs/core/Maths/math.vector.js";import{Camera as d}from"@babylonjs/core/Cameras/camera.js";import{ShaderMaterial as f}from"@babylonjs/core/Materials/shaderMaterial.js";import{RawTexture as m}from"@babylonjs/core/Materials/Textures/rawTexture.js";import{Mesh as p}from"@babylonjs/core/Meshes/mesh.js";import{VertexData as y}from"@babylonjs/core/Meshes/mesh.vertexData.js";import{PrepareUniformsForImageProcessing as g,PrepareSamplersForImageProcessing as v}from"@babylonjs/core/Materials/imageProcessingConfiguration.functions.js";import{ShaderStore as x}from"@babylonjs/core/Engines/shaderStore.js";import"@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js";import"@babylonjs/core/Shaders/ShadersInclude/imageProcessingDeclaration.js";import"@babylonjs/core/Shaders/ShadersInclude/imageProcessingFunctions.js";import"@babylonjs/core/ShadersWGSL/ShadersInclude/helperFunctions.js";import"@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingDeclaration.js";import"@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingFunctions.js";import{Effect as S}from"@babylonjs/core/Materials/effect.js";import{ShaderLanguage as b}from"@babylonjs/core/Materials/shaderLanguage.js";import{BoundingInfo as w}from"@babylonjs/core/Culling/boundingInfo.js";import{BaseTexture as M}from"@babylonjs/core/Materials/Textures/baseTexture.js";import{Scene as z}from"@babylonjs/core/scene.js";import{InstancedMesh as _}from"@babylonjs/core/Meshes/instancedMesh.js";import{Texture as A}from"@babylonjs/core/Materials/Textures/texture.js";import{StandardMaterial as P}from"@babylonjs/core/Materials/standardMaterial.js";let O=null;function T(){return null===O?Math.random():O()}function V(){return O??Math.random}function E(t){const e=V();return O=t,e}function $(t){let e=t>>>0||2654435769;return()=>{e=e+1831565813|0;let t=e;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}function C(t,e){const i=E(t);try{return e()}finally{E(i)}}const I=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let N=1234567;const F=Math.PI/180,B=180/Math.PI;function U(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return(I[255&t]+I[t>>8&255]+I[t>>16&255]+I[t>>24&255]+"-"+I[255&e]+I[e>>8&255]+"-"+I[e>>16&15|64]+I[e>>24&255]+"-"+I[63&i|128]+I[i>>8&255]+"-"+I[i>>16&255]+I[i>>24&255]+I[255&s]+I[s>>8&255]+I[s>>16&255]+I[s>>24&255]).toLowerCase()}function R(t,e,i){return Math.max(e,Math.min(i,t))}function L(t,e){return(t%e+e)%e}function D(t,e,i,s,n){return s+(t-e)*(n-s)/(i-e)}function k(t,e,i){return t!==e?(i-t)/(e-t):0}function q(t,e,i){return(1-i)*t+i*e}function J(t,e,i,s){return q(t,e,1-Math.exp(-i*s))}function G(t,e=1){return e-Math.abs(L(t,2*e)-e)}function W(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}function j(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*t*(t*(6*t-15)+10)}function Q(t,e){return t+Math.floor(T()*(e-t+1))}function H(t,e){return t+T()*(e-t)}function Y(t){return t*(.5-T())}function X(t){void 0!==t&&(N=t);let e=N+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}function Z(t){return t*F}function K(t){return t*B}function tt(t){return!(t&t-1)&&0!==t}function et(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function it(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function st(t,e,i,s,n){const r=Math.cos,o=Math.sin,a=r(i/2),h=o(i/2),l=r((e+s)/2),c=o((e+s)/2),u=r((e-s)/2),d=o((e-s)/2),f=r((s-e)/2),m=o((s-e)/2);switch(n){case"XYX":t.set(a*c,h*u,h*d,a*l);break;case"YZY":t.set(h*d,a*c,h*u,a*l);break;case"ZXZ":t.set(h*u,h*d,a*c,a*l);break;case"XZX":t.set(a*c,h*m,h*f,a*l);break;case"YXY":t.set(h*f,a*c,h*m,a*l);break;case"ZYZ":t.set(h*m,h*f,a*c,a*l);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function nt(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function rt(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const ot={DEG2RAD:F,RAD2DEG:B,generateUUID:U,clamp:R,euclideanModulo:L,mapLinear:D,inverseLerp:k,lerp:q,damp:J,pingpong:G,smoothstep:W,smootherstep:j,randInt:Q,randFloat:H,randFloatSpread:Y,seededRandom:X,degToRad:Z,radToDeg:K,isPowerOfTwo:tt,ceilPowerOfTwo:et,floorPowerOfTwo:it,setQuaternionFromProperEuler:st,normalize:rt,denormalize:nt};class at{constructor(t=0,e=0,i=0,s=1){this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,n,r,o){let a=i[s+0],h=i[s+1],l=i[s+2],c=i[s+3];const u=n[r+0],d=n[r+1],f=n[r+2],m=n[r+3];if(0===o)return t[e+0]=a,t[e+1]=h,t[e+2]=l,void(t[e+3]=c);if(1===o)return t[e+0]=u,t[e+1]=d,t[e+2]=f,void(t[e+3]=m);if(c!==m||a!==u||h!==d||l!==f){let t=1-o;const e=a*u+h*d+l*f+c*m,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const n=Math.sqrt(s),r=Math.atan2(n,e*i);t=Math.sin(t*r)/n,o=Math.sin(o*r)/n}const n=o*i;if(a=a*t+u*n,h=h*t+d*n,l=l*t+f*n,c=c*t+m*n,t===1-o){const t=1/Math.sqrt(a*a+h*h+l*l+c*c);a*=t,h*=t,l*=t,c*=t}}t[e]=a,t[e+1]=h,t[e+2]=l,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,n,r){const o=i[s],a=i[s+1],h=i[s+2],l=i[s+3],c=n[r],u=n[r+1],d=n[r+2],f=n[r+3];return t[e]=o*f+l*c+a*d-h*u,t[e+1]=a*f+l*u+h*c-o*d,t[e+2]=h*f+l*d+o*u-a*c,t[e+3]=l*f-o*c-a*u-h*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new at(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,s=t._y,n=t._z,r=t._order,o=Math.cos,a=Math.sin,h=o(i/2),l=o(s/2),c=o(n/2),u=a(i/2),d=a(s/2),f=a(n/2);switch(r){case"XYZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"YXZ":this._x=u*l*c+h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"ZXY":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c-u*d*f;break;case"ZYX":this._x=u*l*c-h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c+u*d*f;break;case"YZX":this._x=u*l*c+h*d*f,this._y=h*d*c+u*l*f,this._z=h*l*f-u*d*c,this._w=h*l*c-u*d*f;break;case"XZY":this._x=u*l*c-h*d*f,this._y=h*d*c-u*l*f,this._z=h*l*f+u*d*c,this._w=h*l*c+u*d*f;break;default:console.warn("../math.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],n=e[8],r=e[1],o=e[5],a=e[9],h=e[2],l=e[6],c=e[10],u=i+o+c;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(l-a)*t,this._y=(n-h)*t,this._z=(r-s)*t}else if(i>o&&i>c){const t=2*Math.sqrt(1+i-o-c);this._w=(l-a)/t,this._x=.25*t,this._y=(s+r)/t,this._z=(n+h)/t}else if(o>c){const t=2*Math.sqrt(1+o-i-c);this._w=(n-h)/t,this._x=(s+r)/t,this._y=.25*t,this._z=(a+l)/t}else{const t=2*Math.sqrt(1+c-i-o);this._w=(r-s)/t,this._x=(n+h)/t,this._y=(a+l)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(R(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,n=t._z,r=t._w,o=e._x,a=e._y,h=e._z,l=e._w;return this._x=i*l+r*o+s*h-n*a,this._y=s*l+r*a+n*o-i*h,this._z=n*l+r*h+i*a-s*o,this._w=r*l-i*o-s*a-n*h,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,n=this._z,r=this._w;let o=r*t._w+i*t._x+s*t._y+n*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=r,this._x=i,this._y=s,this._z=n,this;const a=1-o*o;if(a<=Number.EPSILON){const t=1-e;return this._w=t*r+e*this._w,this._x=t*i+e*this._x,this._y=t*s+e*this._y,this._z=t*n+e*this._z,this.normalize(),this}const h=Math.sqrt(a),l=Math.atan2(h,o),c=Math.sin((1-e)*l)/h,u=Math.sin(e*l)/h;return this._w=r*c+this._w*u,this._x=i*c+this._x*u,this._y=s*c+this._y*u,this._z=n*c+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*T(),e=2*Math.PI*T(),i=T(),s=Math.sqrt(1-i),n=Math.sqrt(i);return this.set(s*Math.sin(t),s*Math.cos(t),n*Math.sin(e),n*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}Object.defineProperty(at.prototype,"isQuaternion",{value:!0});class ht{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new ht(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(ct.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(ct.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6]*s,this.y=n[1]*e+n[4]*i+n[7]*s,this.z=n[2]*e+n[5]*i+n[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=t.elements,r=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*e+n[4]*i+n[8]*s+n[12])*r,this.y=(n[1]*e+n[5]*i+n[9]*s+n[13])*r,this.z=(n[2]*e+n[6]*i+n[10]*s+n[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,n=t.x,r=t.y,o=t.z,a=t.w,h=2*(r*s-o*i),l=2*(o*e-n*s),c=2*(n*i-r*e);return this.x=e+a*h+r*c-o*l,this.y=i+a*l+o*h-n*c,this.z=s+a*c+n*l-r*h,this}transformDirection(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s,this.y=n[1]*e+n[5]*i+n[9]*s,this.z=n[2]*e+n[6]*i+n[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,n=t.z,r=e.x,o=e.y,a=e.z;return this.x=s*a-n*o,this.y=n*r-i*a,this.z=i*o-s*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return lt.copy(this).projectOnVector(t),this.sub(lt)}reflect(t){return this.sub(lt.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(R(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}random(){return this.x=T(),this.y=T(),this.z=T(),this}randomDirection(){const t=T()*Math.PI*2,e=2*T()-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this.z=Math.abs(this.z),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}Object.defineProperty(ht.prototype,"isVector3",{value:!0});const lt=new ht,ct=new at,ut=2e3,dt=2001;class ft{constructor(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,i){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,i,s,n,r,o,a,h,l,c,u,d,f,m,p){const y=this.elements;return y[0]=t,y[4]=e,y[8]=i,y[12]=s,y[1]=n,y[5]=r,y[9]=o,y[13]=a,y[2]=h,y[6]=l,y[10]=c,y[14]=u,y[3]=d,y[7]=f,y[11]=m,y[15]=p,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new ft).fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/mt.setFromMatrixColumn(t,0).length(),n=1/mt.setFromMatrixColumn(t,1).length(),r=1/mt.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,n=t.z,r=Math.cos(i),o=Math.sin(i),a=Math.cos(s),h=Math.sin(s),l=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*l,i=r*c,s=o*l,n=o*c;e[0]=a*l,e[4]=-a*c,e[8]=h,e[1]=i+s*h,e[5]=t-n*h,e[9]=-o*a,e[2]=n-t*h,e[6]=s+i*h,e[10]=r*a}else if("YXZ"===t.order){const t=a*l,i=a*c,s=h*l,n=h*c;e[0]=t+n*o,e[4]=s*o-i,e[8]=r*h,e[1]=r*c,e[5]=r*l,e[9]=-o,e[2]=i*o-s,e[6]=n+t*o,e[10]=r*a}else if("ZXY"===t.order){const t=a*l,i=a*c,s=h*l,n=h*c;e[0]=t-n*o,e[4]=-r*c,e[8]=s+i*o,e[1]=i+s*o,e[5]=r*l,e[9]=n-t*o,e[2]=-r*h,e[6]=o,e[10]=r*a}else if("ZYX"===t.order){const t=r*l,i=r*c,s=o*l,n=o*c;e[0]=a*l,e[4]=s*h-i,e[8]=t*h+n,e[1]=a*c,e[5]=n*h+t,e[9]=i*h-s,e[2]=-h,e[6]=o*a,e[10]=r*a}else if("YZX"===t.order){const t=r*a,i=r*h,s=o*a,n=o*h;e[0]=a*l,e[4]=n-t*c,e[8]=s*c+i,e[1]=c,e[5]=r*l,e[9]=-o*l,e[2]=-h*l,e[6]=i*c+s,e[10]=t-n*c}else if("XZY"===t.order){const t=r*a,i=r*h,s=o*a,n=o*h;e[0]=a*l,e[4]=-c,e[8]=h*l,e[1]=t*c+n,e[5]=r*l,e[9]=i*c-s,e[2]=s*c-i,e[6]=o*l,e[10]=n*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(yt,t,gt)}lookAt(t,e,i){const s=this.elements;return St.subVectors(t,e),0===St.lengthSq()&&(St.z=1),St.normalize(),vt.crossVectors(i,St),0===vt.lengthSq()&&(1===Math.abs(i.z)?St.x+=1e-4:St.z+=1e-4,St.normalize(),vt.crossVectors(i,St)),vt.normalize(),xt.crossVectors(St,vt),s[0]=vt.x,s[4]=xt.x,s[8]=St.x,s[1]=vt.y,s[5]=xt.y,s[9]=St.y,s[2]=vt.z,s[6]=xt.z,s[10]=St.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[4],a=i[8],h=i[12],l=i[1],c=i[5],u=i[9],d=i[13],f=i[2],m=i[6],p=i[10],y=i[14],g=i[3],v=i[7],x=i[11],S=i[15],b=s[0],w=s[4],M=s[8],z=s[12],_=s[1],A=s[5],P=s[9],O=s[13],T=s[2],V=s[6],E=s[10],$=s[14],C=s[3],I=s[7],N=s[11],F=s[15];return n[0]=r*b+o*_+a*T+h*C,n[4]=r*w+o*A+a*V+h*I,n[8]=r*M+o*P+a*E+h*N,n[12]=r*z+o*O+a*$+h*F,n[1]=l*b+c*_+u*T+d*C,n[5]=l*w+c*A+u*V+d*I,n[9]=l*M+c*P+u*E+d*N,n[13]=l*z+c*O+u*$+d*F,n[2]=f*b+m*_+p*T+y*C,n[6]=f*w+m*A+p*V+y*I,n[10]=f*M+m*P+p*E+y*N,n[14]=f*z+m*O+p*$+y*F,n[3]=g*b+v*_+x*T+S*C,n[7]=g*w+v*A+x*V+S*I,n[11]=g*M+v*P+x*E+S*N,n[15]=g*z+v*O+x*$+S*F,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],n=t[12],r=t[1],o=t[5],a=t[9],h=t[13],l=t[2],c=t[6],u=t[10],d=t[14];return t[3]*(+n*a*c-s*h*c-n*o*u+i*h*u+s*o*d-i*a*d)+t[7]*(+e*a*d-e*h*u+n*r*u-s*r*d+s*h*l-n*a*l)+t[11]*(+e*h*c-e*o*d-n*r*c+i*r*d+n*o*l-i*h*l)+t[15]*(-s*o*l-e*a*c+e*o*u+s*r*c-i*r*u+i*a*l)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return"number"==typeof t?(s[12]=t,s[13]=e,s[14]=i):(s[12]=t.x,s[13]=t.y,s[14]=t.z),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=t[9],u=t[10],d=t[11],f=t[12],m=t[13],p=t[14],y=t[15],g=c*p*h-m*u*h+m*a*d-o*p*d-c*a*y+o*u*y,v=f*u*h-l*p*h-f*a*d+r*p*d+l*a*y-r*u*y,x=l*m*h-f*c*h+f*o*d-r*m*d-l*o*y+r*c*y,S=f*c*a-l*m*a-f*o*u+r*m*u+l*o*p-r*c*p,b=e*g+i*v+s*x+n*S;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/b;return t[0]=g*w,t[1]=(m*u*n-c*p*n-m*s*d+i*p*d+c*s*y-i*u*y)*w,t[2]=(o*p*n-m*a*n+m*s*h-i*p*h-o*s*y+i*a*y)*w,t[3]=(c*a*n-o*u*n-c*s*h+i*u*h+o*s*d-i*a*d)*w,t[4]=v*w,t[5]=(l*p*n-f*u*n+f*s*d-e*p*d-l*s*y+e*u*y)*w,t[6]=(f*a*n-r*p*n-f*s*h+e*p*h+r*s*y-e*a*y)*w,t[7]=(r*u*n-l*a*n+l*s*h-e*u*h-r*s*d+e*a*d)*w,t[8]=x*w,t[9]=(f*c*n-l*m*n-f*i*d+e*m*d+l*i*y-e*c*y)*w,t[10]=(r*m*n-f*o*n+f*i*h-e*m*h-r*i*y+e*o*y)*w,t[11]=(l*o*n-r*c*n-l*i*h+e*c*h+r*i*d-e*o*d)*w,t[12]=S*w,t[13]=(l*m*s-f*c*s+f*i*u-e*m*u-l*i*p+e*c*p)*w,t[14]=(f*o*s-r*m*s-f*i*a+e*m*a+r*i*p-e*o*p)*w,t[15]=(r*c*s-l*o*s+l*i*a-e*c*a-r*i*u+e*o*u)*w,this}scale(t){const e=this.elements,i=t.x,s=t.y,n=t.z;return e[0]*=i,e[4]*=s,e[8]*=n,e[1]*=i,e[5]*=s,e[9]*=n,e[2]*=i,e[6]*=s,e[10]*=n,e[3]*=i,e[7]*=s,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return"number"==typeof t?this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1):this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),n=1-i,r=t.x,o=t.y,a=t.z,h=n*r,l=n*o;return this.set(h*r+i,h*o-s*a,h*a+s*o,0,h*o+s*a,l*o+i,l*a-s*r,0,h*a-s*o,l*a+s*r,n*a*a+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,n,r){return this.set(1,i,n,0,t,1,r,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,n=e._x,r=e._y,o=e._z,a=e._w,h=n+n,l=r+r,c=o+o,u=n*h,d=n*l,f=n*c,m=r*l,p=r*c,y=o*c,g=a*h,v=a*l,x=a*c,S=i.x,b=i.y,w=i.z;return s[0]=(1-(m+y))*S,s[1]=(d+x)*S,s[2]=(f-v)*S,s[3]=0,s[4]=(d-x)*b,s[5]=(1-(u+y))*b,s[6]=(p+g)*b,s[7]=0,s[8]=(f+v)*w,s[9]=(p-g)*w,s[10]=(1-(u+m))*w,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let n=mt.set(s[0],s[1],s[2]).length();const r=mt.set(s[4],s[5],s[6]).length(),o=mt.set(s[8],s[9],s[10]).length();this.determinant()<0&&(n=-n),t.x=s[12],t.y=s[13],t.z=s[14],pt.copy(this);const a=1/n,h=1/r,l=1/o;return pt.elements[0]*=a,pt.elements[1]*=a,pt.elements[2]*=a,pt.elements[4]*=h,pt.elements[5]*=h,pt.elements[6]*=h,pt.elements[8]*=l,pt.elements[9]*=l,pt.elements[10]*=l,e.setFromRotationMatrix(pt),i.x=n,i.y=r,i.z=o,this}makePerspective(t,e,i,s,n,r,o=2e3){const a=this.elements,h=2*n/(e-t),l=2*n/(i-s),c=(e+t)/(e-t),u=(i+s)/(i-s);let d,f;if(o===ut)d=-(r+n)/(r-n),f=-2*r*n/(r-n);else{if(o!==dt)throw new Error("Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-r/(r-n),f=-r*n/(r-n)}return a[0]=h,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=u,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=f,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,i,s,n,r,o=2e3){const a=this.elements,h=1/(e-t),l=1/(i-s),c=1/(r-n),u=(e+t)*h,d=(i+s)*l;let f,m;if(o===ut)f=(r+n)*c,m=-2*c;else{if(o!==dt)throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);f=n*c,m=-1*c}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-u,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-f,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}Object.defineProperty(ft.prototype,"isMatrix4",{value:!0});const mt=new ht,pt=new ft,yt=new ht(0,0,0),gt=new ht(1,1,1),vt=new ht,xt=new ht,St=new ht,bt=new ft,wt=new at;class Mt{constructor(t=0,e=0,i=0,s=Mt.DEFAULT_ORDER){this._x=t,this._y=e,this._z=i,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new Mt(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,n=s[0],r=s[4],o=s[8],a=s[1],h=s[5],l=s[9],c=s[2],u=s[6],d=s[10];switch(e){case"XYZ":this._y=Math.asin(R(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(u,h),this._z=0);break;case"YXZ":this._x=Math.asin(-R(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin(R(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-r,h)):(this._y=0,this._z=Math.atan2(a,n));break;case"ZYX":this._y=Math.asin(-R(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(a,n)):(this._x=0,this._z=Math.atan2(-r,h));break;case"YZX":this._z=Math.asin(R(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-R(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(u,h),this._y=Math.atan2(o,n)):(this._x=Math.atan2(-l,d),this._y=0);break;default:console.warn("../math.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return bt.makeRotationFromQuaternion(t),this.setFromRotationMatrix(bt,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return wt.setFromEuler(this),this.setFromQuaternion(wt,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(t){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Mt.DEFAULT_ORDER="XYZ",Object.defineProperty(Mt.prototype,"isEuler",{value:!0});class zt{constructor(t,e,i,s,n,r,o,a,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,o,a,h)}set(t,e,i,s,n,r,o,a,h){const l=this.elements;return l[0]=t,l[1]=s,l[2]=o,l[3]=e,l[4]=n,l[5]=a,l[6]=i,l[7]=r,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],o=i[3],a=i[6],h=i[1],l=i[4],c=i[7],u=i[2],d=i[5],f=i[8],m=s[0],p=s[3],y=s[6],g=s[1],v=s[4],x=s[7],S=s[2],b=s[5],w=s[8];return n[0]=r*m+o*g+a*S,n[3]=r*p+o*v+a*b,n[6]=r*y+o*x+a*w,n[1]=h*m+l*g+c*S,n[4]=h*p+l*v+c*b,n[7]=h*y+l*x+c*w,n[2]=u*m+d*g+f*S,n[5]=u*p+d*v+f*b,n[8]=u*y+d*x+f*w,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8];return e*r*l-e*o*h-i*n*l+i*o*a+s*n*h-s*r*a}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7],l=t[8],c=l*r-o*h,u=o*a-l*n,d=h*n-r*a,f=e*c+i*u+s*d;if(0===f)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return t[0]=c*m,t[1]=(s*h-l*i)*m,t[2]=(o*i-s*r)*m,t[3]=u*m,t[4]=(l*e-s*a)*m,t[5]=(s*n-o*e)*m,t[6]=d*m,t[7]=(i*a-h*e)*m,t[8]=(r*e-i*n)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,n,r,o){const a=Math.cos(n),h=Math.sin(n);return this.set(i*a,i*h,-i*(a*r+h*o)+r+t,-s*h,s*a,-s*(-h*r+a*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(_t.makeScale(t,e)),this}rotate(t){return this.premultiply(_t.makeRotation(-t)),this}translate(t,e){return this.premultiply(_t.makeTranslation(t,e)),this}makeTranslation(t,e){return"number"==typeof t?this.set(1,0,t,0,1,e,0,0,1):this.set(1,0,t.x,0,1,t.y,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new zt).fromArray(this.elements)}}Object.defineProperty(zt.prototype,"isMatrix3",{value:!0});const _t=new zt,At=new Float32Array(4);class Pt extends at{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Ot=Pt.prototype;Ot.data=At,Ot.offset=0,Object.defineProperties(Pt.prototype,{_x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},_y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},_z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},_w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class Tt{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new Tt(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(R(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*i-r*s+t.x,this.y=n*s+r*i+t.y,this}random(){return this.x=T(),this.y=T(),this}*[Symbol.iterator](){yield this.x,yield this.y}}Object.defineProperty(Tt.prototype,"isVector2",{value:!0});const Vt=new Float32Array(3);class Et extends ht{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const $t=Et.prototype;$t.data=Vt,$t.offset=0,Object.defineProperties(Et.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}}});class Ct{constructor(t=0,e=0,i=0,s=1){this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new Ct(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s+r[12]*n,this.y=r[1]*e+r[5]*i+r[9]*s+r[13]*n,this.z=r[2]*e+r[6]*i+r[10]*s+r[14]*n,this.w=r[3]*e+r[7]*i+r[11]*s+r[15]*n,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,n;const r=.01,o=.1,a=t.elements,h=a[0],l=a[4],c=a[8],u=a[1],d=a[5],f=a[9],m=a[2],p=a[6],y=a[10];if(Math.abs(l-u)<r&&Math.abs(c-m)<r&&Math.abs(f-p)<r){if(Math.abs(l+u)<o&&Math.abs(c+m)<o&&Math.abs(f+p)<o&&Math.abs(h+d+y-3)<o)return this.set(1,0,0,0),this;e=Math.PI;const t=(h+1)/2,a=(d+1)/2,g=(y+1)/2,v=(l+u)/4,x=(c+m)/4,S=(f+p)/4;return t>a&&t>g?t<r?(i=0,s=.707106781,n=.707106781):(i=Math.sqrt(t),s=v/i,n=x/i):a>g?a<r?(i=.707106781,s=0,n=.707106781):(s=Math.sqrt(a),i=v/s,n=S/s):g<r?(i=.707106781,s=.707106781,n=0):(n=Math.sqrt(g),i=x/n,s=S/n),this.set(i,s,n,e),this}let g=Math.sqrt((p-f)*(p-f)+(c-m)*(c-m)+(u-l)*(u-l));return Math.abs(g)<.001&&(g=1),this.x=(p-f)/g,this.y=(c-m)/g,this.z=(u-l)/g,this.w=Math.acos((h+d+y-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}random(){return this.x=T(),this.y=T(),this.z=T(),this.w=T(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}Object.defineProperty(Ct.prototype,"isVector4",{value:!0});const It=new Float32Array(4);class Nt extends Ct{constructor(t,e){super(),this.data=t,this.offset=e}bind(t,e){this.data=t,this.offset=e}}const Ft=Nt.prototype;let Bt;function Ut(t){Bt=t}function Rt(){return Bt}Ft.data=It,Ft.offset=0,Object.defineProperties(Nt.prototype,{x:{get(){return this.data[this.offset]},set(t){this.data[this.offset]=t}},y:{get(){return this.data[this.offset+1]},set(t){this.data[this.offset+1]=t}},z:{get(){return this.data[this.offset+2]},set(t){this.data[this.offset+2]=t}},w:{get(){return this.data[this.offset+3]},set(t){this.data[this.offset+3]=t}}});class Lt{constructor(t,e){this.resolver=t,this.bounce=e,this.type="ApplyCollision",this.tempV=new ht}initialize(t){}update(t,e){const i=this.resolver??Bt;void 0!==i&&i.resolve(t.position,this.tempV)&&t.velocity.reflect(this.tempV).multiplyScalar(this.bounce)}frameUpdate(t){}toJSON(){return{type:this.type,bounce:this.bounce}}static fromJSON(t){return new Lt(void 0,"number"==typeof t.bounce?t.bounce:1)}clone(){return new Lt(this.resolver,this.bounce)}reset(){}}const Dt=t=>({r:t.x,g:t.y,b:t.z,a:t.w}),kt=t=>new Ct(t.r,t.g,t.b,t.a);function qt(t,e){if("number"==typeof t)return t;switch(e){case"Color":return{r:t.x,g:t.y,b:t.z};case"Vector4":return t instanceof Ct?{x:t.x,y:t.y,z:t.z,w:t.w}:{...Jt(t),w:0};default:return Jt(t)}}const Jt=t=>({x:t.x,y:t.y,z:t.z}),Gt=t=>"number"==typeof t?t:0;function Wt(t){return"number"==typeof t?new ht:"r"in t?new ht(t.r,t.g,t.b):new ht(t.x,t.y,t.z)}function jt(t){return"number"==typeof t||"r"in t?new Ct:new Ct(t.x,t.y,t.z,"w"in t?t.w:0)}class Qt extends Error{constructor(t,e=[t]){super(t),this.name="QuarksFormatError",this.problems=e}}let Ht={};const Yt=[];function Xt(t,e){const i=Ht,s=Yt.splice(0);Ht=t;try{return e()}finally{Ht=i,Yt.splice(0,Yt.length,...s)}}function Zt(t,e){Yt.push(t);try{return e()}finally{Yt.pop()}}function Kt(){return Yt.reduce((t,e)=>t&&!e.startsWith("[")?`${t}.${e}`:t+e,"")}const te=t=>{const e=Kt();if(Ht.strict)throw new Qt(e?`${t} (at ${e})`:t);Ht.onWarning?Ht.onWarning(t,e):console.warn(`[quarks] ${t}${e?` (at ${e})`:""}`)},ee=(t,e)=>Array.isArray(t)?new ht(t[0]??e.x,t[1]??e.y,t[2]??e.z):e,ie=(t,e)=>{const i=e?.type;return null==e?`Missing ${t}`:void 0===i?`${t[0].toUpperCase()}${t.slice(1)} without a type`:`Unknown ${t} ${JSON.stringify(i)}`};function se(t,e){if(t===e)return!0;if("object"!=typeof t||"object"!=typeof e||null===t||null===e)return"number"==typeof t&&"number"==typeof e&&Number.isNaN(t)&&Number.isNaN(e);if(Array.isArray(t)!==Array.isArray(e))return!1;const i=new Set([...Object.keys(t),...Object.keys(e)]);for(const s of i)if(!se(t[s],e[s]))return!1;return!0}function ne(t,e){if(null===t||"object"!=typeof t||"string"!=typeof t.type)return t;const i=t=>{let i=!1;try{return{out:Xt({onWarning:()=>i=!0},()=>e(t)),warned:i}}catch{return{out:void 0,warned:!0}}},s=i({type:t.type}).out;if(null==s||"object"!=typeof s)return t;const n={type:t.type};for(const[e,i]of Object.entries(t))"type"===e||void 0===i||se(i,s[e])||(n[e]=i);if(Object.keys(n).length===Object.keys(t).length)return t;const r=i(n);return!r.warned&&se(r.out,t)?n:t}class re{constructor(t){this.value=t,this.type="value"}startGen(t){}genValue(t){return this.value}toJSON(){return{type:"ConstantValue",value:this.value}}static fromJSON(t){return new re(t.value)}clone(){return new re(this.value)}}class oe{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(T())}genValue(t){return-1===this.indexCount&&this.startGen(t),ot.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new oe(t.a,t.b)}clone(){return new oe(this.a,this.b)}}class ae{constructor(t,e,i,s){this.p=[t,e,i,s]}genValue(t){const e=this.p,i=t*t,s=1-t,n=s*s;return e[0]*n*s+e[1]*n*t*3+e[2]*s*i*3+e[3]*i*t}derivativeCoefficients(t){const e=[];for(let i=t,s=i.length-1;s>0;s--){const t=[];for(let e=0;e<s;e++){const n=s*(i[e+1]-i[e]);t.push(n)}e.push(t),i=t}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],i=1-t,s=i*t*2,n=t*t;return i*i*e[0]+s*e[1]+n*e[2]}controlCurve(t,e){this.p[1]=t/3+this.p[0],this.p[2]=this.p[3]-e/3}hull(t){let e=this.p;const i=[e[0],e[1],e[2],e[3]];for(;e.length>1;){const s=[];for(let n=0;n<e.length-1;n++){const r=(1-t)*e[n]+t*e[n+1];i.push(r),s.push(r)}e=s}return i}split(t){const e=this.hull(t);return{left:new ae(e[0],e[4],e[7],e[9]),right:new ae(e[9],e[8],e[6],e[3]),span:e}}clone(){return new ae(this.p[0],this.p[1],this.p[2],this.p[3])}toJSON(){return{p0:this.p[0],p1:this.p[1],p2:this.p[2],p3:this.p[3]}}static fromJSON(t){return new ae(t.p0,t.p1,t.p2,t.p3)}}class he{constructor(){this.functions=new Array}findFunction(t){const e=this.functions,i=e.length-1;if(i<=0)return 0===i&&t>=e[0][1]&&t<=1?0:-1;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;return-1}getStartX(t){return this.functions[t][1]}setStartX(t,e){t>0&&(this.functions[t][1]=e)}getEndX(t){return t+1<this.functions.length?this.functions[t+1][1]:1}setEndX(t,e){t+1<this.functions.length&&(this.functions[t+1][1]=e)}insertFunction(t,e){const i=Math.min(Math.max(t,0),1);let s=this.functions.findIndex(([,t])=>t>i);-1===s&&(s=this.functions.length),this.functions.splice(s,0,[e,i])}removeFunction(t){return this.functions.splice(t,1)[0][0]}getFunction(t){return this.functions[t][0]}setFunction(t,e){this.functions[t][0]=e}get numOfFunctions(){return this.functions.length}}class le extends he{constructor(t=[[new ae(0,1/3,1/3*2,1),0]]){super(),this.table=null,this.tableSignature=null,this.type="function",this.functions=t}refreshTable(){const t=this.functions,e=t.length;if(0===e)return this.table=null,void(this.tableSignature=null);const i=5*e;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));for(let i=0,r=0;i<e;i++,r+=5){const e=t[i][0].p,o=t[i][1];n||(n=s[r]!==e[0]||s[r+1]!==e[1]||s[r+2]!==e[2]||s[r+3]!==e[3]||s[r+4]!==o),n&&(s[r]=e[0],s[r+1]=e[1],s[r+2]=e[2],s[r+3]=e[3],s[r+4]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const r=le.TABLE_SIZE,o=null!==this.table&&this.table.length===r?this.table:new Float32Array(r),a=1/(r-1);for(let t=0;t<r;t++)o[t]=this.genValueExact(t*a);this.table=o}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genValue(t,e=0){const i=this.table;if(null!==i){const t=i.length-1;if(e<=0)return i[0];if(e>=1)return i[t];const s=e*t,n=0|s,r=s-n,o=i[n];return o+(i[n+1]-o)*r}return this.genValueExact(e)}genValueExact(t){const e=this.functions,i=e.length;if(0===i)return 0;const s=this.findFunction(t);if(-1===s)return t<e[0][1]?e[0][0].genValue(0):e[i-1][0].genValue(1);const n=e[s][1],r=(s+1<i?e[s+1][1]:1)-n;return e[s][0].genValue(r>0?(t-n)/r:0)}toSVG(t,e){if(e<1||0===this.functions.length)return"";let i=["M",0,this.functions[0][0].p[0]].join(" ");for(let s=1/e;s<=1;s+=1/e)i=[i,"L",s*t,this.genValueExact(s)].join(" ");return i}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new le(t.functions.map(t=>[ae.fromJSON(t.function),t.start]))}clone(){return new le(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}le.TABLE_SIZE=257;class ce{constructor(t,e){this.curve1=t,this.curve2=e,this.type="function",this.indexCount=-1}startGen(t){this.indexCount=t.length,t.push(T())}refreshTable(){this.curve1.refreshTable(),this.curve2.refreshTable()}genValue(t,e=0){-1===this.indexCount&&this.startGen(t);const i=t[this.indexCount],s=void 0===i?.5:i,n=this.curve1.genValue(t,e);return n+(this.curve2.genValue(t,e)-n)*s}toJSON(){return{type:"RandomBetweenCurves",curve1:this.curve1.toJSON(),curve2:this.curve2.toJSON()}}static fromJSON(t){return new ce(ue(t.curve1,"curve1"),ue(t.curve2,"curve2"))}clone(){return new ce(this.curve1.clone(),this.curve2.clone())}}function ue(t,e){return"PiecewiseBezier"===t?.type&&Array.isArray(t.functions)?le.fromJSON(t):(te(`RandomBetweenCurves ${e}: ${ie("curve",t)}; using a flat 0 curve.`),new le([[new ae(0,0,0,0),0]]))}function de(t){switch(t?.type){case"ConstantValue":return re.fromJSON(t);case"IntervalValue":return oe.fromJSON(t);case"PiecewiseBezier":return le.fromJSON(t);case"RandomBetweenCurves":return ce.fromJSON(t);default:return te(`${ie("value generator",t)}; using 0.`),new re(0)}}const fe=new ht;class me{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,i,s){const n=this.axis,r=n.lengthSq();return 0===r?fe.set(0,0,1):fe.copy(n).multiplyScalar(1/Math.sqrt(r)),e.setFromAxisAngle(fe,this.angle.genValue(t,s)*i)}toJSON(){return{type:"AxisAngle",axis:{x:this.axis.x,y:this.axis.y,z:this.axis.z},angle:this.angle.toJSON()}}static fromJSON(t){return new me(new ht(t.axis.x,t.axis.y,t.axis.z),de(t.angle))}clone(){return new me(this.axis.clone(),this.angle.clone())}}class pe{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(T())}genColor(t,e){return-1===this.indexCount&&this.startGen(t),e.copy(this.a).lerp(this.b,t[this.indexCount])}toJSON(){return{type:"ColorRange",a:Dt(this.a),b:Dt(this.b)}}static fromJSON(t){return new pe(kt(t.a),kt(t.b))}clone(){return new pe(this.a.clone(),this.b.clone())}}class ye{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){const e=this.keys,i=e.length-1;if(i<0||t<e[0][1])return-1;if(t>=e[i][1])return i;if(1===i)return 0;let s=0,n=i;for(;s+1<n;){const i=s+n>>1;if(t<e[i][1])n=i-1;else{if(!(t>this.getEndX(i)))return i;s=i+1}}for(let i=s;i<=n;i++)if(t>=e[i][1]&&t<=this.getEndX(i))return i;return-1}getStartX(t){return this.keys[t][1]}getEndX(t){return t+1<this.keys.length?this.keys[t+1][1]:1}genValue(t,e){const i=this.keys,s=this.findKey(e),n=i.length-1;if("Number"===this.subType){if(-1===s)return i[0][0];if(s>=n)return i[n][0];const t=i[s][1],r=i[s][0],o=i[s+1][1]-t;return(i[s+1][0]-r)*(o>0?(e-t)/o:0)+r}{if(-1===s)return t.copy(i[0][0]);if(s>=n)return t.copy(i[n][0]);const r=i[s][1],o=i[s+1][1]-r;return t.copy(i[s][0]).lerp(i[s+1][0],o>0?(e-r)/o:0)}}toJSON(){return{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:qt(t,this.subType),pos:e}))}}static fromJSON(t){switch(t.subType){case"Number":return new ye(t.keys.map(t=>[Gt(t.value),t.pos]),t.subType);case"Vector4":return new ye(t.keys.map(t=>[jt(t.value),t.pos]),t.subType);default:return new ye(t.keys.map(t=>[Wt(t.value),t.pos]),t.subType)}}clone(){return"Number"===this.subType?new ye(this.keys.map(([t,e])=>[t,e]),this.subType):new ye(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const ge=new Ct;class ve{constructor(t=[[new ht(1,1,1),0],[new ht(1,1,1),1]],e=[[1,0],[1,1]]){this.table=null,this.tableSignature=null,this.type="function",this.color=new ye(t,"Color"),this.alpha=new ye(e,"Number")}refreshTable(){const t=this.color.keys,e=this.alpha.keys,i=4*t.length+2*e.length;let s=this.tableSignature,n=null===s||s.length!==i;n&&(s=new Float64Array(i));let r=0;for(let e=0;e<t.length;e++,r+=4){const i=t[e][0],o=t[e][1];n||(n=s[r]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+3]!==o),n&&(s[r]=i.x,s[r+1]=i.y,s[r+2]=i.z,s[r+3]=o)}for(let t=0;t<e.length;t++,r+=2){const i=e[t][0],o=e[t][1];n||(n=s[r]!==i||s[r+1]!==o),n&&(s[r]=i,s[r+1]=o)}if(!n&&null!==this.table)return;this.tableSignature=s;const o=ve.TABLE_SIZE,a=null!==this.table&&this.table.length===4*o?this.table:new Float32Array(4*o),h=1/(o-1),l=ge;for(let t=0;t<o;t++){this.genColorExact(l,t*h);const e=4*t;a[e]=l.x,a[e+1]=l.y,a[e+2]=l.z,a[e+3]=l.w}this.table=a}sampledTable(){return this.table}clearTable(){this.table=null,this.tableSignature=null}genColor(t,e,i){const s=this.table;if(null!==s){const t=ve.TABLE_SIZE-1;if(i<=0)return e.x=s[0],e.y=s[1],e.z=s[2],e.w=s[3],e;if(i>=1){const i=4*t;return e.x=s[i],e.y=s[i+1],e.z=s[i+2],e.w=s[i+3],e}const n=i*t,r=0|n,o=n-r,a=4*r,h=a+4;return e.x=s[a]+(s[h]-s[a])*o,e.y=s[a+1]+(s[h+1]-s[a+1])*o,e.z=s[a+2]+(s[h+2]-s[a+2])*o,e.w=s[a+3]+(s[h+3]-s[a+3])*o,e}return this.genColorExact(e,i)}genColorExact(t,e){const i=this.color.keys,s=i.length-1,n=this.color.findKey(e);let r,o,a;if(-1===n||n>=s){const t=i[-1===n?0:s][0];r=t.x,o=t.y,a=t.z}else{const t=i[n][0],s=i[n+1][0],h=i[n][1],l=i[n+1][1]-h,c=l>0?(e-h)/l:0;r=t.x+(s.x-t.x)*c,o=t.y+(s.y-t.y)*c,a=t.z+(s.z-t.z)*c}const h=this.alpha.keys,l=h.length-1,c=this.alpha.findKey(e);let u;if(-1===c||c>=l)u=h[-1===c?0:l][0];else{const t=h[c][1],i=h[c][0],s=h[c+1][1]-t;u=i+(h[c+1][0]-i)*(s>0?(e-t)/s:0)}return t.x=r,t.y=o,t.z=a,t.w=u,t}toJSON(){return{type:"Gradient",color:this.color.toJSON(),alpha:this.alpha.toJSON()}}static fromJSON(t){if(t.functions){const e=t.functions.map(({function:t,start:e})=>[pe.fromJSON(t),e]),i=e.map(([t,e])=>[t.a,e]);return e.length>0&&i.push([e[e.length-1][0].b,1]),new ve(i.map(([t,e])=>[new ht(t.x,t.y,t.z),e]),i.map(([t,e])=>[t.w,e]))}{const e=new ve;return t.alpha?e.alpha=ye.fromJSON(t.alpha):te("Gradient has no alpha keys; it is opaque."),t.color?e.color=ye.fromJSON(t.color):te("Gradient has no color keys; it is white."),e}}clone(){const t=new ve;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}ve.TABLE_SIZE=257;class xe{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const i=T();return e.copy(this.a).lerp(this.b,i)}toJSON(){return{type:"RandomColor",a:Dt(this.a),b:Dt(this.b)}}static fromJSON(t){return new xe(kt(t.a),kt(t.b))}clone(){return new xe(this.a.clone(),this.b.clone())}}const Se=new Ct;class be{constructor(t,e){this.indexCount=-1,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(T())}genColor(t,e,i){return-1===this.indexCount&&this.startGen(t),this.gradient1.genColor(t,e,i),this.gradient2.genColor(t,Se,i),e.lerp(Se,t[this.indexCount])}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new be(ve.fromJSON(t.gradient1),ve.fromJSON(t.gradient2))}clone(){return new be(this.gradient1.clone(),this.gradient2.clone())}}class we{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:Dt(this.color)}}static fromJSON(t){return new we(kt(t.color))}clone(){return new we(this.color.clone())}}function Me(t){switch(t?.type){case"ConstantColor":return we.fromJSON(t);case"ColorRange":return pe.fromJSON(t);case"RandomColor":return xe.fromJSON(t);case"Gradient":return ve.fromJSON(t);case"RandomColorBetweenGradient":return be.fromJSON(t);default:return te(`${ie("colour generator",t)}; using white.`),new we(new Ct(1,1,1,1))}}class ze{get eular(){return this.euler}set eular(t){this.euler=t}constructor(t,e,i,s){this.angleX=t,this.angleY=e,this.angleZ=i,this.type="rotation",this.euler=new Mt(0,0,0,s)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,i,s){return this.euler.set(this.angleX.genValue(t,s)*i,this.angleY.genValue(t,s)*i,this.angleZ.genValue(t,s)*i),e.setFromEuler(this.euler)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.euler.order}}static fromJSON(t){return new ze(de(t.angleX),de(t.angleY),de(t.angleZ),t.eulerOrder)}clone(){return new ze(this.angleX.clone(),this.angleY.clone(),this.angleZ.clone(),this.euler.order)}}class _e{constructor(){this.indexCount=-1,this.type="rotation"}startGen(t){let e,i,s,n,r,o;this.indexCount=t.length;do{e=2*T()-1,i=2*T()-1,s=e*e+i*i}while(s>1);do{n=2*T()-1,r=2*T()-1,o=n*n+r*r}while(o>1);const a=Math.sqrt((1-s)/o);t.push(e,i,a*n,a*r)}genValue(t,e,i,s){-1===this.indexCount&&this.startGen(t);const n=this.indexCount;return e.set(t[n],t[n+1],t[n+2],t[n+3]),e}toJSON(){return{type:"RandomQuat"}}static fromJSON(t){return new _e}clone(){return new _e}}function Ae(t){switch(t?.type){case"AxisAngle":return me.fromJSON(t);case"Euler":return ze.fromJSON(t);case"RandomQuat":return _e.fromJSON(t);default:return te(`${ie("rotation generator",t)}; using a random rotation.`),new _e}}class Pe{constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,i){return e.set(this.x.genValue(t,i),this.y.genValue(t,i),this.z.genValue(t,i))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new Pe(de(t.x),de(t.y),de(t.z))}clone(){return new Pe(this.x.clone(),this.y.clone(),this.z.clone())}}function Oe(t){return"Vector3Function"===t?.type?Pe.fromJSON(t):(te(`${ie("vector generator",t)}; using a zero vector.`),new Pe(new re(0),new re(0),new re(0)))}function Te(t){switch(t?.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":case"RandomBetweenCurves":return de(t);case"AxisAngle":case"RandomQuat":case"Euler":return Ae(t);case"Vector3Function":return Oe(t);default:return te(`${ie("generator",t)}; using 0.`),new re(0)}}const Ve=[new ht,new ht,new ht],Ee=new ft,$e=new ht(1,0,0),Ce=new ht(0,1,0),Ie=[!1,!1,!1];function Ne(t,e){return"world"===t||"local"===t?t:e}function Fe(t){return 0===t?0:1/t}class Be{constructor(){this.position=new ht,this.quaternion=new at,this.scale=new ht(1,1,1),this.quaternionInverse=new at,this.scaleInverse=new ht(1,1,1)}refresh(t){const e=t.emitter.matrixWorld;e.decompose(this.position,this.quaternion,this.scale),0!==this.scale.x&&0!==this.scale.y&&0!==this.scale.z||function(t,e){t.extractBasis(Ve[0],Ve[1],Ve[2]);let i=0;for(let t=0;t<3;t++)Ie[t]=Ve[t].lengthSq()>0,Ie[t]&&(Ve[t].normalize(),i++);if(0===i)return e.set(0,0,0,1);if(1===i){const t=Ie.indexOf(!0),e=(t+1)%3,i=Ve[t],s=Math.abs(i.x)<.9?$e:Ce;Ve[e].crossVectors(i,s).normalize(),Ie[e]=!0}const s=Ie.indexOf(!1);Ve[s].crossVectors(Ve[(s+1)%3],Ve[(s+2)%3]).normalize(),e.setFromRotationMatrix(Ee.makeBasis(Ve[0],Ve[1],Ve[2]))}(e,this.quaternion),this.quaternionInverse.copy(this.quaternion).invert(),this.scaleInverse.set(Fe(this.scale.x),Fe(this.scale.y),Fe(this.scale.z))}toSimulation(t,e,i){return i&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion):i||"world"!==e||t.applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}fromSimulation(t,e,i){return i&&"local"===e?t.applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse):i||"world"!==e||t.multiply(this.scale).applyQuaternion(this.quaternion),t}pointToSimulation(t,e,i){return i&&"local"===e?t.multiply(this.scale).applyQuaternion(this.quaternion).add(this.position):i||"world"!==e||t.sub(this.position).applyQuaternion(this.quaternionInverse).multiply(this.scaleInverse),t}}class Ue{constructor(t,e,i="world"){this.direction=t,this.magnitude=e,this.space=i,this.type="ApplyForce",this._frame=new Be,this._direction=new ht,this._direction.copy(t)}initialize(t,e){this.ps=e,this.magnitude.startGen(t.memory)}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const i=this.magnitude.genValue(t.memory)*this._step(e),s=this._direction,n=t.velocity;n.x+=s.x*i,n.y+=s.y*i,n.z+=s.z*i}updateAll(t,e,i){const s=this.magnitude,n=this._direction,r=this._step(i),o=s instanceof re,a=o?s.value*r:0;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const h=o?a:s.genValue(e.memory)*r,l=e.velocity;l.x+=n.x*h,l.y+=n.y*h,l.z+=n.z*h}}frameUpdate(t){this._direction.copy(this.direction),void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&(this._frame.refresh(this.ps),this._frame.toSimulation(this._direction,this.space,this.ps.worldSpace))}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new Ue(ee(t.direction,new ht(0,0,0)),de(t.magnitude??t.force),Ne(t.space,"world"))}clone(){return new Ue(this.direction.clone(),this.magnitude.clone(),this.space)}reset(){}}class Re{constructor(t=0,e=0,i=new ht){this.scaleX=t,this.scaleY=e,this.position=i,this.locations=[]}transform(t,e){const i=this.locations.length;if(0===i)return;const s=this.locations[e%i];t.x=s.x*this.scaleX+this.position.x,t.y=s.y*this.scaleY+this.position.y,t.z=this.position.z}static fromJSON(t){const e=t.position,i=Array.isArray(e)?new ht(e[0],e[1],e[2]):new ht(e?.x??0,e?.y??0,e?.z??0),s=new Re(t.scaleX??0,t.scaleY??0,i);return s.locations=(t.locations??[]).map(t=>new Tt(t.x,t.y)),s}clone(){const t=new Re(this.scaleX,this.scaleY,this.position.clone());return t.locations=this.locations.map(t=>t.clone()),t}toJSON(){return{type:"TextureSequencer",scaleX:this.scaleX,scaleY:this.scaleY,position:[this.position.x,this.position.y,this.position.z],locations:this.locations.map(t=>({x:t.x,y:t.y}))}}fromImage(t,e){const i=document.createElement("canvas");i.width=t.width,i.height=t.height;const s=i.getContext("2d");if(!s)return;s.drawImage(t,0,0);const n=s.getImageData(0,0,i.width,i.height,{colorSpace:"srgb"});i.remove(),this.locations.length=0;for(let t=0;t<n.height;t++)for(let i=0;i<n.width;i++)n.data[4*(t*n.width+i)+3]>e&&this.locations.push(new Tt(i,n.height-t))}}function Le(t){switch(t?.type){case void 0:return null==t?void te(`${ie("sequencer",t)}; skipping it.`):Re.fromJSON(t);case"TextureSequencer":return Re.fromJSON(t);default:return void te(`${ie("sequencer",t)}; skipping it.`)}}class De{constructor(t){this.type="ApplySequences",this.sequencers=[],this.time=0,this.index=0,this.pCount=0,this.tempV=new ht,this.states=new WeakMap,this.delay=t}initialize(t){const e=this.states.get(t);e?(e.id=this.pCount,e.inMotion=!1):this.states.set(t,{id:this.pCount,begin:new ht,dst:new ht,inMotion:!1}),this.pCount++}reset(){this.time=0,this.index=0,this.pCount=0}update(t,e){const i=this.sequencers[this.index];if(void 0===i)return;const s=this.states.get(t);if(void 0===s)return;const[n,r]=i,o=s.id*this.delay;if(this.time>=n.a+o&&this.time<=n.b+o){s.inMotion||(s.inMotion=!0,s.begin.copy(t.position),r.transform(s.dst,s.id));const e=n.b-n.a;t.position.lerpVectors(s.begin,s.dst,De.BEZIER.genValue(e>0?(this.time-n.a-o)/e:1))}else this.time>n.b+o&&(s.inMotion=!1)}frameUpdate(t){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=t}appendSequencer(t,e){this.sequencers.push([t,e])}toJSON(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(([t,e])=>({range:t.toJSON(),sequencer:e.toJSON()}))}}static fromJSON(t){const e=new De("number"==typeof t.delay?t.delay:0);return(Array.isArray(t.sequencers)?t.sequencers:[]).forEach(t=>{const i=Le(t.sequencer);void 0!==i&&e.sequencers.push([de(t.range),i])}),e}clone(){const t=new De(this.delay);return t.sequencers=this.sequencers.map(t=>[t[0].clone(),t[1].clone()]),t}}De.BEZIER=new ae(0,0,1,1);class ke{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new ht,this._q=new at,this.memory=[]}initialize(t){const e=t.velocity.length();0!=e&&(t.velocity.normalize(),0===t.velocity.x&&0===t.velocity.y?this._temp.set(0,t.velocity.z,0):this._temp.set(-t.velocity.y,t.velocity.x,0),this.memory.length=0,this.angle.startGen(this.memory),this._q.setFromAxisAngle(this._temp.normalize(),this.angle.genValue(this.memory)),this._temp.copy(t.velocity),t.velocity.applyQuaternion(this._q),this._q.setFromAxisAngle(this._temp,T()*Math.PI*2),t.velocity.applyQuaternion(this._q),t.velocity.setLength(e))}update(t,e){}frameUpdate(t){}toJSON(){return{type:this.type,angle:this.angle.toJSON()}}static fromJSON(t){return new ke(de(t.angle))}clone(){return new ke(this.angle.clone())}reset(){this.memory.length=0}}function qe(t,e){const i=t.velocity.length()*t.speedModifier,s=e.b-e.a;if(0===s)return i>=e.a?1:0;const n=(i-e.a)/s;return n<0?0:n>1?1:n}class Je{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=qe(t,this.speedRange);this.color.genColor(t.memory,t.color,i),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new Je(Me(t.color),t.speedRange?oe.fromJSON(t.speedRange):new oe(0,1))}clone(){return new Je(this.color.clone(),this.speedRange.clone())}reset(){}}class Ge{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=t.color,s=t.startColor;this.color.genColor(t.memory,i,t.age/t.life),i.x*=s.x,i.y*=s.y,i.z*=s.z,i.w*=s.w}updateAll(t,e,i){const s=this.color;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=e.color,r=e.startColor;s.genColor(e.memory,n,e.age/e.life),n.x*=r.x,n.y*=r.y,n.z*=r.z,n.w*=r.w}}frameUpdate(t){this.color.refreshTable?.()}toJSON(){return{type:this.type,color:this.color.toJSON()}}static fromJSON(t){return new Ge(Me(t.color))}clone(){return new Ge(this.color.clone())}reset(){}}class We{constructor(t=64){this.previousVelocity=We.EMPTY,this.rotationQuaternion=We.EMPTY,this.angularVelocityQuaternion=We.EMPTY,this.memory=new Float64Array(0),this.memoryStride=0,this.capacity=Math.max(1,t),this.position=new Float32Array(3*this.capacity),this.previousPosition=new Float32Array(3*this.capacity),this.previousSize=new Float32Array(3*this.capacity),this.previousColor=new Float32Array(4*this.capacity),this.velocity=new Float32Array(3*this.capacity),this.size=new Float32Array(3*this.capacity),this.startSize=new Float32Array(3*this.capacity),this.color=new Float32Array(4*this.capacity),this.startColor=new Float32Array(4*this.capacity),this.scalars=new Float64Array(this.capacity*We.SCALAR_STRIDE),this.rotation=new Float32Array(this.capacity),this.angularVelocity=new Float32Array(this.capacity),this.uvTile=new Float32Array(this.capacity),this.startSpeed=new Float32Array(this.capacity),this.flip=new Uint8Array(this.capacity)}ensureCapacity(t){if(t<=this.capacity)return!1;let e=this.capacity;for(;e<t;)e*=2;this.position=We.grow(this.position,3*e),this.previousPosition=We.grow(this.previousPosition,3*e);const i=this.previousSize===this.size,s=this.previousColor===this.color;if(i||(this.previousSize=We.grow(this.previousSize,3*e)),this.previousVelocity.length>0&&(this.previousVelocity=We.grow(this.previousVelocity,3*e)),this.rotationQuaternion.length>0){const t=this.rotationQuaternion.length;this.rotationQuaternion=We.grow(this.rotationQuaternion,4*e),this.angularVelocityQuaternion=We.grow(this.angularVelocityQuaternion,4*e);for(let i=t+3;i<4*e;i+=4)this.rotationQuaternion[i]=1,this.angularVelocityQuaternion[i]=1}if(s||(this.previousColor=We.grow(this.previousColor,4*e)),this.velocity=We.grow(this.velocity,3*e),this.size=We.grow(this.size,3*e),this.startSize=We.grow(this.startSize,3*e),this.color=We.grow(this.color,4*e),i&&(this.previousSize=this.size),s&&(this.previousColor=this.color),this.startColor=We.grow(this.startColor,4*e),this.scalars=We.growDouble(this.scalars,e*We.SCALAR_STRIDE),this.memoryStride>0){const t=new Float64Array(e*this.memoryStride);t.fill(NaN),t.set(this.memory),this.memory=t}this.rotation=We.grow(this.rotation,e),this.angularVelocity=We.grow(this.angularVelocity,e),this.uvTile=We.grow(this.uvTile,e),this.startSpeed=We.grow(this.startSpeed,e);const n=new Uint8Array(e);return n.set(this.flip),this.flip=n,this.capacity=e,!0}keepPreviousVelocity(){return!(this.previousVelocity.length>=3*this.capacity)&&(this.previousVelocity=new Float32Array(3*this.capacity),!0)}recordMemory(t,e){const i=e.length;let s=this.memoryStride;if(i>s||this.memory.length<this.capacity*s){s=Math.max(s,i);const t=new Float64Array(this.capacity*s);t.fill(NaN);const e=this.memoryStride,n=this.memory,r=e>0?n.length/e:0;for(let i=0,o=0,a=0;i<r;i++,o+=e,a+=s)for(let i=0;i<e;i++)t[a+i]=n[o+i];this.memory=t,this.memoryStride=s}const n=t*s;for(let t=0;t<s;t++){const s=t<i?e[t]:void 0;this.memory[n+t]="number"==typeof s?s:NaN}}useSizeSnapshot(t){t?this.previousSize===this.size&&(this.previousSize=new Float32Array(this.size)):this.previousSize=this.size}useColorSnapshot(t){t?this.previousColor===this.color&&(this.previousColor=new Float32Array(this.color)):this.previousColor=this.color}ensureQuaternionColumns(){if(this.rotationQuaternion.length>=4*this.capacity)return!1;this.rotationQuaternion=new Float32Array(4*this.capacity),this.angularVelocityQuaternion=new Float32Array(4*this.capacity);for(let t=3;t<this.rotationQuaternion.length;t+=4)this.rotationQuaternion[t]=1,this.angularVelocityQuaternion[t]=1;return!0}swapRows(t,e){if(t===e)return;const i=3*t,s=3*e;We.swap3(this.position,i,s),We.swap3(this.previousPosition,i,s),this.previousSize!==this.size&&We.swap3(this.previousSize,i,s),this.previousVelocity.length>0&&We.swap3(this.previousVelocity,i,s),We.swap3(this.velocity,i,s),We.swap3(this.size,i,s),We.swap3(this.startSize,i,s);const n=4*t,r=4*e;We.swap4(this.color,n,r),this.previousColor!==this.color&&We.swap4(this.previousColor,n,r),We.swap4(this.startColor,n,r),this.rotationQuaternion.length>0&&(We.swap4(this.rotationQuaternion,n,r),We.swap4(this.angularVelocityQuaternion,n,r)),We.swap3(this.scalars,t*We.SCALAR_STRIDE,e*We.SCALAR_STRIDE);const o=this.memoryStride;if(o>0){const i=this.memory;for(let s=0,n=t*o,r=e*o;s<o;s++,n++,r++){const t=i[n];i[n]=i[r],i[r]=t}}We.swap1(this.rotation,t,e),We.swap1(this.angularVelocity,t,e),We.swap1(this.uvTile,t,e),We.swap1(this.startSpeed,t,e),We.swap1(this.flip,t,e)}static swap1(t,e,i){const s=t[e];t[e]=t[i],t[i]=s}static growDouble(t,e){const i=new Float64Array(e);return i.set(t),i}static swap3(t,e,i){let s=t[e];t[e]=t[i],t[i]=s,s=t[e+1],t[e+1]=t[i+1],t[i+1]=s,s=t[e+2],t[e+2]=t[i+2],t[i+2]=s}static swap4(t,e,i){We.swap3(t,e,i);const s=t[e+3];t[e+3]=t[i+3],t[i+3]=s}static grow(t,e){const i=new Float32Array(e);return i.set(t),i}}We.EMPTY=new Float32Array(0),We.SCALAR_STRIDE=3,We.AGE=0,We.LIFE=1,We.SPEED_MODIFIER=2;class je{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return null!==this.prev}hasNext(){return null!==this.next}}class Qe{constructor(){this.length=0,this.head=this.tail=null}isEmpty(){return null===this.head}clear(){this.length=0,this.head=this.tail=null}front(){return null===this.head?null:this.head.data}back(){return null===this.tail?null:this.tail.data}dequeue(){if(this.head){const t=this.head.data;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,t}}pop(){if(this.tail){const t=this.tail.data;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,t}}queue(t){const e=new je(t);this.tail||(this.tail=e),this.head&&(this.head.prev=e,e.next=this.head),this.head=e,this.length++}push(t){const e=new je(t);this.head||(this.head=e),this.tail&&(this.tail.next=e,e.prev=this.tail),this.tail=e,this.length++}insertBefore(t,e){const i=new je(e);i.next=t,i.prev=t.prev,null!==i.prev&&(i.prev.next=i),i.next.prev=i,t==this.head&&(this.head=i),this.length++}remove(t){if(null===this.head||null===this.tail)return;let e=this.head;for(t===this.head.data&&(this.head=this.head.next),t===this.tail.data&&(this.tail=this.tail.prev);null!==e.next&&e.data!==t;)e=e.next;e.data===t&&(null!==e.prev&&(e.prev.next=e.next),null!==e.next&&(e.next.prev=e.prev),this.length--)}*values(){let t=this.head;for(;null!==t;)yield t.data,t=t.next}}class He{constructor(){this.position=new ht,this.velocity=new ht,this.age=0,this.life=1,this.size=new ht,this.rotation=0,this.color=new Ct(1,1,1,1),this.uvTile=0,this.memory=[]}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.position.set(0,0,0),this.velocity.set(0,0,0),this.age=0,this.life=1,this.size.set(1,1,1),this.rotation=0,this.color.set(1,1,1,1),this.uvTile=0}}class Ye{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get angularVelocity(){const t=this.angularVelocityQuaternion;return void 0!==t?t:this.store.angularVelocity[this.storeIndex]}set angularVelocity(t){if("number"==typeof t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=t;else if(void 0===t)this.angularVelocityQuaternion=void 0,this.store.angularVelocity[this.storeIndex]=0;else{let e=this.angularVelocityQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new Pt(this.store.angularVelocityQuaternion,4*this.storeIndex),this.angularVelocityQuaternion=e),e!==t&&e.copy(t)}}get rotation(){const t=this.rotationQuaternion;return void 0!==t?t:this.store.rotation[this.storeIndex]}set rotation(t){if("number"==typeof t)this.rotationQuaternion=void 0,this.store.rotation[this.storeIndex]=t;else{let e=this.rotationQuaternion;void 0===e&&(this.store.ensureQuaternionColumns(),e=new Pt(this.store.rotationQuaternion,4*this.storeIndex),this.rotationQuaternion=e),e!==t&&e.copy(t)}}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}get flip(){return this.store.flip[this.storeIndex]}set flip(t){this.store.flip[this.storeIndex]=t}constructor(t=new We(1),e=0){this.rotationQuaternion=void 0,this.angularVelocityQuaternion=void 0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new Et(t.position,i),this.previousPosition=new Et(t.previousPosition,i),this.previousVelocity=new Et(t.previousVelocity,i),this.velocity=new Et(t.velocity,i),this.size=new Et(t.size,i),this.startSize=new Et(t.startSize,i),this.color=new Nt(t.color,s),this.startColor=new Nt(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*We.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,i=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,i),this.startColor.bind(t.startColor,i),this.rotationQuaternion?.bind(t.rotationQuaternion,i),this.angularVelocityQuaternion?.bind(t.angularVelocityQuaternion,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*We.SCALAR_STRIDE}get died(){return this.age>=this.life}reset(){this.memory.length=0}}const Xe=new Float32Array(0);class Ze{constructor(t,e,i){this.position=t,this.size=e,this.color=i}}class Ke{get startSpeed(){return this.store.startSpeed[this.storeIndex]}set startSpeed(t){this.store.startSpeed[this.storeIndex]=t}get age(){return this.scalars[this.scalarOffset]}set age(t){this.scalars[this.scalarOffset]=t}get life(){return this.scalars[this.scalarOffset+1]}set life(t){this.scalars[this.scalarOffset+1]=t}get speedModifier(){return this.scalars[this.scalarOffset+2]}set speedModifier(t){this.scalars[this.scalarOffset+2]=t}get previous(){return this._previous??(this._previous=new Qe)}set previous(t){this._previous=t}get uvTile(){return this.store.uvTile[this.storeIndex]}set uvTile(t){this.store.uvTile[this.storeIndex]=t}constructor(t=new We(1),e=0){this.length=30,this._previous=void 0,this.historyPositions=Xe,this.historySizes=Xe,this.historyBaseSizes=Xe,this.headWidthScale=1,this.historyColors=Xe,this.historySides=Xe,this.historyAges=Xe,this.historyDistances=Xe,this.historyCapacity=0,this.historyHead=0,this.historyCount=0,this.memory=[],this.store=t,this.storeIndex=e;const i=3*e,s=4*e;this.position=new Et(t.position,i),this.previousPosition=new Et(t.previousPosition,i),this.previousVelocity=new Et(t.previousVelocity,i),this.velocity=new Et(t.velocity,i),this.size=new Et(t.size,i),this.startSize=new Et(t.startSize,i),this.color=new Nt(t.color,s),this.startColor=new Nt(t.startColor,s),this.scalars=t.scalars,this.scalarOffset=e*We.SCALAR_STRIDE,this.size.set(1,1,1),this.startSize.set(1,1,1),this.life=1,this.speedModifier=1}setStoreIndex(t){this.storeIndex=t,this.rebind()}rebind(){const t=this.store,e=3*this.storeIndex,i=4*this.storeIndex;this.position.bind(t.position,e),this.previousPosition.bind(t.previousPosition,e),this.previousVelocity.bind(t.previousVelocity,e),this.velocity.bind(t.velocity,e),this.size.bind(t.size,e),this.startSize.bind(t.startSize,e),this.color.bind(t.color,i),this.startColor.bind(t.startColor,i),this.scalars=t.scalars,this.scalarOffset=this.storeIndex*We.SCALAR_STRIDE}ensureHistoryCapacity(t){this.historyCapacity!==t&&(this.historyCapacity=t,this.historySizes.length<t&&(this.historyPositions=new Float32Array(3*t),this.historySizes=new Float32Array(t),this.historyBaseSizes=new Float32Array(t),this.historyColors=new Float32Array(4*t),this.historyAges=new Float32Array(t),this.historyDistances=new Float32Array(t),this.historySides.length>0&&(this.historySides=new Float32Array(3*t))),this.historyHead=0,this.historyCount=0)}ensureSideHistory(){this.historySides.length<3*this.historyCapacity&&(this.historySides=new Float32Array(3*this.historyCapacity))}resetHistory(){this.historyHead=0,this.historyCount=0}getHistoryIndex(t){const e=this.historyCapacity;return(this.historyHead-this.historyCount+e+t)%e}update(t=!1,e=!0){0===this.historyCapacity&&this.ensureHistoryCapacity(Math.max(1,Math.ceil(this.length)));const i=this.historyCapacity,s=this.store,n=this.storeIndex,r=n*We.SCALAR_STRIDE,o=s.scalars[r+We.AGE];if(o>=s.scalars[r+We.LIFE])return void this.dropOldest();const a=t&&this.historyCount>0,h=a?(this.historyHead+i-1)%i:this.historyHead,l=3*h,c=this.historyPositions,u=s.position,d=3*n;c[l]=u[d],c[l+1]=u[d+1],c[l+2]=u[d+2];const f=s.size[d];this.historyBaseSizes[h]=f,this.historySizes[h]=f*this.headWidthScale;const m=4*h,p=this.historyColors,y=s.color,g=4*n;p[m]=y[g],p[m+1]=y[g+1],p[m+2]=y[g+2],p[m+3]=y[g+3],this.historyAges[h]=o,a||(this.historyHead=(h+1)%i,this.historyCount<i&&this.historyCount++),e&&this.measureHeadDistance()}measureHeadDistance(){const t=this.historyCount;if(0===t)return;const e=this.historyCapacity,i=(this.historyHead+e-1)%e;if(1===t)return void(this.historyDistances[i]=0);const s=(i+e-1)%e,n=this.historyPositions,r=n[3*i]-n[3*s],o=n[3*i+1]-n[3*s+1],a=n[3*i+2]-n[3*s+2];this.historyDistances[i]=this.historyDistances[s]+Math.sqrt(r*r+o*o+a*a)}dropOldest(){this.historyCount>0&&this.historyCount--}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.headWidthScale=1,this.resetHistory()}}function ti(t,e){return Math.floor(T()*(e-t))+t}function ei(t,e){const i=Number.isNaN(t)?0:1-ot.clamp(t,0,1),s=ot.lerp(Math.pow(i,e),1,T());return 2===e?Math.sqrt(s):Math.cbrt(s)}const ii=new ht(0,1,0),si=new ht(0,0,0),ni=new ht(1,1,1),ri=new ht(0,0,1),oi=1e-6;var ai;!function(t){t[t.Death=0]="Death",t[t.Birth=1]="Birth",t[t.Frame=2]="Frame"}(ai||(ai={}));const hi={color:1,size:2,rotation:4,lifetime:8};function li(t){let e=0;for(const i of t)e|=hi[i]??0;return e}class ci{constructor(t,e,i,s=ai.Frame,n=1,r=[]){this.particleSystem=t,this.useVelocityAsBasis=e,this.subParticleSystem=i,this.mode=s,this.emitProbability=n,this.inherit=r,this.type="EmitSubParticleSystem",this.q_=new at,this.v_=new ht,this.v2_=new ht,this.v3_=new ht,this.subEmissions=new Array,this.spareEmissions=new Array;const o=this.target;o&&(o.onlyUsedByOther=!0)}initialize(t){}update(t,e){(this.mode===ai.Frame||this.mode===ai.Birth&&0===t.age||this.mode===ai.Death&&t.age+e>=t.life&&!this.particleSystem.ringBufferActive)&&this.emit(t,e)}hasPendingEmission(){const t=this.target;if(void 0===t)return!1;for(let e=0;e<this.subEmissions.length;e++)if(t.hasPendingEmission(this.subEmissions[e]))return!0;return!1}get targetSystem(){return this.target}get target(){const t=this.subParticleSystem;if(null===t||"object"!=typeof t)return;const e=t.system;return e?.isDisposed?void 0:e}emit(t,e){if(!this.target)return;if(T()>this.emitProbability)return;const i=this.spareEmissions.pop(),s=void 0!==i?i:{burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:new ft,travelDistance:0,particle:void 0,serial:void 0,previousWorldPos:void 0};s.burstParticleCount=0,s.burstParticleIndex=0,s.isBursting=!1,s.burstIndex=0,s.burstWaveIndex=0,s.time=0,s.waitEmiting=0,s.travelDistance=0,this.mode===ai.Death?(s.particle=ci.copyInto(s.ghost??(s.ghost=new Ye),t),s.serial=void 0):(s.particle=t,s.serial=t.serial),s.inherit=li(this.inherit),this.mode===ai.Death&&(s.inherit&=~hi.lifetime),s.previousWorldPos=void 0,this.setMatrixFromParticle(s.matrix,t),this.subEmissions.push(s)}frameUpdate(t){const e=this.target;if(e)for(let i=0;i<this.subEmissions.length;i++)if(this.subEmissions[i].time>=e.duration){const t=this.subEmissions[i];t.particle=void 0,t.matrix=new ft,this.spareEmissions.push(t),this.subEmissions[i]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,i--}else{const s=this.subEmissions[i],n=s.particle;void 0!==n&&n===s.ghost||(void 0!==n&&n.age<n.life&&n.serial===s.serial?this.setMatrixFromParticle(s.matrix,n):s.particle=void 0),e.emit(t,s,s.matrix)}else this.clearEmissions()}toJSON(){return{type:this.type,subParticleSystem:"string"==typeof this.subParticleSystem?this.subParticleSystem:this.subParticleSystem?this.subParticleSystem.uuid:"",useVelocityAsBasis:this.useVelocityAsBasis,mode:this.mode,emitProbability:this.emitProbability,...this.inherit.length>0?{inherit:this.inherit.slice()}:{}}}static fromJSON(t,e){return new ci(e,Boolean(t.useVelocityAsBasis),t.subParticleSystem,t.mode,t.emitProbability,ci.validInherit(t.inherit))}clone(){return new ci(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability,this.inherit.slice())}reset(){this.clearEmissions()}clearEmissions(){for(const t of this.subEmissions)t.particle=void 0,this.spareEmissions.push(t);this.subEmissions.length=0}static copyInto(t,e){return t.position.copy(e.position),t.velocity.copy(e.velocity),t.color.copy(e.color),t.size.copy(e.size),t.rotation=e.rotation??0,t.age=e.age,t.life=e.life,t}static validInherit(t){return Array.isArray(t)?t.filter(t=>t in hi):[]}setMatrixFromParticle(t,e){let i;if(void 0===e.rotation||this.useVelocityAsBasis){const i=e.position,s=this.v3_.copy(e.velocity),n=s.length(),r=this.v_,o=this.v2_;if(n<oi)r.set(1,0,0),o.set(0,1,0),s.set(0,0,1);else if(s.divideScalar(n),Math.abs(s.x)<oi&&Math.abs(s.y)<oi){const t=s.z>0?1:-1;r.set(1,0,0),o.set(0,t,0),s.set(0,0,t)}else r.copy(ri).cross(s).normalize(),o.copy(s).cross(r);t.set(r.x,o.x,s.x,i.x,r.y,o.y,s.y,i.y,r.z,o.z,s.z,i.z,0,0,0,1)}else e.rotation instanceof at?i=e.rotation:(this.q_.setFromAxisAngle(ri,e.rotation),i=this.q_),t.compose(e.position,i,ni);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}class ui{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,i,s="world"){this.x=t,this.y=e,this.z=i,this.space=s,this.type="ForceOverLife",this._temp=new ht,this._frame=new Be}_step(t){const e=this.ps;return(void 0===e||e.worldSpace)&&"world"===this.space?t*(e?.motionScale??1):t}update(t,e){const i=t.age/t.life;this._temp.set(this.x.genValue(t.memory,i),this.y.genValue(t.memory,i),this.z.genValue(t.memory,i));const s=void 0===this.ps||this.ps.worldSpace;this._frame.toSimulation(this._temp,this.space,s),t.velocity.addScaledVector(this._temp,this._step(e))}updateAll(t,e,i){const s=this._temp,n=this.x,r=this.y,o=this.z,a=this._frame,h=this.space,l=void 0===this.ps||this.ps.worldSpace,c=l!==("world"===h),u=this._step(i);for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const d=e.memory,f=e.age/e.life;s.set(n.genValue(d,f),r.genValue(d,f),o.genValue(d,f)),c&&a.toSimulation(s,h,l),e.velocity.addScaledVector(s,u)}}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON(),..."world"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new ui(de(t.x),de(t.y),de(t.z),Ne(t.space,"world"))}frameUpdate(t){void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)&&this._frame.refresh(this.ps)}clone(){return new ui(this.x.clone(),this.y.clone(),this.z.clone(),this.space)}reset(){}}class di{constructor(t,e={}){this.type="FrameOverLife",this.salt=new oe(0,1),this.frame=t,this.fps=e.fps??0,this.cycles=e.cycles??1,this.frameCount=e.frameCount??0,this.loop=e.loop??!0,this.random=e.random??!1,this.startFrame=e.startFrame}get frame(){return this._frame}set frame(t){this._frame=t}isPlain(){return!(this.fps>0)&&1===this.cycles&&void 0===this.startFrame}initialize(t){this._frame.startGen(t.memory),this.startFrame?.startGen(t.memory),this.salt.startGen(t.memory)}update(t,e){t.uvTile=this.frameAt(t,t.age,t.age/t.life)}updateAll(t,e,i){for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.uvTile=this.frameAt(e,e.age,e.age/e.life))}}frameAt(t,e,i){if(this.fps>0){const s=this.sampleFrame(t,i),n=this.frameCount;let r=Math.floor(e*this.fps)+this.offset(t);return this.random&&n>0?s+Math.floor(di.hash(r,this.saltOf(t))*n):(n>0&&(r=this.loop?di.wrap(r,n):Math.min(r,n-1)),s+r)}let s;if(1!==this.cycles&&this.cycles>0){const e=i*this.cycles;s=this.sampleFrame(t,i>=1?1:e-Math.floor(e))}else s=this.sampleFrame(t,i);return void 0!==this.startFrame&&(s+=this.offset(t),this.frameCount>0&&(s=di.wrap(s,this.frameCount))),s}offset(t){return void 0!==this.startFrame?Math.floor(this.startFrame.genValue(t.memory)):0}saltOf(t){const e=t.memory[this.salt.indexCount];return"number"==typeof e?e:0}static hash(t,e){const i=43758.5453*Math.sin(12.9898*t+7833.233*e);return Math.min(i-Math.floor(i),.999999)}static wrap(t,e){return(t%e+e)%e}sampleFrame(t,e){return"function"===this._frame.type?this._frame.genValue(t.memory,e):this._frame.genValue(t.memory)}frameUpdate(t){this._frame.refreshTable?.()}toJSON(){return{type:this.type,frame:this.frame.toJSON(),...this.fps>0?{fps:this.fps}:{},...1!==this.cycles?{cycles:this.cycles}:{},...this.frameCount>0?{frameCount:this.frameCount}:{},...this.loop?{}:{loop:!1},...this.random?{random:!0}:{},...void 0!==this.startFrame?{startFrame:this.startFrame.toJSON()}:{}}}static fromJSON(t){return new di(de(t.frame),{fps:"number"==typeof t.fps?t.fps:void 0,cycles:"number"==typeof t.cycles?t.cycles:void 0,frameCount:"number"==typeof t.frameCount?t.frameCount:void 0,loop:"boolean"==typeof t.loop?t.loop:void 0,random:!0===t.random,startFrame:void 0!==t.startFrame?de(t.startFrame):void 0})}clone(){return new di(this.frame.clone(),{fps:this.fps,cycles:this.cycles,frameCount:this.frameCount,loop:this.loop,random:this.random,startFrame:this.startFrame?.clone()})}reset(){}}class fi{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new ht}initialize(t){}update(t,e){const i=t.position.distanceToSquared(this.center);0!==i&&(this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/i*e))}updateAll(t,e,i){const s=this.center.x,n=this.center.y,r=this.center.z,o=this.magnitude*i;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const a=e.position,h=s-a.x,l=n-a.y,c=r-a.z,u=h*h+l*l+c*c;if(0===u)continue;const d=o/(u*Math.sqrt(u)),f=e.velocity;f.x+=h*d,f.y+=l*d,f.z+=c*d}}frameUpdate(t){}toJSON(){return{type:this.type,center:[this.center.x,this.center.y,this.center.z],magnitude:this.magnitude}}static fromJSON(t){return new fi(ee(t.center,new ht(0,0,0)),"number"==typeof t.magnitude?t.magnitude:0)}clone(){return new fi(this.center.clone(),this.magnitude)}reset(){}}class mi{constructor(t=new re(1),e="initial"){this.multiplier=t,this.mode=e,this.type="InheritVelocity",this._temp=new ht,this._tempPos=new ht,this._tempQInv=new at,this._tempScaleInv=new ht(1,1,1)}initialize(t,e){this.ps=e,this.multiplier.startGen(t.memory),"initial"===this.mode&&e.emitterVelocity&&(this._temp.copy(e.emitterVelocity),e.worldSpace||(this.decomposeInverse(e),this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv)),t.velocity.addScaledVector(this._temp,this.multiplier.genValue(t.memory,0)))}frameUpdate(t){this.ps&&!this.ps.worldSpace&&this.decomposeInverse(this.ps)}update(t,e){"current"===this.mode&&void 0!==this.ps&&this.ps.emitterVelocity&&(this._temp.copy(this.ps.emitterVelocity),this.ps.worldSpace||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,this.multiplier.genValue(t.memory,t.age/t.life)*e))}decomposeInverse(t){t.emitter.matrixWorld.decompose(this._tempPos,this._tempQInv,this._tempScaleInv),this._tempQInv.invert(),this._tempScaleInv.set(1/this._tempScaleInv.x,1/this._tempScaleInv.y,1/this._tempScaleInv.z)}toJSON(){return{type:this.type,multiplier:this.multiplier.toJSON(),mode:this.mode}}static fromJSON(t){return new mi(t.multiplier?de(t.multiplier):new re(1),"current"===t.mode?"current":"initial")}clone(){return new mi(this.multiplier.clone(),this.mode)}reset(){}}class pi{initialize(t,e){void 0!==e&&(this.ps=e),this.speed.startGen(t.memory)}motionScale(){const t=this.ps;return void 0!==t&&t.worldSpace?t.motionScale??1:1}constructor(t,e,i="local"){this.speed=t,this.dampen=e,this.space=i,this.type="LimitSpeedOverLife",this._frame=new Be,this._limit=new ht,this._velocity=new ht}_convertsSpace(){const t=void 0===this.ps||this.ps.worldSpace;return this.speed instanceof Pe&&t!==("world"===this.space)}_limitAxes(t,e,i,s,n){const r=this.speed.genValue(t.memory,this._limit,e),o=this._velocity.copy(t.velocity),a=void 0===this.ps||this.ps.worldSpace;n&&this._frame.fromSimulation(o,this.space,a);const h="world"===this.space?s:1,l=yi(o.x,r.x*h),c=yi(o.y,r.y*h),u=yi(o.z,r.z*h);0===l&&0===c&&0===u||(o.set(-l*i,-c*i,-u*i),n&&this._frame.toSimulation(o,this.space,a),t.velocity.add(o))}dampenStep(t){const e=this.dampen>1?1:this.dampen>0?this.dampen:0;return 1-Math.pow(1-e/3,60*t)}update(t,e){if(this.speed instanceof Pe){const i=t.age/t.life;return void this._limitAxes(t,i,this.dampenStep(e),this.motionScale(),this._convertsSpace())}const i=t.velocity.length(),s=this.speed.genValue(t.memory,t.age/t.life)*this.motionScale();if(i>s){const n=(i-s)/i;t.velocity.multiplyScalar(1-n*this.dampenStep(e))}}updateAll(t,e,i){const s=this.speed,n=this.dampenStep(i),r=this.motionScale();if(s instanceof Pe){const i=this._convertsSpace();for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this._limitAxes(e,e.age/e.life,n,r,i)}return}for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const o=e.velocity,a=o.length(),h=s.genValue(e.memory,e.age/e.life)*r;a>h&&o.multiplyScalar(1-(a-h)/a*n)}}toJSON(){return{type:this.type,speed:this.speed.toJSON(),dampen:this.dampen,..."local"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new pi("Vector3Function"===t.speed?.type?Pe.fromJSON(t.speed):de(t.speed),"number"==typeof t.dampen?t.dampen:1,Ne(t.space,"local"))}frameUpdate(t){const e=this.speed;e instanceof Pe?(e.x.refreshTable?.(),e.y.refreshTable?.(),e.z.refreshTable?.(),void 0!==this.ps&&this._convertsSpace()&&this._frame.refresh(this.ps)):e.refreshTable?.()}clone(){return new pi(this.speed.clone(),this.dampen,this.space)}reset(){}}function yi(t,e){const i=e>0?e:0;return t>i?t-i:t<-i?t+i:0}const gi=.5*(Math.sqrt(3)-1),vi=(3-Math.sqrt(3))/6,xi=1/3,Si=1/6,bi=(Math.sqrt(5)-1)/4,wi=(5-Math.sqrt(5))/20,Mi=new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),zi=new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);class _i{constructor(t=e){const e="function"==typeof t?t:function(t){let e=0,i=0,s=0,n=1;const r=function(){let t=4022871197;return function(e){e=e.toString();for(let i=0;i<e.length;i++){t+=e.charCodeAt(i);let s=.02519603282416938*t;t=s>>>0,s-=t,s*=t,t=s>>>0,s-=t,t+=4294967296*s}return 2.3283064365386963e-10*(t>>>0)}}();e=r(" "),i=r(" "),s=r(" "),e-=r(t),e<0&&(e+=1);i-=r(t),i<0&&(i+=1);s-=r(t),s<0&&(s+=1);return function(){const t=2091639*e+2.3283064365386963e-10*n;return e=i,i=s,s=t-(n=0|t)}}(t);this.p=function(t){const e=new Uint8Array(256);for(let t=0;t<256;t++)e[t]=t;for(let i=0;i<255;i++){const s=i+~~(t()*(256-i)),n=e[i];e[i]=e[s],e[s]=n}return e}(e),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(let t=0;t<512;t++)this.perm[t]=this.p[255&t],this.permMod12[t]=this.perm[t]%12}noise2D(t,e){const i=this.permMod12,s=this.perm;let n=0,r=0,o=0;const a=(t+e)*gi,h=Math.floor(t+a),l=Math.floor(e+a),c=(h+l)*vi,u=t-(h-c),d=e-(l-c);let f,m;u>d?(f=1,m=0):(f=0,m=1);const p=u-f+vi,y=d-m+vi,g=u-1+2*vi,v=d-1+2*vi,x=255&h,S=255&l;let b=.5-u*u-d*d;if(b>=0){const t=3*i[x+s[S]];b*=b,n=b*b*(Mi[t]*u+Mi[t+1]*d)}let w=.5-p*p-y*y;if(w>=0){const t=3*i[x+f+s[S+m]];w*=w,r=w*w*(Mi[t]*p+Mi[t+1]*y)}let M=.5-g*g-v*v;if(M>=0){const t=3*i[x+1+s[S+1]];M*=M,o=M*M*(Mi[t]*g+Mi[t+1]*v)}return 70*(n+r+o)}noise3D(t,e,i){const s=this.permMod12,n=this.perm;let r,o,a,h;const l=(t+e+i)*xi,c=Math.floor(t+l),u=Math.floor(e+l),d=Math.floor(i+l),f=(c+u+d)*Si,m=t-(c-f),p=e-(u-f),y=i-(d-f);let g,v,x,S,b,w;m>=p?p>=y?(g=1,v=0,x=0,S=1,b=1,w=0):m>=y?(g=1,v=0,x=0,S=1,b=0,w=1):(g=0,v=0,x=1,S=1,b=0,w=1):p<y?(g=0,v=0,x=1,S=0,b=1,w=1):m<y?(g=0,v=1,x=0,S=0,b=1,w=1):(g=0,v=1,x=0,S=1,b=1,w=0);const M=m-g+Si,z=p-v+Si,_=y-x+Si,A=m-S+2*Si,P=p-b+2*Si,O=y-w+2*Si,T=m-1+.5,V=p-1+.5,E=y-1+.5,$=255&c,C=255&u,I=255&d;let N=.6-m*m-p*p-y*y;if(N<0)r=0;else{const t=3*s[$+n[C+n[I]]];N*=N,r=N*N*(Mi[t]*m+Mi[t+1]*p+Mi[t+2]*y)}let F=.6-M*M-z*z-_*_;if(F<0)o=0;else{const t=3*s[$+g+n[C+v+n[I+x]]];F*=F,o=F*F*(Mi[t]*M+Mi[t+1]*z+Mi[t+2]*_)}let B=.6-A*A-P*P-O*O;if(B<0)a=0;else{const t=3*s[$+S+n[C+b+n[I+w]]];B*=B,a=B*B*(Mi[t]*A+Mi[t+1]*P+Mi[t+2]*O)}let U=.6-T*T-V*V-E*E;if(U<0)h=0;else{const t=3*s[$+1+n[C+1+n[I+1]]];U*=U,h=U*U*(Mi[t]*T+Mi[t+1]*V+Mi[t+2]*E)}return 32*(r+o+a+h)}noise4D(t,e,i,s){const n=this.perm;let r,o,a,h,l;const c=(t+e+i+s)*bi,u=Math.floor(t+c),d=Math.floor(e+c),f=Math.floor(i+c),m=Math.floor(s+c),p=(u+d+f+m)*wi,y=t-(u-p),g=e-(d-p),v=i-(f-p),x=s-(m-p);let S=0,b=0,w=0,M=0;y>g?S++:b++,y>v?S++:w++,y>x?S++:M++,g>v?b++:w++,g>x?b++:M++,v>x?w++:M++;const z=S>=3?1:0,_=b>=3?1:0,A=w>=3?1:0,P=M>=3?1:0,O=S>=2?1:0,T=b>=2?1:0,V=w>=2?1:0,E=M>=2?1:0,$=S>=1?1:0,C=b>=1?1:0,I=w>=1?1:0,N=M>=1?1:0,F=y-z+wi,B=g-_+wi,U=v-A+wi,R=x-P+wi,L=y-O+2*wi,D=g-T+2*wi,k=v-V+2*wi,q=x-E+2*wi,J=y-$+3*wi,G=g-C+3*wi,W=v-I+3*wi,j=x-N+3*wi,Q=y-1+4*wi,H=g-1+4*wi,Y=v-1+4*wi,X=x-1+4*wi,Z=255&u,K=255&d,tt=255&f,et=255&m;let it=.6-y*y-g*g-v*v-x*x;if(it<0)r=0;else{const t=n[Z+n[K+n[tt+n[et]]]]%32*4;it*=it,r=it*it*(zi[t]*y+zi[t+1]*g+zi[t+2]*v+zi[t+3]*x)}let st=.6-F*F-B*B-U*U-R*R;if(st<0)o=0;else{const t=n[Z+z+n[K+_+n[tt+A+n[et+P]]]]%32*4;st*=st,o=st*st*(zi[t]*F+zi[t+1]*B+zi[t+2]*U+zi[t+3]*R)}let nt=.6-L*L-D*D-k*k-q*q;if(nt<0)a=0;else{const t=n[Z+O+n[K+T+n[tt+V+n[et+E]]]]%32*4;nt*=nt,a=nt*nt*(zi[t]*L+zi[t+1]*D+zi[t+2]*k+zi[t+3]*q)}let rt=.6-J*J-G*G-W*W-j*j;if(rt<0)h=0;else{const t=n[Z+$+n[K+C+n[tt+I+n[et+N]]]]%32*4;rt*=rt,h=rt*rt*(zi[t]*J+zi[t+1]*G+zi[t+2]*W+zi[t+3]*j)}let ot=.6-Q*Q-H*H-Y*Y-X*X;if(ot<0)l=0;else{const t=n[Z+1+n[K+1+n[tt+1+n[et+1]]]]%32*4;ot*=ot,l=ot*ot*(zi[t]*Q+zi[t+1]*H+zi[t+2]*Y+zi[t+3]*X)}return 27*(r+o+a+h+l)}}const Ai=100,Pi=new Array(Ai),Oi=new ht,Ti=new at;function Vi(t){let e=Pi[t];return void 0===e&&(e=new _i(t),Pi[t]=e),e}class Ei{constructor(t,e,i=new re(1),s=new re(0),n=new re(0),r){this.frequency=t,this.power=e,this.positionAmount=i,this.rotationAmount=s,this.scrollSpeed=n,this.remap=r,this.type="Noise",this.duration=0,this.scrollOffset=0,this.scrollMemory=[],this._frequency=NaN,this._power=NaN,this._positionAmount=NaN,this._rotationAmount=NaN,this.scrollSpeed.startGen(this.scrollMemory)}sample(t,e,i){const s=t.noise2D(0,e),n=this.remap;return void 0===n?s:n.genValue(i,.5*(s+1))}initialize(t){const e=t.memory;this.frequency.startGen(e),this.power.startGen(e),this.positionAmount.startGen(e),this.rotationAmount.startGen(e),this.remap?.startGen(e);const i="number"==typeof t.rotation;let s=t._noiseState;if(void 0===s)return s={lastPos:new ht,lastRot:0,lastRotQ:i?null:new at,generatorX:Vi(ti(0,Ai)),generatorY:Vi(ti(0,Ai)),generatorZ:Vi(ti(0,Ai)),generatorW:Vi(ti(0,Ai))},void(t._noiseState=s);s.lastPos.set(0,0,0),s.lastRot=0,i?s.lastRotQ=null:null===s.lastRotQ?s.lastRotQ=new at:s.lastRotQ.set(0,0,0,1),s.generatorX=Vi(ti(0,Ai)),s.generatorY=Vi(ti(0,Ai)),s.generatorZ=Vi(ti(0,Ai)),s.generatorW=Vi(ti(0,Ai))}static constantOf(t){return t instanceof re?t.value:NaN}rotateByNoise(t,e,i,s,n){const r=e.lastRotQ;t.multiply(r.invert()),Oi.set(this.sample(e.generatorX,i,n),this.sample(e.generatorY,i,n),this.sample(e.generatorZ,i,n));const o=Oi.length();o>0?(Oi.multiplyScalar(1/o),Ti.setFromAxisAngle(Oi,this.sample(e.generatorW,i,n)*Math.PI*s)):Ti.set(0,0,0,1),t.multiply(Ti),r.copy(Ti)}update(t,e){const i=t._noiseState;if(void 0===i)return;const s=t.memory,n=t.age/t.life,r=this._frequency,o=r==r?r:this.frequency.genValue(s,n),a=this._power,h=a==a?a:this.power.genValue(s,n),l=this._positionAmount,c=l==l?l:this.positionAmount.genValue(s,n),u=this._rotationAmount,d=u==u?u:this.rotationAmount.genValue(s,n),f=t.age*o+this.scrollOffset;if(c>0){const e=h*c;t.position.sub(i.lastPos),Oi.set(this.sample(i.generatorX,f,s)*e,this.sample(i.generatorY,f,s)*e,this.sample(i.generatorZ,f,s)*e),t.position.add(Oi),i.lastPos.copy(Oi)}if(d>0){const e=h*d;if("number"==typeof t.rotation){const n=this.sample(i.generatorW,f,s)*Math.PI*e;t.rotation=t.rotation-i.lastRot+n,i.lastRot=n}else null!==i.lastRotQ&&this.rotateByNoise(t.rotation,i,f,e,s)}}updateAll(t,e,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.rotation,o=s.scalars,a=We.SCALAR_STRIDE,h=this._frequency,l=this._power,c=this._positionAmount,u=this._rotationAmount;for(let i=0,s=0,d=0;i<e;i++,s+=3,d+=a){const e=o[d],a=o[d+1];if(e>=a)continue;const f=t[i],m=f._noiseState;if(void 0===m)continue;const p=f.memory,y=e/a,g=h==h?h:this.frequency.genValue(p,y),v=l==l?l:this.power.genValue(p,y),x=c==c?c:this.positionAmount.genValue(p,y),S=u==u?u:this.rotationAmount.genValue(p,y),b=e*g+this.scrollOffset;if(x>0){const t=v*x,e=m.lastPos,i=this.sample(m.generatorX,b,p)*t,r=this.sample(m.generatorY,b,p)*t,o=this.sample(m.generatorZ,b,p)*t;n[s]=Math.fround(n[s]-e.x)+i,n[s+1]=Math.fround(n[s+1]-e.y)+r,n[s+2]=Math.fround(n[s+2]-e.z)+o,e.set(i,r,o)}if(S>0){const t=v*S;if("number"==typeof f.rotation){const e=this.sample(m.generatorW,b,p)*Math.PI*t;r[i]=r[i]-m.lastRot+e,m.lastRot=e}else null!==m.lastRotQ&&this.rotateByNoise(f.rotation,m,b,t,p)}}}toJSON(){return{type:this.type,frequency:this.frequency.toJSON(),power:this.power.toJSON(),positionAmount:this.positionAmount.toJSON(),rotationAmount:this.rotationAmount.toJSON(),scrollSpeed:this.scrollSpeed.toJSON(),...void 0!==this.remap?{remap:this.remap.toJSON()}:{}}}frameUpdate(t){this.duration+=t,this.scrollOffset+=this.scrollSpeed.genValue(this.scrollMemory,0)*t,this._frequency=Ei.constantOf(this.frequency),this._power=Ei.constantOf(this.power),this._positionAmount=Ei.constantOf(this.positionAmount),this._rotationAmount=Ei.constantOf(this.rotationAmount)}static fromJSON(t){return new Ei(de(t.frequency),de(t.power),t.positionAmount?de(t.positionAmount):void 0,t.rotationAmount?de(t.rotationAmount):void 0,t.scrollSpeed?de(t.scrollSpeed):new re(0),t.remap?de(t.remap):void 0)}clone(){return new Ei(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone(),this.scrollSpeed.clone(),this.remap?.clone())}reset(){this.scrollOffset=0}}class $i{constructor(t,e=new ht(0,1,0),i="local"){this.orbitSpeed=t,this.axis=e,this.space=i,this.type="OrbitOverLife",this.temp=new ht,this._frame=new Be,this._axis=new ht(0,1,0),this._center=new ht,this.rotation=new at,this.refreshAxis()}initialize(t,e){this.ps=e,this.orbitSpeed.startGen(t.memory)}refreshAxis(){const t=this._axis.copy(this.axis),e=this._center.set(0,0,0);if(void 0!==this.ps){const i=this.ps.worldSpace;this._frame.toSimulation(t,this.space,i),this._frame.pointToSimulation(e,this.space,i)}const i=t.length();i>0?t.multiplyScalar(1/i):t.set(0,0,0)}converts(){return void 0!==this.ps&&this.ps.worldSpace!==("world"===this.space)}update(t,e){const i=this._axis;if(0===i.x&&0===i.y&&0===i.z)return;const s=t.position;s.sub(this._center),this.temp.copy(s).projectOnVector(i),this.rotation.setFromAxisAngle(i,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),s.sub(this.temp),s.applyQuaternion(this.rotation),s.add(this.temp),s.add(this._center)}updateAll(t,e,i){const s=this._axis;if(0===s.x&&0===s.y&&0===s.z)return;const n=this.orbitSpeed,r=this._center,o=this.temp,a=this.rotation;for(let h=0;h<e;h++){const e=t[h];if(e.age>=e.life)continue;const l=e.position;l.sub(r),o.copy(l).projectOnVector(s),a.setFromAxisAngle(s,n.genValue(e.memory,e.age/e.life)*i),l.sub(o),l.applyQuaternion(a),l.add(o),l.add(r)}}frameUpdate(t){this.converts()&&this._frame.refresh(this.ps),this.refreshAxis()}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z],..."local"!==this.space?{space:this.space}:{}}}static fromJSON(t){return new $i(de(t.orbitSpeed),t.axis?new ht(t.axis[0],t.axis[1],t.axis[2]):void 0,Ne(t.space,"local"))}clone(){return new $i(this.orbitSpeed.clone(),this.axis.clone(),this.space)}reset(){}}const Ci=new at;class Ii{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new at}initialize(t){t.rotation instanceof at&&(t.angularVelocity=t instanceof Ye?Ci:new at,this.angularVelocity.startGen(t.memory))}update(t,e){if(t.rotation instanceof at){this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat);const i=t.angularVelocity;i instanceof at&&i.copy(this.tempQuat)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new Ii(Ae(t.angularVelocity))}frameUpdate(t){}clone(){return new Ii(this.angularVelocity.clone())}reset(){}}class Ni{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new at}initialize(t){"number"==typeof t.rotation&&this.angularVelocity.startGen(t.memory)}update(t,e){if("number"==typeof t.rotation){const i=qe(t,this.speedRange),s=this.angularVelocity.genValue(t.memory,i);t.rotation+=e*s,t.angularVelocity=s}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new Ni(de(t.angularVelocity),t.speedRange?oe.fromJSON(t.speedRange):new oe(0,1))}frameUpdate(t){}clone(){return new Ni(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class Fi{constructor(t){this.angularVelocity=t,this.type="RotationOverLife",this.tempQuat=new at}initialize(t){"number"==typeof t.rotation?this.angularVelocity.startGen(t.memory):t.rotation instanceof at&&(this.angularVelocity.startGen(t.memory),t.angularVelocity instanceof at||(t.angularVelocity=new at))}update(t,e){if("number"==typeof t.rotation){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);t.rotation+=e*i,t.angularVelocity=i}else if(t.rotation instanceof at){const i=this.angularVelocity.genValue(t.memory,t.age/t.life);this.turnAboutZ(t,t.rotation,i*e)}}updateAll(t,e,i){const s=this.angularVelocity;for(let n=0;n<e;n++){const e=t[n];if(e.age>=e.life)continue;const r=e.rotation;if("number"==typeof r){const t=s.genValue(e.memory,e.age/e.life);e.rotation=r+i*t,e.angularVelocity=t}else if(r instanceof at){const t=s.genValue(e.memory,e.age/e.life);this.turnAboutZ(e,r,t*i)}}}turnAboutZ(t,e,i){const s=this.tempQuat.setFromAxisAngle(ri,i);e.multiply(s);const n=t.angularVelocity;n instanceof at&&n.copy(s)}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new Fi(de(t.angularVelocity))}frameUpdate(t){this.angularVelocity.refreshTable?.()}clone(){return new Fi(this.angularVelocity.clone())}reset(){}}class Bi{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=qe(t,this.speedRange);this.size instanceof Pe?this.size.genValue(t.memory,t.size,e).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,e))}toJSON(){return{type:this.type,size:this.size.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new Bi(Te(t.size),t.speedRange?oe.fromJSON(t.speedRange):new oe(0,1))}frameUpdate(t){}clone(){return new Bi(this.size.clone(),this.speedRange.clone())}reset(){}}class Ui{constructor(t){this.type="SizeOverLife",this._sizeIsVector3=!1,this.size=t}get size(){return this._size}set size(t){this._size=t,this._sizeIsVector3=t instanceof Pe}initialize(t){this._size.startGen(t.memory)}update(t){const e=t.age/t.life;if(this._sizeIsVector3)this._size.genValue(t.memory,t.size,e).multiply(t.startSize);else{const i=this._size.genValue(t.memory,e),s=t.size,n=t.startSize;s.x=n.x*i,s.y=n.y*i,s.z=n.z*i}}updateAll(t,e,i){if(this._sizeIsVector3){const i=this._size;for(let s=0;s<e;s++){const e=t[s];e.age>=e.life||i.genValue(e.memory,e.size,e.age/e.life).multiply(e.startSize)}return}const s=this._size;for(let i=0;i<e;i++){const e=t[i];if(e.age>=e.life)continue;const n=s.genValue(e.memory,e.age/e.life),r=e.size,o=e.startSize;r.x=o.x*n,r.y=o.y*n,r.z=o.z*n}}toJSON(){return{type:this.type,size:this.size.toJSON()}}static fromJSON(t){return new Ui(Te(t.size))}frameUpdate(t){this._size.refreshTable?.()}clone(){return new Ui(this.size.clone())}reset(){}}class Ri{initialize(t){this.speed.startGen(t.memory)}constructor(t){this.speed=t,this.type="SpeedOverLife"}update(t){t.speedModifier=this.speed.genValue(t.memory,t.age/t.life)}updateAll(t,e,i){const s=this.speed;for(let i=0;i<e;i++){const e=t[i];e.age>=e.life||(e.speedModifier=s.genValue(e.memory,e.age/e.life))}}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new Ri(de(t.speed))}frameUpdate(t){this.speed.refreshTable?.()}clone(){return new Ri(this.speed.clone())}reset(){}}function Li(t){return 0===t?0:1/t}class Di{constructor(t,e,i,s,n=0){this.scale=t,this.octaves=e,this.velocityMultiplier=i,this.timeScale=s,this.seed=n,this.type="TurbulenceField",this.timeOffset=new ht,this.initialOffset=new ht,this.temp=new ht,this.temp2=new ht;const r=$(n);this.generator=new _i(r),this.initialOffset.set(r()*Li(t.x)*s.x,r()*Li(t.y)*s.y,r()*Li(t.z)*s.z),this.timeOffset.copy(this.initialOffset)}initialize(t){}update(t,e){const i=t.position.x*Li(this.scale.x),s=t.position.y*Li(this.scale.y),n=t.position.z*Li(this.scale.z);this.temp.set(0,0,0);let r=1;for(let t=0;t<this.octaves;t++)this.temp2.set(this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.x*r)/r,this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.y*r)/r,this.generator.noise4D(i*r,s*r,n*r,this.timeOffset.z*r)/r),this.temp.add(this.temp2),r*=2;this.temp.multiply(this.velocityMultiplier),t.velocity.addScaledVector(this.temp,e)}updateAll(t,e,i){const s=e>0?t[0].store:void 0;if(void 0===s){for(let s=0;s<e;s++){const e=t[s];e.age<e.life&&this.update(e,i)}return}const n=s.position,r=s.velocity,o=s.scalars,a=We.SCALAR_STRIDE,h=this.generator,l=this.octaves,c=Li(this.scale.x),u=Li(this.scale.y),d=Li(this.scale.z),f=this.velocityMultiplier.x*i,m=this.velocityMultiplier.y*i,p=this.velocityMultiplier.z*i,y=this.timeOffset.x,g=this.timeOffset.y,v=this.timeOffset.z;for(let t=0,i=0,s=0;t<e;t++,i+=3,s+=a){if(o[s]>=o[s+1])continue;const t=n[i]*c,e=n[i+1]*u,a=n[i+2]*d;let x=0,S=0,b=0,w=1;for(let i=0;i<l;i++){const i=t*w,s=e*w,n=a*w;x+=h.noise4D(i,s,n,y*w)/w,S+=h.noise4D(i,s,n,g*w)/w,b+=h.noise4D(i,s,n,v*w)/w,w*=2}r[i]+=x*f,r[i+1]+=S*m,r[i+2]+=b*p}}toJSON(){return{type:this.type,scale:[this.scale.x,this.scale.y,this.scale.z],octaves:this.octaves,velocityMultiplier:[this.velocityMultiplier.x,this.velocityMultiplier.y,this.velocityMultiplier.z],timeScale:[this.timeScale.x,this.timeScale.y,this.timeScale.z],...0!==this.seed?{seed:this.seed}:{}}}frameUpdate(t){this.timeOffset.x+=t*this.timeScale.x,this.timeOffset.y+=t*this.timeScale.y,this.timeOffset.z+=t*this.timeScale.z}static fromJSON(t){return new Di(ee(t.scale,new ht(1,1,1)),"number"==typeof t.octaves?t.octaves:1,ee(t.velocityMultiplier,new ht(1,1,1)),ee(t.timeScale,new ht(1,1,1)),"number"==typeof t.seed?t.seed:0)}clone(){return new Di(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone(),this.seed)}reset(){this.timeOffset.copy(this.initialOffset)}}const ki=new ht(1,0,0),qi=new ht(0,1,0),Ji=new ht(0,0,1);class Gi{constructor(t=new re(0),e=new re(0),i=new re(0),s=new re(0),n=new re(0),r=new re(0),o="local",a=new re(0),h=new ht){this.linearX=t,this.linearY=e,this.linearZ=i,this.orbitalX=s,this.orbitalY=n,this.orbitalZ=r,this.space=o,this.radial=a,this.orbitalOffset=h,this.type="VelocityOverLife",this._temp=new ht,this._tempEmitterPos=new ht,this._tempQ=new at,this._tempQInv=new at,this._tempScale=new ht(1,1,1),this._tempScaleInv=new ht(1,1,1),this._tempRot=new at,this._axisX=new ht(1,0,0),this._axisY=new ht(0,1,0),this._axisZ=new ht(0,0,1),this._center=new ht}initialize(t,e){this.ps=e,this.linearX.startGen(t.memory),this.linearY.startGen(t.memory),this.linearZ.startGen(t.memory),this.orbitalX.startGen(t.memory),this.orbitalY.startGen(t.memory),this.orbitalZ.startGen(t.memory),this.radial.startGen(t.memory)}frameUpdate(t){this.ps&&(this.ps.emitter.matrixWorld.decompose(this._tempEmitterPos,this._tempQ,this._tempScale),this._tempQInv.copy(this._tempQ).invert(),this._tempScaleInv.set(1/this._tempScale.x,1/this._tempScale.y,1/this._tempScale.z),this._axisX.copy(ki),this._axisY.copy(qi),this._axisZ.copy(Ji),this._center.copy(this.orbitalOffset),this.ps.worldSpace&&(this._axisX.applyQuaternion(this._tempQ),this._axisY.applyQuaternion(this._tempQ),this._axisZ.applyQuaternion(this._tempQ),this._center.multiply(this._tempScale).applyQuaternion(this._tempQ).add(this._tempEmitterPos)))}update(t,e){const i=t.age/t.life;this._temp.set(this.linearX.genValue(t.memory,i),this.linearY.genValue(t.memory,i),this.linearZ.genValue(t.memory,i));const s=void 0!==this.ps&&this.ps.worldSpace;s&&"local"===this.space?this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ):s||"world"!==this.space||this._temp.multiply(this._tempScaleInv).applyQuaternion(this._tempQInv),t.position.addScaledVector(this._temp,e);const n=this.radial.genValue(t.memory,i);if(0!==n){this._temp.copy(t.position).sub(this._center);const i=this._temp.length();i>0&&t.position.addScaledVector(this._temp,n*e/i)}const r=this.orbitalX.genValue(t.memory,i)*e,o=this.orbitalY.genValue(t.memory,i)*e,a=this.orbitalZ.genValue(t.memory,i)*e;0===r&&0===o&&0===a||(t.position.sub(this._center),this.orbit(t.position,this._axisX,r),this.orbit(t.position,this._axisY,o),this.orbit(t.position,this._axisZ,a),t.position.add(this._center))}orbit(t,e,i){0!==i&&(this._tempRot.setFromAxisAngle(e,i),t.applyQuaternion(this._tempRot))}toJSON(){return{type:this.type,linearX:this.linearX.toJSON(),linearY:this.linearY.toJSON(),linearZ:this.linearZ.toJSON(),orbitalX:this.orbitalX.toJSON(),orbitalY:this.orbitalY.toJSON(),orbitalZ:this.orbitalZ.toJSON(),space:this.space,radial:this.radial.toJSON(),orbitalOffset:[this.orbitalOffset.x,this.orbitalOffset.y,this.orbitalOffset.z]}}static fromJSON(t){const e=t=>t?de(t):new re(0);return new Gi(e(t.linearX),e(t.linearY),e(t.linearZ),e(t.orbitalX),e(t.orbitalY),e(t.orbitalZ),"world"===t.space?"world":"local",e(t.radial),Array.isArray(t.orbitalOffset)?new ht(t.orbitalOffset[0]??0,t.orbitalOffset[1]??0,t.orbitalOffset[2]??0):new ht)}clone(){return new Gi(this.linearX.clone(),this.linearY.clone(),this.linearZ.clone(),this.orbitalX.clone(),this.orbitalY.clone(),this.orbitalZ.clone(),this.space,this.radial.clone(),this.orbitalOffset.clone())}reset(){}}class Wi{initialize(t){this.width.startGen(t.memory)}constructor(t,e=!1){this.width=t,this.absolute=e,this.type="WidthOverLength"}update(t){if(!(t instanceof Ke))return;const e=t.memory;t.headWidthScale=this.absolute?1:this.width.genValue(e,0);const i=t.historyCount;if(0===i)return;const s=t.historyCapacity,n=t.historySizes,r=t.historyBaseSizes,o=1/i,a=this.absolute;let h=t.getHistoryIndex(0);for(let t=0;t<i;t++){const l=this.width.genValue(e,(i-t)*o);n[h]=a?l:r[h]*l,h++,h===s&&(h=0)}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON(),absolute:this.absolute}}static fromJSON(t){return new Wi(de(t.width),t.absolute??!0)}clone(){return new Wi(this.width.clone(),this.absolute)}reset(){}}const ji={ApplyForce:{type:"ApplyForce",constructor:Ue,params:[["direction",["vec3"]],["magnitude",["value"]],["space",["string"]]],loadJSON:Ue.fromJSON},Noise:{type:"Noise",constructor:Ei,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]],["scrollSpeed",["value"]],["remap",["valueFunc"]]],loadJSON:Ei.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:Di,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]],["seed",["number"]]],loadJSON:Di.fromJSON},GravityForce:{type:"GravityForce",constructor:fi,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:fi.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:Ge,params:[["color",["colorFunc"]]],loadJSON:Ge.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:Fi,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:Fi.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:Ii,params:[["angularVelocity",["rotationFunc"]]],loadJSON:Ii.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:Ui,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:Ui.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:Je,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:Je.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:Ni,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:Ni.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:Bi,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:Bi.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:Ri,params:[["speed",["value","valueFunc"]]],loadJSON:Ri.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:di,params:[["frame",["value","valueFunc"]],["fps",["number"]],["cycles",["number"]],["frameCount",["number"]],["loop",["boolean"]],["random",["boolean"]],["startFrame",["value"]]],loadJSON:di.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:ui,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]],["space",["string"]]],loadJSON:ui.fromJSON},VelocityOverLife:{type:"VelocityOverLife",constructor:Gi,params:[["linearX",["value","valueFunc"]],["linearY",["value","valueFunc"]],["linearZ",["value","valueFunc"]],["orbitalX",["value","valueFunc"]],["orbitalY",["value","valueFunc"]],["orbitalZ",["value","valueFunc"]],["space",["string"]],["radial",["value","valueFunc"]],["orbitalOffset",["vec3"]]],loadJSON:Gi.fromJSON},InheritVelocity:{type:"InheritVelocity",constructor:mi,params:[["multiplier",["value","valueFunc"]],["mode",["string"]]],loadJSON:mi.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:$i,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]],["space",["string"]]],loadJSON:$i.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:Wi,params:[["width",["value","valueFunc"]],["absolute",["boolean"]]],loadJSON:Wi.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:ke,params:[["angle",["value"]]],loadJSON:ke.fromJSON},ApplySequences:{type:"ApplySequences",constructor:De,params:[["delay",["number"]]],loadJSON:De.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:ci,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]],["inherit",["subEmitterInherit"]]],loadJSON:ci.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:pi,params:[["speed",["value","valueFunc","vec3Func"]],["dampen",["number"]],["space",["string"]]],loadJSON:pi.fromJSON},ApplyCollision:{type:"ApplyCollision",constructor:Lt,params:[["bounce",["number"]]],loadJSON:Lt.fromJSON}};function Qi(t,e){const i=t?ji[t.type]:void 0;return i?i.loadJSON(t,e):(te(`${ie("behavior",t)}; it is skipped.`),null)}function Hi(t,e){const i=t.toJSON(),s=ji[i?.type];return s?ne(i,t=>s.loadJSON(t,e).toJSON()):i}const Yi={PiecewiseBezier:le,Vector3Function:Pe,Quaternion:at,ConstantValue:re,Gradient:ve,Vector4View:Nt,AxisAngleGenerator:me,IntervalValue:oe,ColorRange:pe};function Xi(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.PiecewiseBezier ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length - 1 : 0;\n const ${t}_const = ${t} instanceof deps.ConstantValue;\n const ${t}_cv = ${t}_const ? ${t}.value : 0;\n const ${t}_iv = ${t} instanceof deps.IntervalValue;\n const ${t}_slot = ${t}_iv ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n const ${t}_a = ${t}_iv ? ${t}.a : 0, ${t}_b = ${t}_iv ? ${t}.b : 0;`}function Zi(t){return`const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz) * scalars[s + 2];\n let ts = span${t} === 0 ? (speed >= lo${t} ? 1 : 0) : (speed - lo${t}) / span${t};\n ts = ts < 0 ? 0 : ts > 1 ? 1 : ts;`}function Ki(t,e,i){return`let ${e};\n if (${t}_tbl !== null) {\n const tt = ${i};\n if (tt <= 0) ${e} = ${t}_tbl[0];\n else if (tt >= 1) ${e} = ${t}_tbl[${t}_last];\n else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const v0 = ${t}_tbl[ix];\n ${e} = v0 + (${t}_tbl[ix + 1] - v0) * (x - ix);\n }\n } else if (${t}_const) ${e} = ${t}_cv;\n else if (${t}_iv) {\n // The particle's own sample, from the memory column when it holds it.\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n ${e} = (1 - r) * ${t}_a + r * ${t}_b;\n } else ${e} = ${t}.genValue(p.memory, ${i});`}function ts(t,e){return`const ${t} = ${e};\n const ${t}_tbl = ${t} instanceof deps.Gradient ? ${t}.sampledTable() : null;\n const ${t}_last = ${t}_tbl !== null ? ${t}_tbl.length / 4 - 1 : 0;\n const ${t}_cr = ${t} instanceof deps.ColorRange;\n const ${t}_slot = ${t}_cr ? ${t}.indexCount : -1;\n const ${t}_col = ${t}_slot >= 0 && ${t}_slot < ms;\n // Rounded to float32 as copying the colour into the particle does.\n const ${t}_ax = ${t}_cr ? Math.fround(${t}.a.x) : 0, ${t}_ay = ${t}_cr ? Math.fround(${t}.a.y) : 0;\n const ${t}_az = ${t}_cr ? Math.fround(${t}.a.z) : 0, ${t}_aw = ${t}_cr ? Math.fround(${t}.a.w) : 0;\n const ${t}_bx = ${t}_cr ? ${t}.b.x : 0, ${t}_by = ${t}_cr ? ${t}.b.y : 0;\n const ${t}_bz = ${t}_cr ? ${t}.b.z : 0, ${t}_bw = ${t}_cr ? ${t}.b.w : 0;`}function es(t,e){return`if (${t}_tbl !== null) {\n const tt = ${e};\n const tbl = ${t}_tbl;\n let r, g, b, a;\n if (tt <= 0) {\n r = tbl[0]; g = tbl[1]; b = tbl[2]; a = tbl[3];\n } else if (tt >= 1) {\n const o = ${t}_last * 4;\n r = tbl[o]; g = tbl[o + 1]; b = tbl[o + 2]; a = tbl[o + 3];\n } else {\n const x = tt * ${t}_last;\n const ix = x | 0;\n const fr = x - ix;\n const o = ix * 4;\n const nx = o + 4;\n r = tbl[o] + (tbl[nx] - tbl[o]) * fr;\n g = tbl[o + 1] + (tbl[nx + 1] - tbl[o + 1]) * fr;\n b = tbl[o + 2] + (tbl[nx + 2] - tbl[o + 2]) * fr;\n a = tbl[o + 3] + (tbl[nx + 3] - tbl[o + 3]) * fr;\n }\n color[o4] = Math.fround(r) * startColor[o4];\n color[o4 + 1] = Math.fround(g) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(b) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(a) * startColor[o4 + 3];\n } else if (${t}_cr) {\n let r = ${t}_col ? mem[row * ms + ${t}_slot] : NaN;\n if (r !== r) r = p.memory[${t}_slot];\n color[o4] = Math.fround(${t}_ax + (${t}_bx - ${t}_ax) * r) * startColor[o4];\n color[o4 + 1] = Math.fround(${t}_ay + (${t}_by - ${t}_ay) * r) * startColor[o4 + 1];\n color[o4 + 2] = Math.fround(${t}_az + (${t}_bz - ${t}_az) * r) * startColor[o4 + 2];\n color[o4 + 3] = Math.fround(${t}_aw + (${t}_bw - ${t}_aw) * r) * startColor[o4 + 3];\n } else {\n ${t}.genColor(p.memory, tmpColor, ${e});\n color[o4] = tmpColor.x * startColor[o4];\n color[o4 + 1] = tmpColor.y * startColor[o4 + 1];\n color[o4 + 2] = tmpColor.z * startColor[o4 + 2];\n color[o4 + 3] = tmpColor.w * startColor[o4 + 3];\n }`}function is(t,e,i,s,n,r,o){return`{\n const cx = 2 * (${n} * ${i} - ${r} * ${e});\n const cy = 2 * (${r} * ${t} - ${s} * ${i});\n const cz = 2 * (${s} * ${e} - ${n} * ${t});\n const nx = ${t} + ${o} * cx + ${n} * cz - ${r} * cy;\n const ny = ${e} + ${o} * cy + ${r} * cx - ${s} * cz;\n ${i} = ${i} + ${o} * cz + ${s} * cy - ${n} * cx;\n ${t} = nx;\n ${e} = ny;\n }`}function ss(t,e){return`const ${t}_q = ${e};\n const ${t}x = ${t}_q.x, ${t}y = ${t}_q.y, ${t}z = ${t}_q.z, ${t}w = ${t}_q.w;`}function ns(t,e){return`const ${t}_v = ${e};\n const ${t}x = ${t}_v.x, ${t}y = ${t}_v.y, ${t}z = ${t}_v.z;`}function rs(t,e,i,s){return`{\n const half = ${t} / 2;\n const sn = Math.sin(half);\n const qx = ${e} * sn, qy = ${i} * sn, qz = ${s} * sn, qw = Math.cos(half);\n ${is("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(px); py = Math.fround(py); pz = Math.fround(pz);\n }`}function os(t,e){switch(t.type){case"ColorOverLife":return{setup:ts(`g${e}`,`behaviors[${e}].color`),body:`{${es(`g${e}`,"t")}}`};case"SizeOverLife":return{setup:`const g${e} = behaviors[${e}].size;\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Xi(`sg${e}`,`g${e}`)}`,body:`if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, t).multiply(p.startSize);\n } else {\n ${Ki(`sg${e}`,"v","t")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }`};case"ApplyForce":return{setup:`const b${e} = behaviors[${e}];\n const d${e} = b${e}._direction;\n const dx${e} = d${e}.x, dy${e} = d${e}.y, dz${e} = d${e}.z;\n const step${e} = b${e}._step(delta);\n ${Xi(`g${e}`,`b${e}.magnitude`)}`,body:`{\n ${Ki(`g${e}`,"m","t")}\n const s = m * step${e};\n vel[o3] += dx${e} * s; vel[o3 + 1] += dy${e} * s; vel[o3 + 2] += dz${e} * s;\n }`};case"RotationOverLife":return{setup:`${Xi(`g${e}`,`behaviors[${e}].angularVelocity`)}\n const rotation_${e} = count > 0 ? particles[0].rotation : undefined;\n const angle_${e} = typeof rotation_${e} === 'number';\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = !angle_${e} && rq${e}.length > 0 && rotation_${e} instanceof deps.Quaternion;`,body:`if (angle_${e}) {\n ${Ki(`g${e}`,"rate","t")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n } else if (quat_${e}) {\n ${Ki(`g${e}`,"rate","t")}\n const half = (rate * delta) / 2;\n const qz = Math.sin(half), qw = Math.cos(half);\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + ay * qz;\n rq${e}[o4 + 1] = ay * qw - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz;\n rq${e}[o4 + 3] = aw * qw - az * qz;\n aq${e}[o4] = 0; aq${e}[o4 + 1] = 0; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"FrameOverLife":return{setup:`${Xi(`g${e}`,`behaviors[${e}].frame`)}\n const b${e} = behaviors[${e}];\n const plain${e} = typeof b${e}.isPlain !== 'function' || b${e}.isPlain();`,body:`if (plain${e}) {${Ki(`g${e}`,"v","t")} uvTile[row] = v;}\n else uvTile[row] = b${e}.frameAt(p, age, t);`};case"SpeedOverLife":return{setup:Xi(`g${e}`,`behaviors[${e}].speed`),body:`{${Ki(`g${e}`,"v","t")} scalars[s + 2] = v;}`};case"ForceOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Xi(`gx${e}`,`b${e}.x`)}\n ${Xi(`gy${e}`,`b${e}.y`)}\n ${Xi(`gz${e}`,`b${e}.z`)}\n const world${e} = b${e}.ps === undefined || b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const toLocal${e} = !world${e} && b${e}.space === 'world';\n const step${e} = b${e}._step(delta);\n const fr${e} = b${e}._frame;\n ${ns(`sc${e}`,`toWorld${e} ? fr${e}.scale : fr${e}.scaleInverse`)}\n ${ss(`q${e}`,`toWorld${e} ? fr${e}.quaternion : fr${e}.quaternionInverse`)}`,body:`{\n ${Ki(`gx${e}`,"fx","t")}\n ${Ki(`gy${e}`,"fy","t")}\n ${Ki(`gz${e}`,"fz","t")}\n if (toWorld${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${is("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n } else if (toLocal${e}) {\n ${is("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n }\n vel[o3] += fx * step${e}; vel[o3 + 1] += fy * step${e}; vel[o3 + 2] += fz * step${e};}`};case"LimitSpeedOverLife":return{setup:`const b${e} = behaviors[${e}];\n const vec3_${e} = b${e}.speed instanceof deps.Vector3Function;\n ${Xi(`g${e}`,`b${e}.speed`)}\n const dampen${e} = b${e}.dampenStep(delta);\n const ms${e} = typeof b${e}.motionScale === 'function' ? b${e}.motionScale() : 1;\n const conv${e} = vec3_${e} && b${e}._convertsSpace();`,body:`if (vec3_${e}) b${e}._limitAxes(p, t, dampen${e}, ms${e}, conv${e});\n else {const vx = vel[o3], vy = vel[o3 + 1], vz = vel[o3 + 2];\n const speed = Math.sqrt(vx * vx + vy * vy + vz * vz);\n ${Ki(`g${e}`,"limitBase","t")}\n const limit = limitBase * ms${e};\n if (speed > limit) {\n const f = 1 - ((speed - limit) / speed) * dampen${e};\n vel[o3] = vx * f; vel[o3 + 1] = vy * f; vel[o3 + 2] = vz * f;\n }}`};case"GravityForce":return{setup:`const b${e} = behaviors[${e}];\n const cx${e} = b${e}.center.x, cy${e} = b${e}.center.y, cz${e} = b${e}.center.z;\n const gm${e} = b${e}.magnitude * delta;`,body:`{const dx = cx${e} - pos[o3], dy = cy${e} - pos[o3 + 1], dz = cz${e} - pos[o3 + 2];\n const d2 = dx * dx + dy * dy + dz * dz;\n if (d2 > 0) {\n const f = gm${e} / (d2 * Math.sqrt(d2));\n vel[o3] += dx * f; vel[o3 + 1] += dy * f; vel[o3 + 2] += dz * f;\n }}`};case"ColorBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${ts(`g${e}`,`b${e}.color`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};`,body:`{${Zi(e)}\n ${es(`g${e}`,"ts")}}`};case"SizeBySpeed":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.size;\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const vec3_${e} = g${e} instanceof deps.Vector3Function;\n ${Xi(`sg${e}`,`g${e}`)}`,body:`{${Zi(e)}\n if (vec3_${e}) {\n g${e}.genValue(p.memory, p.size, ts).multiply(p.startSize);\n } else {\n ${Ki(`sg${e}`,"v","ts")}\n size[o3] = startSize[o3] * v;\n size[o3 + 1] = startSize[o3 + 1] * v;\n size[o3 + 2] = startSize[o3 + 2] * v;\n }}`};case"RotationBySpeed":return{setup:`const b${e} = behaviors[${e}];\n ${Xi(`g${e}`,`b${e}.angularVelocity`)}\n const lo${e} = b${e}.speedRange.a;\n const span${e} = b${e}.speedRange.b - lo${e};\n const angle_${e} = count > 0 && typeof particles[0].rotation === 'number';`,body:`if (angle_${e}) {\n ${Zi(e)}\n ${Ki(`g${e}`,"rate","ts")}\n rot[row] += delta * rate;\n angVel[row] = rate;\n }`};case"OrbitOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Xi(`g${e}`,`b${e}.orbitSpeed`)}\n ${ns(`ax${e}`,`b${e}._axis`)}\n ${ns(`c${e}`,`b${e}._center`)}\n const alen${e} = ax${e}x * ax${e}x + ax${e}y * ax${e}y + ax${e}z * ax${e}z;\n const orbit${e} = alen${e} !== 0;\n const chalf${e} = (g${e}_cv * delta) / 2;\n const csn${e} = Math.sin(chalf${e});\n const cqx${e} = ax${e}x * csn${e}, cqy${e} = ax${e}y * csn${e}, cqz${e} = ax${e}z * csn${e};\n const cqw${e} = Math.cos(chalf${e});`,body:`if (orbit${e}) {\n let px = Math.fround(pos[o3] - c${e}x), py = Math.fround(pos[o3 + 1] - c${e}y), pz = Math.fround(pos[o3 + 2] - c${e}z);\n // Divided by the squared length as projectOnVector does, so the bits match.\n const f = (ax${e}x * px + ax${e}y * py + ax${e}z * pz) / alen${e};\n const tx = ax${e}x * f, ty = ax${e}y * f, tz = ax${e}z * f;\n let qx, qy, qz, qw;\n if (g${e}_const) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n ${Ki(`g${e}`,"sp","t")}\n const half = (sp * delta) / 2;\n const sn = Math.sin(half);\n qx = ax${e}x * sn; qy = ax${e}y * sn; qz = ax${e}z * sn; qw = Math.cos(half);\n }\n px = Math.fround(px - tx); py = Math.fround(py - ty); pz = Math.fround(pz - tz);\n ${is("px","py","pz","qx","qy","qz","qw")}\n px = Math.fround(Math.fround(px) + tx); py = Math.fround(Math.fround(py) + ty); pz = Math.fround(Math.fround(pz) + tz);\n pos[o3] = px + c${e}x;\n pos[o3 + 1] = py + c${e}y;\n pos[o3 + 2] = pz + c${e}z;}`};case"Rotation3DOverLife":return{setup:`const b${e} = behaviors[${e}];\n const g${e} = b${e}.angularVelocity;\n const q${e} = b${e}.tempQuat;\n const rq${e} = store.rotationQuaternion, aq${e} = store.angularVelocityQuaternion;\n const quat_${e} = rq${e}.length > 0 && count > 0 && particles[0].rotation instanceof deps.Quaternion;\n const fixed_${e} = g${e} instanceof deps.AxisAngleGenerator && g${e}.angle instanceof deps.ConstantValue;\n let cqx${e} = 0, cqy${e} = 0, cqz${e} = 0, cqw${e} = 1;\n if (fixed_${e}) {\n g${e}.genValue(undefined, q${e}, delta, 0);\n cqx${e} = q${e}.x; cqy${e} = q${e}.y; cqz${e} = q${e}.z; cqw${e} = q${e}.w;\n }`,body:`if (quat_${e}) {\n let qx, qy, qz, qw;\n if (fixed_${e}) {\n qx = cqx${e}; qy = cqy${e}; qz = cqz${e}; qw = cqw${e};\n } else {\n g${e}.genValue(p.memory, q${e}, delta, t);\n qx = q${e}.x; qy = q${e}.y; qz = q${e}.z; qw = q${e}.w;\n }\n const ax = rq${e}[o4], ay = rq${e}[o4 + 1], az = rq${e}[o4 + 2], aw = rq${e}[o4 + 3];\n rq${e}[o4] = ax * qw + aw * qx + ay * qz - az * qy;\n rq${e}[o4 + 1] = ay * qw + aw * qy + az * qx - ax * qz;\n rq${e}[o4 + 2] = az * qw + aw * qz + ax * qy - ay * qx;\n rq${e}[o4 + 3] = aw * qw - ax * qx - ay * qy - az * qz;\n aq${e}[o4] = qx; aq${e}[o4 + 1] = qy; aq${e}[o4 + 2] = qz; aq${e}[o4 + 3] = qw;\n }`};case"VelocityOverLife":return{setup:`const b${e} = behaviors[${e}];\n ${Xi(`lx${e}`,`b${e}.linearX`)}\n ${Xi(`ly${e}`,`b${e}.linearY`)}\n ${Xi(`lz${e}`,`b${e}.linearZ`)}\n ${Xi(`ox${e}`,`b${e}.orbitalX`)}\n ${Xi(`oy${e}`,`b${e}.orbitalY`)}\n ${Xi(`oz${e}`,`b${e}.orbitalZ`)}\n ${ns(`aX${e}`,`b${e}._axisX`)}\n ${ns(`aY${e}`,`b${e}._axisY`)}\n ${ns(`aZ${e}`,`b${e}._axisZ`)}\n ${Xi(`rd${e}`,`b${e}.radial`)}\n ${ns(`ce${e}`,`b${e}._center`)}\n const world${e} = b${e}.ps !== undefined && b${e}.ps.worldSpace;\n const toWorld${e} = world${e} && b${e}.space === 'local';\n const convert${e} = toWorld${e} || (!world${e} && b${e}.space === 'world');\n ${ns(`sc${e}`,`toWorld${e} ? b${e}._tempScale : b${e}._tempScaleInv`)}\n ${ss(`q${e}`,`toWorld${e} ? b${e}._tempQ : b${e}._tempQInv`)}`,body:`{\n ${Ki(`lx${e}`,"fx","t")}\n ${Ki(`ly${e}`,"fy","t")}\n ${Ki(`lz${e}`,"fz","t")}\n if (convert${e}) {\n fx *= sc${e}x; fy *= sc${e}y; fz *= sc${e}z;\n ${is("fx","fy","fz",`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n let px = Math.fround(pos[o3] + fx * delta);\n let py = Math.fround(pos[o3 + 1] + fy * delta);\n let pz = Math.fround(pos[o3 + 2] + fz * delta);\n ${Ki(`rd${e}`,"radial","t")}\n if (radial !== 0) {\n // Away from the centre, along the line through the particle.\n const dx = px - ce${e}x, dy = py - ce${e}y, dz = pz - ce${e}z;\n const length = Math.sqrt(dx * dx + dy * dy + dz * dz);\n if (length > 0) {\n const f = (radial * delta) / length;\n px = Math.fround(px + dx * f); py = Math.fround(py + dy * f); pz = Math.fround(pz + dz * f);\n }\n }\n ${Ki(`ox${e}`,"rx","t")}\n ${Ki(`oy${e}`,"ry","t")}\n ${Ki(`oz${e}`,"rz","t")}\n rx *= delta; ry *= delta; rz *= delta;\n if (rx !== 0 || ry !== 0 || rz !== 0) {\n px = Math.fround(px - ce${e}x); py = Math.fround(py - ce${e}y); pz = Math.fround(pz - ce${e}z);\n if (rx !== 0) ${rs("rx",`aX${e}x`,`aX${e}y`,`aX${e}z`)}\n if (ry !== 0) ${rs("ry",`aY${e}x`,`aY${e}y`,`aY${e}z`)}\n if (rz !== 0) ${rs("rz",`aZ${e}x`,`aZ${e}y`,`aZ${e}z`)}\n px = Math.fround(px + ce${e}x); py = Math.fround(py + ce${e}y); pz = Math.fround(pz + ce${e}z);\n }\n pos[o3] = px; pos[o3 + 1] = py; pos[o3 + 2] = pz;}`};case"InheritVelocity":return{setup:`const b${e} = behaviors[${e}];\n const ps${e} = b${e}.ps;\n const ev${e} = b${e}.mode === 'current' && ps${e} !== undefined ? ps${e}.emitterVelocity : undefined;\n const active${e} = ev${e} !== undefined;\n let ivx${e} = 0, ivy${e} = 0, ivz${e} = 0;\n if (active${e}) {\n ivx${e} = ev${e}.x; ivy${e} = ev${e}.y; ivz${e} = ev${e}.z;\n if (!ps${e}.worldSpace) {\n ${ns(`sc${e}`,`b${e}._tempScaleInv`)}\n ${ss(`q${e}`,`b${e}._tempQInv`)}\n ivx${e} *= sc${e}x; ivy${e} *= sc${e}y; ivz${e} *= sc${e}z;\n ${is(`ivx${e}`,`ivy${e}`,`ivz${e}`,`q${e}x`,`q${e}y`,`q${e}z`,`q${e}w`)}\n }\n }\n ${Xi(`gm${e}`,`b${e}.multiplier`)}`,body:`if (active${e}) {\n ${Ki(`gm${e}`,"m","t")}\n const f = m * delta;\n pos[o3] += ivx${e} * f; pos[o3 + 1] += ivy${e} * f; pos[o3 + 2] += ivz${e} * f;\n }`};default:return null}}const as=new Map;function hs(t,e,i){const s=as.get(i);if(void 0!==s)return s??void 0;const n=function(t,e){const i=`\n if (count === 0) return;\n if (store === undefined) {\n store = particles[0].store;\n if (store === undefined) {\n // Particles of some other implementation, without columns: run the behaviors as they are.\n for (const k of [${e.join(", ")}]) {\n const b = behaviors[k];\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n if (p.age < p.life) b.update(p, delta);\n }\n }\n return;\n }\n }\n const pos = store.position, vel = store.velocity;\n const size = store.size, startSize = store.startSize;\n const color = store.color, startColor = store.startColor;\n const scalars = store.scalars;\n const rot = store.rotation, angVel = store.angularVelocity;\n const uvTile = store.uvTile, startSpeed = store.startSpeed;\n const mem = store.memory, ms = store.memoryStride;\n ${t.map(t=>t.setup).join("\n")}\n // The system keeps particles[i] on row i. Anything else (a hand-built\n // list) is caught by its ends and read through each particle's row.\n const mapped = particles[0].storeIndex !== 0 || particles[count - 1].storeIndex !== count - 1;\n for (let i = 0; i < count; i++) {\n const p = particles[i];\n const row = mapped ? p.storeIndex : i;\n const s = row * 3;\n const age = scalars[s], life = scalars[s + 1];\n if (age >= life) continue;\n const t = age / life;\n const o3 = row * 3, o4 = row * 4;\n ${t.map(t=>t.body).join("\n")}\n }`;try{return new Function("deps",`const tmpColor = new deps.Vector4View(new Float32Array(4), 0);\n return function (behaviors, particles, count, delta, store) {${i}};`)(Yi)}catch(t){return}}(t,e);return as.set(i,n??null),n}function ls(t){const e=[];let i=[],s=[],n=[],r=0;const o=()=>{if(0===s.length)return;const t=`${r}:${i.map(t=>t.type).join(",")}`,o=hs(s,n,t);if(void 0!==o)e.push({behaviors:i,run:o});else for(const t of i)e.push({behaviors:[t]});i=[],s=[],n=[]};for(let a=0;a<t.length;a++){const h=t[a],l=os(h,a);null!==l?(0===s.length&&(r=a),i.push(h),s.push(l),n.push(a)):(o(),e.push({behaviors:[h]}))}return o(),e}class cs{constructor(t,e,i){this.position=t??new ht,this.rotation=e??new at,this.scale=i??new ht(1,1,1)}apply(t){t.position.multiply(this.scale).applyQuaternion(this.rotation).add(this.position);const e=t.velocity,i=e.length();if(0===i)return;e.multiply(this.scale).applyQuaternion(this.rotation);const s=e.length();s>0&&e.multiplyScalar(i/s)}isIdentity(){const{position:t,rotation:e,scale:i}=this;return 0===t.x&&0===t.y&&0===t.z&&0===e.x&&0===e.y&&0===e.z&&1===e.w&&1===i.x&&1===i.y&&1===i.z}toJSON(){const t={},{position:e,rotation:i,scale:s}=this;return 0===e.x&&0===e.y&&0===e.z||(t.position=[e.x,e.y,e.z]),0===i.x&&0===i.y&&0===i.z&&1===i.w||(t.rotation=[i.x,i.y,i.z,i.w]),1===s.x&&1===s.y&&1===s.z||(t.scale=[s.x,s.y,s.z]),t}static fromJSON(t){if(!t)return;const{position:e,rotation:i,scale:s}=t;return new cs(e?new ht(e[0],e[1],e[2]):void 0,i?new at(i[0],i[1],i[2],i[3]).normalize():void 0,s?new ht(s[0],s[1],s[2]):void 0)}static toShapeJSON(t){return t&&!t.isIdentity()?{transform:t.toJSON()}:{}}clone(){return new cs(this.position.clone(),this.rotation.clone(),this.scale.clone())}}var us,ds;!function(t){t[t.Volume=0]="Volume",t[t.Shell=1]="Shell",t[t.Edge=2]="Edge"}(us||(us={}));class fs{constructor(t={}){this.type="box",this._point=[0,0,0],this.width=t.width??1,this.height=t.height??1,this.depth=t.depth??1,this.emitFrom=t.emitFrom??us.Volume,this.boxThickness=t.boxThickness?[...t.boxThickness]:[0,0,0],this.transform=t.transform}update(t,e){}initialize(t,e){const i=this._point;for(let t=0;t<3;t++)i[t]=2*T()-1;const s=Math.floor(3*T())%3;this.emitFrom===us.Shell?i[s]=this.onSurface(s):this.emitFrom===us.Edge&&(i[(s+1)%3]=this.onSurface((s+1)%3),i[(s+2)%3]=this.onSurface((s+2)%3)),t.position.set(i[0]*this.width/2,i[1]*this.height/2,i[2]*this.depth/2),t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}onSurface(t){const e=T()<.5?-1:1,i=Math.min(this.boxThickness[t],1);return i<=0||T()<.5?e:e*(1-2*i*T())}toJSON(){return{type:"box",width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:[...this.boxThickness],...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new fs({width:t.width,height:t.height,depth:t.depth,emitFrom:t.emitFrom,boxThickness:Array.isArray(t.boxThickness)?[Number(t.boxThickness[0])||0,Number(t.boxThickness[1])||0,Number(t.boxThickness[2])||0]:void 0,transform:cs.fromJSON(t.transform)})}clone(){return new fs({width:this.width,height:this.height,depth:this.depth,emitFrom:this.emitFrom,boxThickness:this.boxThickness,transform:this.transform?.clone()})}}function ms(t,e,i,s){let n;switch(t){case ds.Loop:n=e-Math.floor(e);break;case ds.PingPong:{const t=e-2*Math.floor(e/2);n=1-Math.abs(t-1);break}case ds.Burst:n=s.isBursting&&s.burstParticleCount>0?s.burstParticleIndex/s.burstParticleCount:T();break;default:n=T()}return i>0&&(n=Math.floor(n/i)*i),n}!function(t){t[t.Random=0]="Random",t[t.Loop=1]="Loop",t[t.PingPong=2]="PingPong",t[t.Burst=3]="Burst"}(ds||(ds={}));class ps{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="circle",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??ds.Random,this.spread=t.spread??0,this.speed=t.speed??new re(1),this.memory=[],this.transform=t.transform}update(t,e){ds.Random!==this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=ms(this.mode,this.currentValue,this.spread,e),s=ei(this.thickness,2),n=i*this.arc;t.position.x=Math.cos(n),t.position.y=Math.sin(n),t.position.z=0,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*s),this.transform?.apply(t)}toJSON(){return{type:"circle",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new ps({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?de(t.speed):void 0,transform:cs.fromJSON(t.transform),spread:t.spread})}clone(){return new ps({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const ys=Math.cos(89*Math.PI/180);var gs,vs;!function(t){t[t.Base=0]="Base",t[t.Volume=1]="Volume"}(gs||(gs={}));class xs{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="cone",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.angle=t.angle??Math.PI/6,this.emitFrom=t.emitFrom??gs.Base,this.length=t.length??5,this.mode=t.mode??ds.Random,this.spread=t.spread??0,this.speed=t.speed??new re(1),this.memory=[],this.transform=t.transform}update(t,e){ds.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=ms(this.mode,this.currentValue,this.spread,e),s=ei(this.thickness,2),n=i*this.arc,r=Math.sin(n),o=Math.cos(n);t.position.x=s*o,t.position.y=s*r,t.position.z=0;const a=Math.min(Math.max(this.angle,0),Math.PI/2),h=s>0?Math.atan(s*Math.tan(a)):0,l=Math.sin(h),c=Math.cos(h);if(t.velocity.set(l*o,l*r,c).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)),this.emitFrom===gs.Volume){const e=Number.isFinite(this.length)?Math.max(0,this.length):0,i=T()*e/Math.max(c,ys);t.position.x+=l*o*i,t.position.y+=l*r*i,t.position.z=c*i}this.transform?.apply(t)}toJSON(){return{type:"cone",radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,emitFrom:this.emitFrom,length:this.length,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new xs({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,emitFrom:t.emitFrom,length:t.length,mode:t.mode,speed:t.speed?de(t.speed):void 0,transform:cs.fromJSON(t.transform),spread:t.spread})}clone(){return new xs({radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,emitFrom:this.emitFrom,length:this.length,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class Ss{constructor(t={}){this.type="donut",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.donutRadius=t.donutRadius??.2*this.radius,this.mode=t.mode??ds.Random,this.spread=t.spread??0,this.speed=t.speed??new re(1),this.memory=[],this.transform=t.transform,this._m1=new ft}reset(){this.currentValue=0,this.memory.length=0}update(t,e){ds.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=ms(this.mode,this.currentValue,this.spread,e),s=T(),n=ei(this.thickness,2),r=i*this.arc,o=s*Math.PI*2,a=Math.sin(r),h=Math.cos(r),l=Math.max(0,this.radius),c=Math.max(0,this.donutRadius)*n;if(t.velocity.set(Math.cos(o)*h,Math.cos(o)*a,Math.sin(o)),t.position.set(l*h,l*a,0).addScaledVector(t.velocity,c),t.velocity.multiplyScalar(t.startSpeed),t.rotation instanceof at){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(si,t.velocity,ii),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"donut",radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new Ss({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?de(t.speed):void 0,transform:cs.fromJSON(t.transform),spread:t.spread})}clone(){return new Ss({radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class bs{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="edge",this.currentValue=0,this.radius=t.radius??1,this.mode=t.mode??ds.Random,this.spread=t.spread??0,this.speed=t.speed??new re(1),this.memory=[],this.transform=t.transform}update(t,e){ds.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=ms(this.mode,this.currentValue,this.spread,e);t.position.set((2*i-1)*this.radius,0,0),t.velocity.set(0,t.startSpeed,0),this.transform?.apply(t)}toJSON(){return{type:"edge",radius:this.radius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new bs({radius:t.radius,mode:t.mode,speed:t.speed?de(t.speed):void 0,spread:t.spread,transform:cs.fromJSON(t.transform)})}clone(){return new bs({radius:this.radius,mode:this.mode,speed:this.speed.clone(),spread:this.spread,transform:this.transform?.clone()})}}!function(t){t[t.Random=0]="Random",t[t.Sequential=1]="Sequential"}(vs||(vs={}));class ws{constructor(t={}){this.type="grid",this.nextCell=0,this.width=t.width??1,this.height=t.height??1,this.column=t.column??10,this.row=t.row??10,this.sampling=t.sampling??vs.Random,this.transform=t.transform}initialize(t){const e=Number.isFinite(this.row)?Math.max(1,Math.floor(this.row)):1,i=Number.isFinite(this.column)?Math.max(1,Math.floor(this.column)):1;let s,n;if(this.sampling===vs.Sequential){const t=this.nextCell%(e*i);this.nextCell=t+1,s=Math.floor(t/i),n=t%i}else s=Math.floor(T()*e),n=Math.floor(T()*i);t.position.x=((n+.5)/i-.5)*this.width,t.position.y=((s+.5)/e-.5)*this.height,t.position.z=0,t.velocity.set(0,0,t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"grid",width:this.width,height:this.height,column:this.column,row:this.row,sampling:this.sampling,...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new ws({width:t.width,height:t.height,column:t.column,row:t.row,sampling:t.sampling,transform:cs.fromJSON(t.transform)})}clone(){return new ws({width:this.width,height:this.height,column:this.column,row:this.row,sampling:this.sampling,transform:this.transform?.clone()})}update(t,e){}reset(){this.nextCell=0}}class Ms{constructor(t={}){this.type="hemisphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??ds.Random,this.spread=t.spread??0,this.speed=t.speed??new re(1),this.memory=[],this.transform=t.transform,this._m1=new ft}reset(){this.currentValue=0,this.memory.length=0}update(t,e){ds.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=ms(this.mode,this.currentValue,this.spread,e),s=T(),n=ei(this.thickness,3),r=i*this.arc,o=Math.acos(s),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*n),t.rotation instanceof at){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(si,t.position,ii),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"hemisphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new Ms({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?de(t.speed):void 0,transform:cs.fromJSON(t.transform),spread:t.spread})}clone(){return new Ms({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class zs{constructor(t){this.type="point",this._m1=new ft,this.transform=t}update(t,e){}initialize(t){const e=T(),i=T(),s=e*Math.PI*2,n=2*i-1,r=Math.sqrt(Math.max(0,1-n*n));if(t.velocity.x=r*Math.cos(s),t.velocity.y=r*Math.sin(s),t.velocity.z=n,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof at){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(si,t.velocity,ii),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"point",...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new zs(cs.fromJSON(t?.transform))}clone(){return new zs(this.transform?.clone())}}class _s{constructor(t={}){this.type="sphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??ds.Random,this.spread=t.spread??0,this.speed=t.speed??new re(1),this.memory=[],this.transform=t.transform,this._m1=new ft}reset(){this.currentValue=0,this.memory.length=0}update(t,e){ds.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=ms(this.mode,this.currentValue,this.spread,e),s=T(),n=ei(this.thickness,3),r=i*this.arc,o=Math.acos(2*s-1),a=Math.sin(r),h=Math.cos(r),l=Math.sin(o),c=Math.cos(o);if(t.position.x=l*h,t.position.y=l*a,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(Math.max(0,this.radius)*n),t.rotation instanceof at){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(si,t.position,ii),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"sphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new _s({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?de(t.speed):void 0,transform:cs.fromJSON(t.transform),spread:t.spread})}clone(){return new _s({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}class As{reset(){this.currentValue=0,this.memory.length=0}constructor(t={}){this.type="rectangle",this.currentValue=0,this.width=t.width??10,this.height=t.height??10,this.thickness=t.thickness??1,this.mode=t.mode??ds.Random,this.spread=t.spread??0,this.speed=t.speed??new re(1),this.memory=[],this.transform=t.transform,this._m1=new ft}update(t,e){ds.Random!==this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=ms(this.mode,this.currentValue,this.spread,e);T();const s=Math.max(0,this.width),n=Math.max(0,this.height),r=2*i*(s+n);let o,a,h,l;r<s?(o=r-s/2,a=-n/2,h=0,l=-1):r<s+n?(o=s/2,a=r-s-n/2,h=1,l=0):r<2*s+n?(o=s/2-(r-s-n),a=n/2,h=0,l=1):(o=-s/2,a=n/2-(r-2*s-n),h=-1,l=0);const c=ei(this.thickness,2);if(t.position.set(o*c,a*c,0),0===o&&0===a?t.velocity.set(h,l,0):t.velocity.set(o,a,0).normalize(),t.velocity.multiplyScalar(t.startSpeed),t.rotation instanceof at){const e=t.rotation;0===e.x&&0===e.y&&0===e.z&&1===e.w&&(this._m1.lookAt(si,t.velocity,ii),t.rotation.setFromRotationMatrix(this._m1))}this.transform?.apply(t)}toJSON(){return{type:"rectangle",width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON(),...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new As({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?de(t.speed):void 0,transform:cs.fromJSON(t.transform),spread:t.spread})}clone(){return new As({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),transform:this.transform?.clone(),spread:this.spread})}}const Ps={box:{type:"box",params:[["width",["number"]],["height",["number"]],["depth",["number"]],["emitFrom",["boxEmitFrom"]],["boxThickness",["vec3"]],["transform",["shapeTransform"]]],constructor:fs,loadJSON:fs.fromJSON},circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:ps,loadJSON:ps.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["emitFrom",["coneEmitFrom"]],["length",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:xs,loadJSON:xs.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:Ss,loadJSON:Ss.fromJSON},edge:{type:"edge",params:[["radius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:bs,loadJSON:bs.fromJSON},point:{type:"point",params:[["transform",["shapeTransform"]]],constructor:zs,loadJSON:zs.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:_s,loadJSON:_s.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:Ms,loadJSON:Ms.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["column",["number"]],["row",["number"]],["sampling",["gridSampling"]],["transform",["shapeTransform"]]],constructor:ws,loadJSON:ws.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]],["transform",["shapeTransform"]]],constructor:As,loadJSON:As.fromJSON}};function Os(t,e){const i=t?Ps[t.type]:void 0;return i?i.loadJSON(t,e):(te(`${ie("emitter shape",t)}; using a point emitter.`),new zs)}function Ts(t,e={}){const i=t.toJSON(),s=Ps[i?.type];return s?ne(i,t=>s.loadJSON(t,e).toJSON()):i}const Vs=[];function Es(t){if(!Vs.find(e=>e.id===t.id)){t.initialize(),Vs.push(t);for(const e of t.emitterShapes)Ps[e.type]||(Ps[e.type]=e);for(const e of t.behaviors)ji[e.type]||(ji[e.type]=e)}}function $s(t){const e=Vs.findIndex(e=>e.id===t);if(e<0)return;const i=Vs[e];Vs.splice(e,1);for(const t of i.emitterShapes)Ps[t.type]===t&&delete Ps[t.type];for(const t of i.behaviors)ji[t.type]===t&&delete ji[t.type]}function Cs(t,e){if(e&&e.length>0)return e;const i=t.length/3,s=new Uint32Array(i);for(let t=0;t<i;t++)s[t]=t;return s}const Is=new WeakMap;function Ns(t){let i=Is.get(t);return void 0===i&&(i=e(),Is.set(t,i)),i}function Fs(t){return Is.get(t)}class Bs{get mesh(){return this._mesh}set mesh(e){if(this._mesh=e,this._positions=void 0,this._indices=void 0,this._triangleIndexToArea.length=0,!e)return;const i=e.getVerticesData(t.PositionKind);if(!i||i.length<9)return;const s=new Float32Array(i),n=e.getIndices(),r=Cs(s,n&&n.length>0?Uint32Array.from(n):void 0),o=Math.floor(r.length/3);if(0===o)return;this._positions=s,this._indices=new Int32Array(r.subarray(0,3*o));let a=0;this._triangleIndexToArea.push(0);const h=new ht,l=new ht,c=new ht,u=new ht;for(let t=0;t<o;t++){const e=r[3*t],s=r[3*t+1],n=r[3*t+2];h.set(i[3*e],i[3*e+1],i[3*e+2]),l.set(i[3*s],i[3*s+1],i[3*s+2]),c.set(i[3*n],i[3*n+1],i[3*n+2]),l.sub(h),c.sub(h),u.crossVectors(l,c),a+=.5*u.length(),this._triangleIndexToArea.push(a)}}constructor(t,e,i){this.type="mesh_surface",this._triangleIndexToArea=[],this._meshReferenceId=e,this.transform=i,t&&(this.mesh=t)}initialize(t){if(!this._positions||!this._indices)return t.position.set(0,0,0),t.velocity.set(0,0,1).multiplyScalar(t.startSpeed),void this.transform?.apply(t);const e=this._triangleIndexToArea.length-1;let i=0,s=e;const n=T()*this._triangleIndexToArea[e];for(;i+1<s;){const t=Math.floor((i+s)/2);n<this._triangleIndexToArea[t]?s=t:i=t}let r=T(),o=T();r+o>1&&(r=1-r,o=1-o);const a=this._indices[3*i],h=this._indices[3*i+1],l=this._indices[3*i+2],c=this._positions[3*a],u=this._positions[3*a+1],d=this._positions[3*a+2],f=this._positions[3*h]-c,m=this._positions[3*h+1]-u,p=this._positions[3*h+2]-d,y=this._positions[3*l]-c,g=this._positions[3*l+1]-u,v=this._positions[3*l+2]-d;t.position.set(c+f*r+y*o,u+m*r+g*o,d+p*r+v*o);const x=m*v-p*g,S=p*y-f*v,b=f*g-m*y,w=Math.sqrt(x*x+S*S+b*b)||1;t.velocity.set(x/w,S/w,b/w).multiplyScalar(t.startSpeed),this.transform?.apply(t)}toJSON(){return{type:"mesh_surface",mesh:this._mesh?Ns(this._mesh):this._meshReferenceId??"",...cs.toShapeJSON(this.transform)}}static fromJSON(t){return new Bs(void 0,t?.mesh,cs.fromJSON(t?.transform))}clone(){return new Bs(this._mesh,this._meshReferenceId,this.transform?.clone())}update(t,e){}}const Us={id:"babylon.quarks",initialize:()=>{},emitterShapes:[{type:"mesh_surface",params:[["mesh",["mesh"]]],constructor:Bs,loadJSON:t=>Bs.fromJSON(t)}],behaviors:[]};var Rs;function Ls(){return{direction:new a(.4,-1,.6),color:new o(1,1,1),ambient:new o(.35,.35,.35)}}function Ds(t){if(!t||"object"!=typeof t)return;const e=Array.isArray(t.color)?t.color:[1,1,1],i=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e;return{color:[i(e[0],1),i(e[1],1),i(e[2],1)],power:Math.max(.01,i(t.power,2)),strength:Math.max(0,i(t.strength,1)),mode:"mix"===t.mode||"fade"===t.mode?t.mode:"add"}}function ks(t,e){return t===e||!(!t||!e)&&(t.mode===e.mode&&t.power===e.power&&t.strength===e.strength&&t.color[0]===e.color[0]&&t.color[1]===e.color[1]&&t.color[2]===e.color[2])}function qs(t,e={}){const i=t&&"object"==typeof t?t:{},s=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,n=(t,e)=>Array.isArray(t)?[s(t[0],e[0]),s(t[1],e[1])]:[e[0],e[1]];return{channel:1===(i.channel??e.channel)?1:0,tiling:n(i.tiling,e.tiling??[1,1]),offset:n(i.offset,e.offset??[0,0]),scroll:n(i.scroll,e.scroll??[0,0])}}function Js(t,e){return t===e||t.channel===e.channel&&t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]}function Gs(t,e={}){const i=qs(void 0,e),s={};return t.channel!==i.channel&&(s.channel=t.channel),t.tiling[0]===i.tiling[0]&&t.tiling[1]===i.tiling[1]||(s.tiling=[...t.tiling]),t.offset[0]===i.offset[0]&&t.offset[1]===i.offset[1]||(s.offset=[...t.offset]),t.scroll[0]===i.scroll[0]&&t.scroll[1]===i.scroll[1]||(s.scroll=[...t.scroll]),Object.keys(s).length>0?s:void 0}!function(t){t[t.BillBoard=0]="BillBoard",t[t.StretchedBillBoard=1]="StretchedBillBoard",t[t.Mesh=2]="Mesh",t[t.Trail=3]="Trail",t[t.HorizontalBillBoard=4]="HorizontalBillBoard",t[t.VerticalBillBoard=5]="VerticalBillBoard",t[t.Beam=6]="Beam"}(Rs||(Rs={}));const Ws={r:[1,0,0,0],g:[0,1,0,0],b:[0,0,1,0],a:[0,0,0,1],luminance:[.2126,.7152,.0722,0]};function js(t){if(!t||"object"!=typeof t||!t.ramp)return;const e=t.channel;return{ramp:t.ramp,channel:void 0!==e&&e in Ws?e:"r"}}function Qs(t,e){return t===e||!!t&&!!e&&t.ramp===e.ramp&&t.channel===e.channel}const Hs=.05;function Ys(t){if(!t||"object"!=typeof t)return;const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?t:e,i=Array.isArray(t.edgeColor)?t.edgeColor:[1,1,1];return{mask:t.mask??null,maskUV:qs(t.maskUV),softness:Math.max(1e-4,e(t.softness,Hs)),edgeWidth:Math.max(0,e(t.edgeWidth,0)),edgeColor:[e(i[0],1),e(i[1],1),e(i[2],1)]}}function Xs(t,e){return t===e||!(!t||!e)&&(t.mask===e.mask&&Js(t.maskUV,e.maskUV)&&t.softness===e.softness&&t.edgeWidth===e.edgeWidth&&t.edgeColor[0]===e.edgeColor[0]&&t.edgeColor[1]===e.edgeColor[1]&&t.edgeColor[2]===e.edgeColor[2])}const Zs={scroll:[0,.5]},Ks=.05;function tn(t){if(!t||"object"!=typeof t||!t.map)return;const e=t.strength;return{map:t.map,mapUV:qs(t.mapUV,Zs),strength:Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:Ks)}}function en(t,e){return t===e||!(!t||!e)&&(t.map===e.map&&t.strength===e.strength&&Js(t.mapUV,e.mapUV))}function sn(t){if(!t||"object"!=typeof t)return;const e=qs(t);return void 0===Gs(e)?void 0:e}function nn(t,e){return t===e||!!t&&!!e&&Js(t,e)}function rn(t){const{mapUV:e,uvDistortion:i,erosion:s}=t;return 1===e?.channel||1===i?.mapUV.channel||!!s?.mask&&1===s.maskUV.channel}function on(t){return"unlit"===t||"scene"===t?t:"fixed"}function an(t){return"distance"===t||"oldestInFront"===t||"youngestInFront"===t?t:"none"}function hn(t){return"front"===t||"back"===t?t:"both"}function ln(t){return"pause"===t||"pauseAndCatchUp"===t?t:"always"}function cn(t){return"disable"===t||"destroy"===t?t:"none"}function un(t){return"pauseUntilReplaced"===t||"loopUntilReplaced"===t?t:"disabled"}function dn(t){const e=(t,e)=>"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e,i=e(t?.x,0),s=e(t?.y,1);return new Tt(Math.min(i,s),Math.max(i,s))}function fn(t){return"hierarchy"===t||"shape"===t?t:"local"}function mn(t){return!t||0===t.x&&0===t.y&&0===t.z?void 0:t.clone()}function pn(t){return"number"==typeof t&&t>0?Math.min(t,1):0}function yn(t){return"number"==typeof t&&Number.isFinite(t)&&t>=1?Math.floor(t):1}function gn(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:e}function vn(t){const e=t.count,i="number"==typeof t.time&&Number.isFinite(t.time)&&t.time>0?t.time:0,s="number"==typeof t.cycle&&Number.isFinite(t.cycle)&&t.cycle>=1?t.cycle:1,n="number"==typeof t.interval&&Number.isFinite(t.interval)?Math.max(0,t.interval):.1,r="number"==typeof t.probability&&Number.isFinite(t.probability)?Math.min(1,Math.max(0,t.probability)):1;return{time:i,count:"number"==typeof e?new re(e):null!=e?e:new re(0),cycle:s,interval:n,probability:r}}function xn(t){return(t??[]).map(vn).sort((t,e)=>t.time-e.time)}const Sn=new Float32Array(0),bn=new Uint16Array(0);function wn(t){return t===Rs.BillBoard||t===Rs.StretchedBillBoard||t===Rs.VerticalBillBoard||t===Rs.HorizontalBillBoard}function Mn(t){return t.uTileCount>1||t.vTileCount>1}function zn(t){return t.minParticleSize>0||t.maxParticleSize!==1/0}function _n(t){const e=t.renderMode,i=e===Rs.Mesh,s=e===Rs.Trail,n=wn(e),o=t.softParticles,a=t.materialTransparent,h=t.pivot,l=sn(t.mapUV),c=tn(t.uvDistortion),u=js(t.gradientMap),d=Ys(t.erosion),f=yn(t.uTileCount),m=yn(t.vTileCount);var p;return{renderMode:e,instancingGeometry:s?Sn:t.instancingGeometry,instancingIndices:s?bn:t.instancingIndices,instancingUVs:s?void 0:t.instancingUVs,instancingUVs2:i&&rn({mapUV:l,uvDistortion:c,erosion:d})?t.instancingUVs2:void 0,instancingNormals:i?t.instancingNormals:void 0,renderOrder:t.renderOrder,uTileCount:f,vTileCount:m,blendTiles:!s&&t.blendTiles&&Mn({uTileCount:f,vTileCount:m}),softParticles:o,softNearFade:o?gn(t.softNearFade,0):0,softFarFade:o?gn(t.softFarFade,1):0,materialBlendMode:a?t.materialBlendMode:r.ALPHA_DISABLE,materialTransparent:a,materialDepthTest:t.materialDepthTest,materialDepthWrite:t.materialDepthWrite,materialAlphaTest:t.materialAlphaTest>0?t.materialAlphaTest:0,texture:t.texture,reflectionTexture:i?t.reflectionTexture??null:null,reflectionLevel:i?t.reflectionLevel??1:1,reflectionAtlas:i?t.reflectionAtlas??null:null,layerMask:t.layerMask,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,applyImageProcessing:t.applyImageProcessing??!0,pivot:n&&h&&(0!==h.x||0!==h.y||0!==h.z)?h.clone():void 0,sortMode:t.sortMode??"none",renderFace:i?hn(t.renderFace):"both",minParticleSize:n?Math.max(0,t.minParticleSize??0):0,maxParticleSize:n?(p=t.maxParticleSize,void 0!==p&&p>0?p:1/0):1/0,lighting:i?t.lighting??"fixed":"fixed",rim:i?Ds(t.rim):void 0,mapUV:l,uvDistortion:c,gradientMap:u,erosion:d}}function An(t,e){return t.renderMode===e.renderMode&&t.instancingGeometry===e.instancingGeometry&&t.instancingIndices===e.instancingIndices&&t.instancingUVs===e.instancingUVs&&t.instancingUVs2===e.instancingUVs2&&t.instancingNormals===e.instancingNormals&&t.texture===e.texture&&t.reflectionTexture===e.reflectionTexture&&t.reflectionAtlas===e.reflectionAtlas&&t.lighting===e.lighting&&t.rim?.mode===e.rim?.mode&&t.uTileCount===e.uTileCount&&t.vTileCount===e.vTileCount&&t.blendTiles===e.blendTiles&&t.softParticles===e.softParticles&&t.materialBlendMode===e.materialBlendMode&&t.materialTransparent===e.materialTransparent&&t.materialDepthTest===e.materialDepthTest&&t.materialDepthWrite===e.materialDepthWrite&&t.materialAlphaTest>0==e.materialAlphaTest>0&&t.layerMask===e.layerMask&&t.renderingGroupId===e.renderingGroupId&&t.renderOrder===e.renderOrder&&t.applyFog===e.applyFog&&t.applyImageProcessing===e.applyImageProcessing&&t.sortMode===e.sortMode&&t.renderFace===e.renderFace&&!t.pivot==!e.pivot&&zn(t)===zn(e)&&t.mapUV?.channel===e.mapUV?.channel&&t.uvDistortion?.map===e.uvDistortion?.map&&t.uvDistortion?.mapUV.channel===e.uvDistortion?.mapUV.channel&&!t.gradientMap==!e.gradientMap&&t.gradientMap?.ramp===e.gradientMap?.ramp&&!t.erosion==!e.erosion&&t.erosion?.mask===e.erosion?.mask&&t.erosion?.maskUV.channel===e.erosion?.maskUV.channel}function Pn(t,e){return t.softNearFade===e.softNearFade&&t.softFarFade===e.softFarFade&&t.materialAlphaTest===e.materialAlphaTest&&t.reflectionLevel===e.reflectionLevel&&function(t,e){return(t?.x??0)===(e?.x??0)&&(t?.y??0)===(e?.y??0)&&(t?.z??0)===(e?.z??0)}(t.pivot,e.pivot)&&t.minParticleSize===e.minParticleSize&&t.maxParticleSize===e.maxParticleSize&&function(t,e){if(!t||!e)return!t==!e;return t.power===e.power&&t.strength===e.strength&&Tn(t.color,e.color)}(t.rim,e.rim)&&Vn(t.mapUV,e.mapUV)&&t.uvDistortion?.strength===e.uvDistortion?.strength&&Vn(t.uvDistortion?.mapUV,e.uvDistortion?.mapUV)&&t.gradientMap?.channel===e.gradientMap?.channel&&t.erosion?.softness===e.erosion?.softness&&t.erosion?.edgeWidth===e.erosion?.edgeWidth&&Tn(t.erosion?.edgeColor,e.erosion?.edgeColor)&&Vn(t.erosion?.maskUV,e.erosion?.maskUV)}function On(t,e){return An(t,e)&&Pn(t,e)}function Tn(t,e){return t&&e?t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]:!t==!e}function Vn(t,e){return t&&e?t.tiling[0]===e.tiling[0]&&t.tiling[1]===e.tiling[1]&&t.offset[0]===e.offset[0]&&t.offset[1]===e.offset[1]&&t.scroll[0]===e.scroll[0]&&t.scroll[1]===e.scroll[1]:!t==!e}function En(t,e={}){const i=function(t,e){if(i=t,"function"==typeof i?.getDepthMap){const i=t,s=i._storeCameraSpaceZ?"viewZ":i._storeNonLinearDepth?"nonLinear":"linear";return{texture:t.getDepthMap(),encoding:e.encoding??s,packed:e.packed??t.isPacked}}var i;return{texture:t,encoding:e.encoding??"linear",packed:e.packed??!1}}(t,e);if(i.packed&&"viewZ"===i.encoding)throw new Error("[babylon.quarks] A packed view-Z depth cannot be decoded; use a float depth texture");return i}function $n(t,e,i){if("viewZ"===e)return i.set(1,0,0,1);const s=t.getEngine(),n=s.useReverseDepthBuffer,r=s.isNDCHalfZRange,o=t.getProjectionMatrix().m,a=o[10],h=o[11],l=o[14],c=o[15];if("linear"===e){let e,s;t.mode===d.ORTHOGRAPHIC_CAMERA?(e=!n&&r?0:1,s=n&&r?0:1):(e=n&&r?t.minZ:r?0:t.minZ,s=n&&r?0:t.maxZ);const o=n?-1:1,h=e+s;return i.set(o*h/a,(-o*e-l)/a,0,1)}const u=r?1:2,f=r?0:-1;return i.set(-u*c,l-f*c,u*h,f*h-a)}function Cn(t,e){const i=e.z*t+e.w,s=Math.abs(i)>1e-8?Math.abs((e.x*t+e.y)/i):0;return s>0?s:1e30}const In=2048,Nn=2047;class Fn{constructor(t){this.counts=new Uint32Array(In),this.floatView=new Float32Array(1),this.uintView=new Uint32Array(this.floatView.buffer),this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t)}ensure(t){this.keys.length<t&&(this.keys=new Uint32Array(t),this.orderA=new Uint32Array(t),this.orderB=new Uint32Array(t))}floatKey(t,e){this.floatView[0]=t;const i=this.uintView[0];return e?~i>>>0:i}}const Bn="\n#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";function Un(t){return`\n#ifdef FOG\n vFogDistance = ${t};\n#endif\n`}const Rn="\n#ifdef FOG\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\n\nfloat quarksFogFactor() {\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n float fogDistance = length(vFogDistance);\n if (vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n";function Ln(t){return`\n#ifdef FOG\n {\n float fogFactor = quarksFogFactor();\n#if defined(FOG_ADDITIVE)\n ${t} *= fogFactor;\n#elif defined(FOG_MULTIPLY)\n ${t} = mix(vec3(1.0), ${t}, fogFactor);\n#else\n ${t} = mix(vFogColor, ${t}, fogFactor);\n#endif\n }\n#endif\n`}const Dn="\n#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";function kn(t){return`\n#ifdef FOG\n vertexOutputs.vFogDistance = ${t};\n#endif\n`}const qn="\n#ifdef FOG\nuniform vFogInfos: vec4f;\nuniform vFogColor: vec3f;\nvarying vFogDistance: vec3f;\n\nfn quarksFog(rgb: vec3f, fogDistanceVector: vec3f) -> vec3f {\n var fogCoeff = 1.0;\n let fogStart = uniforms.vFogInfos.y;\n let fogEnd = uniforms.vFogInfos.z;\n let fogDensity = uniforms.vFogInfos.w;\n let fogDistance = length(fogDistanceVector);\n if (uniforms.vFogInfos.x == 3.0) {\n // A zero-width band is a cut at its distance, not a division by zero.\n fogCoeff = (fogEnd - fogDistance) / max(fogEnd - fogStart, 1e-6);\n } else if (uniforms.vFogInfos.x == 1.0) {\n fogCoeff = exp(-fogDistance * fogDensity);\n } else if (uniforms.vFogInfos.x == 2.0) {\n fogCoeff = exp(-fogDistance * fogDistance * fogDensity * fogDensity);\n }\n let fogFactor = clamp(fogCoeff, 0.0, 1.0);\n#if defined(FOG_ADDITIVE)\n return rgb * fogFactor;\n#elif defined(FOG_MULTIPLY)\n return mix(vec3f(1.0), rgb, fogFactor);\n#else\n return mix(uniforms.vFogColor, rgb, fogFactor);\n#endif\n}\n#endif\n";function Jn(t){return`\n#ifdef FOG\n ${t} = vec4f(quarksFog(${t}.rgb, fragmentInputs.vFogDistance), ${t}.a);\n#endif\n`}function Gn(t,e,i){const s=e*i,n=Wn(Math.floor(t),s);return{column:Wn(n,e),row:Math.floor(n/e)}}function Wn(t,e){return t-e*Math.floor(t/e)}const jn="\n#ifdef UV_TILE\nuniform float tileCountX;\nuniform float tileCountY;\n#endif\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n";function Qn(t){return`\n#ifdef UV_TILE\n {\n vec2 tc = vec2(tileCountX, tileCountY);\n float tileTotal = tc.x * tc.y;\n float baseTile = mod(floor(uvTile), tileTotal);\n vec2 tileUV = vec2(mod(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n float nextTile = mod(baseTile + 1.0, tileTotal);\n vec2 nextUV = vec2(mod(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vUV2 = ${t} / tc + nextUV;\n vTileBlend = fract(uvTile);\n#endif\n }\n#else\n vUV = ${t};\n#endif\n`}const Hn="\n#ifdef UV_TILE\nuniform tileCountX: f32;\nuniform tileCountY: f32;\n\n// A floored modulo, as GLSL's mod: never negative for a positive divisor.\nfn quarksWrap(value: f32, divisor: f32) -> f32 {\n return value - divisor * floor(value / divisor);\n}\n#endif\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n";function Yn(t){return`\n#ifdef UV_TILE\n {\n let tc = vec2f(uniforms.tileCountX, uniforms.tileCountY);\n let tileTotal = tc.x * tc.y;\n let baseTile = quarksWrap(floor(vertexInputs.uvTile), tileTotal);\n let tileUV = vec2f(quarksWrap(baseTile, tc.x), tc.y - 1.0 - floor(baseTile / tc.x)) / tc;\n vertexOutputs.vUV = ${t} / tc + tileUV;\n#ifdef TILE_BLEND\n let nextTile = quarksWrap(baseTile + 1.0, tileTotal);\n let nextUV = vec2f(quarksWrap(nextTile, tc.x), tc.y - 1.0 - floor(nextTile / tc.x)) / tc;\n vertexOutputs.vUV2 = ${t} / tc + nextUV;\n vertexOutputs.vTileBlend = fract(vertexInputs.uvTile);\n#endif\n }\n#else\n vertexOutputs.vUV = ${t};\n#endif\n`}var Xn=`\nattribute vec3 position;\nattribute vec2 uv;\nattribute vec3 normal;\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute vec4 rotation;\nattribute float uvTile;\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${jn}\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute vec2 uv2;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\nvec3 applyQuaternion(vec3 v, vec4 q) {\n vec3 qVec = q.xyz;\n float qW = q.w;\n vec3 t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${Bn}\nvoid main() {\n vec3 scaledPosition = position * size;\n vec3 rotatedPosition = applyQuaternion(scaledPosition, rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n vec3 safeSize = vec3(\n abs(size.x) > 1e-6 ? size.x : 1e-6,\n abs(size.y) > 1e-6 ? size.y : 1e-6,\n abs(size.z) > 1e-6 ? size.z : 1e-6);\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n vec3 rotatedNormal = normalize(applyQuaternion(normal / safeSize, rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n vec3 localPos = rotatedPosition + offset;\n\n vec4 worldPos = world * vec4(localPos, 1.0);\n vec4 viewPos = view * worldPos;\n gl_Position = projection * viewPos;\n${Un("viewPos.xyz")}\n\n vWorldPos = worldPos.xyz;\n vNormal = normalize((world * vec4(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(viewPos.z);\n#endif\n\n${Qn("uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vUV1 = uv2;\n#else\n vUV1 = uv;\n#endif\n#endif\n vColor = color;\n}\n`,Zn=`\nattribute position: vec3f;\nattribute uv: vec2f;\nattribute normal: vec3f;\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: vec4f;\nattribute uvTile: f32;\n\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${Hn}\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n#ifdef MESH_UV2\n// The mesh's second UV set.\nattribute uv2: vec2f;\n#endif\n// UV channel 1: the mesh's second UV set, or its first when it has none.\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\nfn applyQuaternion(v: vec3f, q: vec4f) -> vec3f {\n let qVec = q.xyz;\n let qW = q.w;\n let t = 2.0 * cross(qVec, v);\n return v + qW * t + cross(qVec, t);\n}\n\n${Dn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let size = vertexInputs.size;\n let scaledPosition = vertexInputs.position * size;\n let rotatedPosition = applyQuaternion(scaledPosition, vertexInputs.rotation);\n // A normal scales by the inverse of the size, so a stretched mesh keeps its normals\n // perpendicular; a flat size counts as a sliver rather than dividing by zero.\n let safeSize = vec3f(\n select(1e-6, size.x, abs(size.x) > 1e-6),\n select(1e-6, size.y, abs(size.y) > 1e-6),\n select(1e-6, size.z, abs(size.z) > 1e-6));\n // A mirrored size (an odd number of negative components) turns the winding inside out, so the\n // normal is turned with it and the fragment's front-face test agrees with the geometry.\n let rotatedNormal = normalize(applyQuaternion(vertexInputs.normal / safeSize, vertexInputs.rotation)) * sign(safeSize.x * safeSize.y * safeSize.z);\n let localPos = rotatedPosition + vertexInputs.offset;\n\n let worldPos = uniforms.world * vec4f(localPos, 1.0);\n let viewPos = uniforms.view * worldPos;\n let clipPosition = uniforms.projection * viewPos;\n vertexOutputs.position = clipPosition;\n${kn("viewPos.xyz")}\n\n vertexOutputs.vWorldPos = worldPos.xyz;\n vertexOutputs.vNormal = normalize((uniforms.world * vec4f(rotatedNormal, 0.0)).xyz);\n\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(viewPos.z);\n#endif\n\n${Yn("vertexInputs.uv")}\n\n#ifdef UV1\n#ifdef MESH_UV2\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#else\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;const Kn="textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb",tr=x.IncludesShadersStoreWGSL.imageProcessingFunctions,er=tr.includes(Kn);x.IncludesShadersStoreWGSL.quarksImageProcessingFunctions=er?"\n#if defined(COLORGRADING) && !defined(COLORGRADING3D)\nfn quarksSampleTexture3D(colorTransform: texture_2d<f32>, colorTransformSampler: sampler, colorIn: vec3f, sampler3dSetting: vec2f) -> vec3f {\n let sliceSize = 2.0 * sampler3dSetting.x;\n#ifdef SAMPLER3DGREENDEPTH\n let sliceContinuous = (colorIn.g - sampler3dSetting.x) * sampler3dSetting.y;\n var sliceUV = colorIn.rb;\n#else\n let sliceContinuous = (colorIn.b - sampler3dSetting.x) * sampler3dSetting.y;\n var sliceUV = colorIn.rg;\n#endif\n let sliceInteger = floor(sliceContinuous);\n let sliceFraction = sliceContinuous - sliceInteger;\n sliceUV.x = sliceUV.x * sliceSize + sliceInteger * sliceSize;\n let slice0Color = textureSample(colorTransform, colorTransformSampler, clamp(sliceUV, vec2f(0.0), vec2f(1.0)));\n let slice1Color = textureSample(colorTransform, colorTransformSampler, clamp(sliceUV + vec2f(sliceSize, 0.0), vec2f(0.0), vec2f(1.0)));\n let result = mix(slice0Color.rgb, slice1Color.rgb, sliceFraction);\n#ifdef SAMPLER3DBGRMAP\n return result.rgb;\n#else\n return result.bgr;\n#endif\n}\n#endif\n"+tr.replace(Kn,"quarksSampleTexture3D(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz)"):tr;const ir="\n#if defined(IMAGEPROCESSING) || defined(IMAGEPROCESSINGPOSTPROCESS)\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#endif\n";const sr="\n#if defined(IMAGEPROCESSING) || defined(IMAGEPROCESSINGPOSTPROCESS)\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<quarksImageProcessingFunctions>\n#endif\n";function nr(t){return`${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && !defined(BLEND_MULTIPLY)\n ${t}.rgb = toLinearSpace(${t}.rgb);\n#elif defined(IMAGEPROCESSING)\n ${t}.rgb = toLinearSpace(${t}.rgb);\n ${t} = applyImageProcessing(${t});\n#endif\n`}(t)}\n#if defined(BLEND_PREMULTIPLY)\n ${t}.rgb *= ${t}.a;\n#elif defined(BLEND_MULTIPLY)\n ${t}.rgb = mix(vec3(1.0), ${t}.rgb, ${t}.a);\n#endif\n${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && defined(BLEND_MULTIPLY)\n ${t}.rgb = toLinearSpace(${t}.rgb);\n#endif\n`}(t)}`}function rr(t){return`${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && !defined(BLEND_MULTIPLY)\n ${t} = vec4f(toLinearSpaceVec3(${t}.rgb), ${t}.a);\n#elif defined(IMAGEPROCESSING)\n ${t} = applyImageProcessing(vec4f(toLinearSpaceVec3(${t}.rgb), ${t}.a));\n#endif\n`}(t)}\n#if defined(BLEND_PREMULTIPLY)\n ${t} = vec4f(${t}.rgb * ${t}.a, ${t}.a);\n#elif defined(BLEND_MULTIPLY)\n ${t} = vec4f(mix(vec3f(1.0), ${t}.rgb, ${t}.a), ${t}.a);\n#endif\n${function(t){return`\n#if defined(IMAGEPROCESSINGPOSTPROCESS) && defined(BLEND_MULTIPLY)\n ${t} = vec4f(toLinearSpaceVec3(${t}.rgb), ${t}.a);\n#endif\n`}(t)}`}const or="\n#ifdef SOFT_PARTICLES\nuniform sampler2D depthTexture;\nuniform vec2 softParams;\nuniform vec4 projParams;\nvarying vec4 projPosition;\nvarying float linearDepth;\n\nfloat quarksSceneDepth(vec4 texel) {\n#ifdef SOFT_DEPTH_PACKED\n float d = dot(texel, vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n float d = texel.r;\n#endif\n float denominator = projParams.z * d + projParams.w;\n float depth = abs(denominator) > 1e-8 ? abs((projParams.x * d + projParams.y) / denominator) : 0.0;\n // Nothing drawn there reads as infinitely far.\n return depth > 0.0 ? depth : 1e30;\n}\n#endif\n";function ar(t){return`\n#ifdef SOFT_PARTICLES\n {\n vec2 softUV = 0.5 * (projPosition.xy / projPosition.w) + 0.5;\n float sceneDepth = quarksSceneDepth(texture2D(depthTexture, softUV));\n ${t}.a *= clamp(softParams.y * ((sceneDepth - softParams.x) - linearDepth), 0.0, 1.0);\n }\n#endif\n`}const hr="\n#ifdef SOFT_PARTICLES\nvar depthTextureSampler: sampler;\nvar depthTexture: texture_2d<f32>;\nuniform softParams: vec2f;\nuniform projParams: vec4f;\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n\nfn quarksSceneDepth(texel: vec4f) -> f32 {\n#ifdef SOFT_DEPTH_PACKED\n let d = dot(texel, vec4f(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0));\n#else\n let d = texel.r;\n#endif\n let denominator = uniforms.projParams.z * d + uniforms.projParams.w;\n let depth = select(0.0, abs((uniforms.projParams.x * d + uniforms.projParams.y) / denominator), abs(denominator) > 1e-8);\n // Nothing drawn there reads as infinitely far.\n return select(1e30, depth, depth > 0.0);\n}\n#endif\n";function lr(t){return`\n#ifdef SOFT_PARTICLES\n {\n let softUV = 0.5 * (fragmentInputs.projPosition.xy / fragmentInputs.projPosition.w) + 0.5;\n let sceneDepth = quarksSceneDepth(textureSample(depthTexture, depthTextureSampler, softUV));\n ${t}.a *= clamp(uniforms.softParams.y * ((sceneDepth - uniforms.softParams.x) - fragmentInputs.linearDepth), 0.0, 1.0);\n }\n#endif\n`}const cr="\n#ifdef MAP_TRANSFORM\nuniform vec4 mapTransform;\n#endif\n#ifdef UV_DISTORTION\nuniform sampler2D distortionMap;\nuniform vec4 distortionTransform;\nuniform float distortionStrength;\n#endif\n#ifdef GRADIENT_MAP\nuniform sampler2D gradientMap;\nuniform vec2 gradientMapRange;\nuniform vec4 gradientMapChannel;\n#endif\n#ifdef EROSION\nuniform vec2 erosionParams;\nuniform vec3 erosionEdgeColor;\n#ifdef EROSION_MASK\nuniform sampler2D erosionMask;\nuniform vec4 erosionMaskTransform;\n#endif\n\nvec4 quarksErode(vec4 color, float level, float mask) {\n float softness = erosionParams.x;\n float edgeWidth = erosionParams.y;\n // At level 1 the cut sits below the lowest mask value by the soft band\n // and the edge band, so nothing is cut and no edge shows; at level 0 above\n // the highest. The edge then grows in as the cut rises, rather than popping.\n float cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n float visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n float edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color.rgb += erosionEdgeColor * edge;\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function ur(t){return`\n vec4 baseColor = vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV = vUV1 * mapTransform.xy + mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n vec2 mapUV = vUV * mapTransform.xy + mapTransform.zw;\n#else\n vec2 mapUV = vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n vec2 distortionUV = vUV1;\n #else\n vec2 distortionUV = vUV;\n #endif\n vec2 distortion = (texture2D(distortionMap, distortionUV * distortionTransform.xy + distortionTransform.zw).rg - 0.5) * 2.0 * distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n float erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n float erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n vec4 texColor = texture2D(map, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n vec2 mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n vec2 mapUV2 = vUV2 * mapTransform.xy + mapTransform.zw;\n #else\n vec2 mapUV2 = vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n vec4 texColor2 = texture2D(map, mapUV2);\n texColor = mix(texColor, texColor2, vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n vec4 texColor = vec4(1.0);\n#endif\n #ifdef GRADIENT_MAP\n float rampAt = clamp(dot(texColor, gradientMapChannel), 0.0, 1.0);\n vec4 ramp = texture2D(gradientMap, vec2(mix(gradientMapRange.x, gradientMapRange.y, rampAt), 0.5));\n texColor = vec4(ramp.rgb, ramp.a * mix(texColor.a, 1.0, gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n vec2 erosionUV = vUV1;\n #else\n vec2 erosionUV = vUV;\n #endif\n erosionMaskValue = texture2D(erosionMask, erosionUV * erosionMaskTransform.xy + erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}const dr="\n#ifdef MAP_TRANSFORM\nuniform mapTransform: vec4f;\n#endif\n#ifdef UV_DISTORTION\nvar distortionMapSampler: sampler;\nvar distortionMap: texture_2d<f32>;\nuniform distortionTransform: vec4f;\nuniform distortionStrength: f32;\n#endif\n#ifdef GRADIENT_MAP\nvar gradientMapSampler: sampler;\nvar gradientMap: texture_2d<f32>;\nuniform gradientMapRange: vec2f;\nuniform gradientMapChannel: vec4f;\n#endif\n#ifdef EROSION\nuniform erosionParams: vec2f;\nuniform erosionEdgeColor: vec3f;\n#ifdef EROSION_MASK\nvar erosionMaskSampler: sampler;\nvar erosionMask: texture_2d<f32>;\nuniform erosionMaskTransform: vec4f;\n#endif\n\nfn quarksErode(colorIn: vec4f, level: f32, mask: f32) -> vec4f {\n var color = colorIn;\n let softness = uniforms.erosionParams.x;\n let edgeWidth = uniforms.erosionParams.y;\n let cut = mix(-(softness + edgeWidth), 1.0, 1.0 - level);\n let visible = smoothstep(cut, cut + softness, mask);\n if (edgeWidth > 0.0) {\n let edge = 1.0 - smoothstep(cut + softness, cut + softness + edgeWidth, mask);\n color = vec4f(color.rgb + uniforms.erosionEdgeColor * edge, color.a);\n }\n color.a *= visible;\n return color;\n}\n#endif\n";function fr(t){return`\n var baseColor = fragmentInputs.vColor;\n#if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n var mapUV = fragmentInputs.vUV1 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#elif defined(MAP_TRANSFORM)\n var mapUV = fragmentInputs.vUV * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n#else\n var mapUV = fragmentInputs.vUV;\n#endif\n#ifdef UV_DISTORTION\n #ifdef UV_DISTORTION_UV1\n let distortionUV = fragmentInputs.vUV1;\n #else\n let distortionUV = fragmentInputs.vUV;\n #endif\n let distortion = (textureSample(distortionMap, distortionMapSampler, distortionUV * uniforms.distortionTransform.xy + uniforms.distortionTransform.zw).rg - 0.5) * 2.0 * uniforms.distortionStrength;\n mapUV += distortion;\n#endif\n#ifdef EROSION\n let erosionLevel = baseColor.a;\n baseColor.a = 1.0;\n var erosionMaskValue = 1.0;\n#endif\n#if defined(USE_MAP) || defined(GRADIENT_MAP)\n#ifdef USE_MAP\n var texColor = textureSample(map, mapSampler, mapUV);\n ${t?"#ifdef TILE_BLEND\n #if defined(MAP_TRANSFORM) && defined(MAP_UV1)\n let mapUV2 = mapUV;\n #else\n #ifdef MAP_TRANSFORM\n var mapUV2 = fragmentInputs.vUV2 * uniforms.mapTransform.xy + uniforms.mapTransform.zw;\n #else\n var mapUV2 = fragmentInputs.vUV2;\n #endif\n #ifdef UV_DISTORTION\n mapUV2 += distortion;\n #endif\n #endif\n let texColor2 = textureSample(map, mapSampler, mapUV2);\n texColor = mix(texColor, texColor2, fragmentInputs.vTileBlend);\n #endif":""}\n#else\n // No map: the ramp is looked up at white, its far end.\n var texColor = vec4f(1.0);\n#endif\n #ifdef GRADIENT_MAP\n let rampAt = clamp(dot(texColor, uniforms.gradientMapChannel), 0.0, 1.0);\n let ramp = textureSample(gradientMap, gradientMapSampler, vec2f(mix(uniforms.gradientMapRange.x, uniforms.gradientMapRange.y, rampAt), 0.5));\n texColor = vec4f(ramp.rgb, ramp.a * mix(texColor.a, 1.0, uniforms.gradientMapChannel.a));\n #endif\n #ifdef EROSION\n erosionMaskValue = texColor.a;\n #endif\n baseColor *= texColor;\n#endif\n#ifdef EROSION\n #ifdef EROSION_MASK\n #ifdef EROSION_MASK_UV1\n let erosionUV = fragmentInputs.vUV1;\n #else\n let erosionUV = fragmentInputs.vUV;\n #endif\n erosionMaskValue = textureSample(erosionMask, erosionMaskSampler, erosionUV * uniforms.erosionMaskTransform.xy + uniforms.erosionMaskTransform.zw).r;\n #endif\n baseColor = quarksErode(baseColor, erosionLevel, erosionMaskValue);\n#endif\n`}var mr=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${Rn}\n${ir}\n${or}\n${cr}\nvoid main() {\n${ur(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Ln("baseColor.rgb")}\n${ar("baseColor")}\n${nr("baseColor")}\n gl_FragColor = baseColor;\n}\n`,pr=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${qn}\n${sr}\n${hr}\n${dr}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${fr(!0)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${Jn("baseColor")}\n${lr("baseColor")}\n${rr("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,yr=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\nvarying vec3 vNormal;\nvarying vec3 vWorldPos;\n\n#ifndef MESH_UNLIT\nuniform vec3 lightDirection;\nuniform vec3 lightColor;\nuniform vec3 ambientColor;\n#endif\n\n#ifdef TILE_BLEND\nvarying vec2 vUV2;\nvarying float vTileBlend;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform vec3 eyePosition;\n#endif\n\n#ifdef MESH_RIM\nuniform vec3 rimColor;\nuniform vec2 rimParams;\n#endif\n\n// One 3×2 atlas (px py pz / nx ny nz). Avoids samplerCube and multi-face\n// sampler bindings that raise GL_INVALID_OPERATION on iOS WebKit.\n#ifdef USE_ENVMAP_ATLAS\nuniform sampler2D envAtlas;\nuniform float reflectionLevel;\n\nvec3 sampleEnvAtlas(vec3 r) {\n vec3 a = abs(r);\n vec2 localUV;\n float cellX;\n float cellY;\n // Atlas layout: +X +Y +Z on row 0, -X -Y -Z on row 1.\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n vec2 uv = (vec2(cellX, cellY) + clamp(localUV, 0.0, 1.0)) / vec2(3.0, 2.0);\n return texture2D(envAtlas, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${Rn}\n${ir}\n${or}\n${cr}\nvoid main() {\n${ur(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n vec3 N = normalize(vNormal) * (gl_FrontFacing ? 1.0 : -1.0);\n#ifdef MESH_UNLIT\n vec3 color = baseColor.rgb;\n#else\n vec3 L = normalize(-lightDirection);\n float NdotL = max(dot(N, L), 0.0);\n vec3 litColor = ambientColor + lightColor * NdotL;\n\n vec3 color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n vec3 viewDir = normalize(vWorldPos - eyePosition);\n vec3 reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n vec3 V = normalize(eyePosition - vWorldPos);\n float edgeTerm = pow(1.0 - abs(dot(N, V)), rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, rimColor, clamp(edgeTerm * rimParams.y, 0.0, 1.0));\n #else\n color += rimColor * edgeTerm * rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Ln("color")}\n vec4 finalColor = vec4(color, baseColor.a);\n${ar("finalColor")}\n${nr("finalColor")}\n gl_FragColor = finalColor;\n}\n`,gr=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\nvarying vNormal: vec3f;\nvarying vWorldPos: vec3f;\n\n#ifndef MESH_UNLIT\nuniform lightDirection: vec3f;\nuniform lightColor: vec3f;\nuniform ambientColor: vec3f;\n#endif\n\n#ifdef TILE_BLEND\nvarying vUV2: vec2f;\nvarying vTileBlend: f32;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#if defined(USE_ENVMAP_ATLAS) || defined(MESH_RIM)\nuniform eyePosition: vec3f;\n#endif\n\n#ifdef MESH_RIM\nuniform rimColor: vec3f;\nuniform rimParams: vec2f;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\nvar envAtlasSampler: sampler;\nvar envAtlas: texture_2d<f32>;\nuniform reflectionLevel: f32;\n\nfn sampleEnvAtlas(r: vec3f) -> vec3f {\n let a = abs(r);\n var localUV: vec2f;\n var cellX: f32;\n var cellY: f32;\n if (a.x >= a.y && a.x >= a.z) {\n cellX = 0.0;\n if (r.x >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(-r.z, -r.y) / a.x * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.z, -r.y) / a.x * 0.5 + 0.5;\n }\n } else if (a.y >= a.z) {\n cellX = 1.0;\n if (r.y >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, r.z) / a.y * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(r.x, -r.z) / a.y * 0.5 + 0.5;\n }\n } else {\n cellX = 2.0;\n if (r.z >= 0.0) {\n cellY = 0.0;\n localUV = vec2f(r.x, -r.y) / a.z * 0.5 + 0.5;\n } else {\n cellY = 1.0;\n localUV = vec2f(-r.x, -r.y) / a.z * 0.5 + 0.5;\n }\n }\n let uv = (vec2f(cellX, cellY) + clamp(localUV, vec2f(0.0), vec2f(1.0))) / vec2f(3.0, 2.0);\n return textureSample(envAtlas, envAtlasSampler, uv).rgb;\n}\n#endif\n\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${qn}\n${sr}\n${hr}\n${dr}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${fr(!0)}\n // A back face lights, reflects and rims as the face the camera sees.\n let N = normalize(fragmentInputs.vNormal) * select(-1.0, 1.0, fragmentInputs.frontFacing);\n#ifdef MESH_UNLIT\n var color = baseColor.rgb;\n#else\n let L = normalize(-uniforms.lightDirection);\n let NdotL = max(dot(N, L), 0.0);\n let litColor = uniforms.ambientColor + uniforms.lightColor * NdotL;\n\n var color = baseColor.rgb * litColor;\n#endif\n\n#ifdef USE_ENVMAP_ATLAS\n let viewDir = normalize(fragmentInputs.vWorldPos - uniforms.eyePosition);\n let reflectionCoords = reflect(viewDir, N);\n color += sampleEnvAtlas(reflectionCoords) * uniforms.reflectionLevel;\n#endif\n\n#ifdef MESH_RIM\n // Fresnel: strongest where the surface turns away from the camera.\n let V = normalize(uniforms.eyePosition - fragmentInputs.vWorldPos);\n let edgeTerm = pow(1.0 - abs(dot(N, V)), uniforms.rimParams.x);\n #if defined(MESH_RIM_FADE)\n // Faces turned to the camera fade by the strength; edges stay.\n baseColor.a *= clamp(1.0 - uniforms.rimParams.y * (1.0 - edgeTerm), 0.0, 1.0);\n #elif defined(MESH_RIM_MIX)\n color = mix(color, uniforms.rimColor, clamp(edgeTerm * uniforms.rimParams.y, 0.0, 1.0));\n #else\n color += uniforms.rimColor * edgeTerm * uniforms.rimParams.y;\n #endif\n#endif\n\n // After the rim, so a fade that empties a face can discard it.\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n var finalColor = vec4f(color, baseColor.a);\n\n${Jn("finalColor")}\n${lr("finalColor")}\n${rr("finalColor")}\n fragmentOutputs.color = finalColor;\n}\n`,vr=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${jn}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n${Bn}\nvoid main() {\n float c = cos(rotation);\n float s = sin(rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n vec4 limitCenter = view * world * vec4(offset, 1.0);\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(limitCenter.z) : 1.0;\n float screenSize = max(abs(size.x), abs(size.y)) * projection[1][1] / (2.0 * limitDepth);\n float sizeScale = screenSize > 0.0 ? clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize : 1.0;\n vec3 limitedSize = size * sizeScale;\n#else\n vec3 limitedSize = size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n vec2 alignedPosition = position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += pivot.xy * abs(limitedSize.xy);\n#endif\n vec2 rotatedPosition;\n rotatedPosition.x = c * alignedPosition.x - s * alignedPosition.y;\n rotatedPosition.y = s * alignedPosition.x + c * alignedPosition.y;\n\n#ifdef HORIZONTAL\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = view * mvPosition;\n#elif defined(VERTICAL)\n vec4 mvPosition = world * vec4(offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n mvPosition.xy += rotatedPosition;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n gl_Position = projection * mvPosition;\n${Un("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${Qn("uv")}\n\n#ifdef UV1\n vUV1 = uv;\n#endif\n vColor = color;\n}\n`,xr=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${Hn}\n\n#ifdef PIVOT\n// Quad offset in particle-size units: xy in the quad's plane, z toward the camera.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n${Dn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let c = cos(vertexInputs.rotation);\n let s = sin(vertexInputs.rotation);\n\n#ifdef SIZE_LIMITS\n // The particle's size on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitCenter = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let limitDepth = select(1.0, abs(limitCenter.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = max(abs(vertexInputs.size.x), abs(vertexInputs.size.y)) * uniforms.projection[1][1] / (2.0 * limitDepth);\n let sizeScale = select(1.0, clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize, screenSize > 0.0);\n let limitedSize = vertexInputs.size * sizeScale;\n#else\n let limitedSize = vertexInputs.size;\n#endif\n // A negative size mirrors the quad, which is how flipped particles arrive.\n var alignedPosition = vertexInputs.position.xy * limitedSize.xy;\n#ifdef PIVOT\n // The pivot turns with the particle but is not mirrored with it.\n alignedPosition += uniforms.pivot.xy * abs(limitedSize.xy);\n#endif\n let rotatedPosition = vec2f(\n c * alignedPosition.x - s * alignedPosition.y,\n s * alignedPosition.x + c * alignedPosition.y);\n\n#ifdef HORIZONTAL\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.z -= rotatedPosition.y;\n#ifdef PIVOT\n mvPosition.y += uniforms.pivot.z * abs(limitedSize.x);\n#endif\n mvPosition = uniforms.view * mvPosition;\n#elif defined(VERTICAL)\n var mvPosition = uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.y += rotatedPosition.y;\n mvPosition = uniforms.view * mvPosition;\n mvPosition.x += rotatedPosition.x;\n#else\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n mvPosition.x += rotatedPosition.x;\n mvPosition.y += rotatedPosition.y;\n#endif\n#ifdef PIVOT\n#ifndef HORIZONTAL\n // Toward the camera along its view axis, whichever way the view space\n // faces: anything in front of the camera has the sign of the far side.\n mvPosition.z -= sign(mvPosition.z) * uniforms.pivot.z * abs(limitedSize.x);\n#endif\n#endif\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${kn("mvPosition.xyz")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${Yn("vertexInputs.uv")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,Sr=`\n// Per-vertex attributes\nattribute vec3 position;\nattribute vec2 uv;\n\n// Per-instance attributes\nattribute vec3 offset;\nattribute vec4 color;\nattribute vec3 size;\nattribute float rotation;\nattribute float uvTile;\nattribute vec4 velocity;\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 projection;\n${jn}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform vec3 pivot;\n#endif\n\n// Varyings\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vec2 vUV1;\n#endif\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform vec2 sizeLimits;\n#endif\n\n${Bn}\nvoid main() {\n float lengthFactor = velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n float avgSize = (abs(size.x) + abs(size.y)) * 0.5;\n vec4 mvPosition = view * world * vec4(offset, 1.0);\n vec3 viewVelocity = mat3(view * world) * velocity.xyz;\n float vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n vec3 vdir = vlength > 0.000001 ? viewVelocity / vlength : vec3(0.0, 0.0, 1.0);\n // Seen straight along its length a streak has no side to face; any will do.\n vec3 sideRaw = cross(mvPosition.xyz, vdir);\n vec3 side = dot(sideRaw, sideRaw) > 1e-12 ? normalize(sideRaw) : vec3(1.0, 0.0, 0.0);\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n float limitDepth = abs(projection[2][3]) > 0.0 ? abs(mvPosition.z) : 1.0;\n float screenSize = avgSize * projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, sizeLimits.x, sizeLimits.y) / screenSize;\n }\n#endif\n mvPosition.xyz += position.y * side * avgSize;\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n mvPosition.xyz += (position.x + 0.5) * viewVelocity;\n#else\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n mvPosition.xyz -= (position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n mvPosition.xyz += (pivot.y * side - pivot.x * vdir) * avgSize;\n#endif\n gl_Position = projection * mvPosition;\n${Un("mvPosition.xyz")}\n vec2 quadUV = vec2(size.x < 0.0 ? 1.0 - uv.x : uv.x, size.y < 0.0 ? 1.0 - uv.y : uv.y);\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(mvPosition.z);\n#endif\n\n${Qn("quadUV")}\n\n#ifdef UV1\n vUV1 = quadUV;\n#endif\n vColor = color;\n}\n`,br=`\n// Per-vertex attributes\nattribute position: vec3f;\nattribute uv: vec2f;\n\n// Per-instance attributes\nattribute offset: vec3f;\nattribute color: vec4f;\nattribute size: vec3f;\nattribute rotation: f32;\nattribute uvTile: f32;\nattribute velocity: vec4f;\n\n// Uniforms\nuniform world: mat4x4f;\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n${Hn}\n\n#ifdef PIVOT\n// Streak offset in particle-size units: x from head to tail, y across.\nuniform pivot: vec3f;\n#endif\n\n// Varyings\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// The particle's own UV, never moved by the sheet (UV channel 1).\nvarying vUV1: vec2f;\n#endif\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n#ifdef SIZE_LIMITS\n// Smallest and largest size a particle may have on screen, as fractions of the viewport height.\nuniform sizeLimits: vec2f;\n#endif\n\n${Dn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n let lengthFactor = vertexInputs.velocity.w;\n // A flipped particle arrives with a negative size: the streak keeps its\n // extent and mirrors its texture instead (see quadUV below).\n var avgSize = (abs(vertexInputs.size.x) + abs(vertexInputs.size.y)) * 0.5;\n var mvPosition = uniforms.view * uniforms.world * vec4f(vertexInputs.offset, 1.0);\n let viewWorld = uniforms.view * uniforms.world;\n let viewWorld3 = mat3x3f(viewWorld[0].xyz, viewWorld[1].xyz, viewWorld[2].xyz);\n let viewVelocity = viewWorld3 * vertexInputs.velocity.xyz;\n let vlength = length(viewVelocity);\n // Stretch direction is the velocity direction; only a genuinely motionless particle has none.\n // Deriving it via normalize keeps the stretch aligned even when the speed contribution is ~0\n // (e.g. a speed factor of 0), instead of collapsing the whole burst onto a fixed screen axis.\n var vdir = vec3f(0.0, 0.0, 1.0);\n if (vlength > 0.000001) {\n vdir = viewVelocity / vlength;\n }\n // Seen straight along its length a streak has no side to face; any will do.\n let sideRaw = cross(mvPosition.xyz, vdir);\n var side = vec3f(1.0, 0.0, 0.0);\n if (dot(sideRaw, sideRaw) > 1e-12) {\n side = normalize(sideRaw);\n }\n#ifdef SIZE_LIMITS\n // The streak's width on screen as a fraction of the viewport height, held\n // between the limits; a perspective projection divides by the view depth.\n let limitDepth = select(1.0, abs(mvPosition.z), abs(uniforms.projection[2][3]) > 0.0);\n let screenSize = avgSize * uniforms.projection[1][1] / (2.0 * limitDepth);\n if (screenSize > 0.0) {\n avgSize *= clamp(screenSize, uniforms.sizeLimits.x, uniforms.sizeLimits.y) / screenSize;\n }\n#endif\n let widthOffset = vertexInputs.position.y * side * avgSize;\n // Equivalent to viewVelocity * (1.0 + lengthFactor / vlength) for moving particles, but the\n // size-based term (vdir * lengthFactor) survives when the velocity contribution vanishes.\n#ifdef BEAM\n // The vector runs from the particle to the beam's end: the quad spans it\n // exactly, U from the particle (0) to the end (1), as wide as the size.\n var stretched = mvPosition.xyz + widthOffset + (vertexInputs.position.x + 0.5) * viewVelocity;\n#else\n let lengthOffset = (vertexInputs.position.x + 0.5) * (viewVelocity + vdir * lengthFactor) * avgSize;\n var stretched = mvPosition.xyz + widthOffset - lengthOffset;\n#endif\n#ifdef PIVOT\n // In particle-size units along the quad's own axes: x from head to tail, y across.\n stretched += (uniforms.pivot.y * side - uniforms.pivot.x * vdir) * avgSize;\n#endif\n mvPosition.x = stretched.x;\n mvPosition.y = stretched.y;\n mvPosition.z = stretched.z;\n\n let clipPosition = uniforms.projection * mvPosition;\n vertexOutputs.position = clipPosition;\n${kn("mvPosition.xyz")}\n let quadUV = select(vertexInputs.uv, 1.0 - vertexInputs.uv, vertexInputs.size.xy < vec2f(0.0));\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(mvPosition.z);\n#endif\n\n${Yn("quadUV")}\n\n#ifdef UV1\n vertexOutputs.vUV1 = quadUV;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`,wr=`\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\nvarying vec2 vUV1;\n#endif\n\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform float alphaTest;\n#endif\n\n${Rn}\n${ir}\n${or}\n${cr}\nvoid main() {\n${ur(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < alphaTest) discard;\n#else\n if (baseColor.a < 0.01) discard;\n#endif\n\n${Ln("baseColor.rgb")}\n${ar("baseColor")}\n${nr("baseColor")}\n gl_FragColor = baseColor;\n}\n`,Mr=`\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\nvarying vUV1: vec2f;\n#endif\n\n#ifdef USE_MAP\nvar mapSampler: sampler;\nvar map: texture_2d<f32>;\n#endif\n\n#ifdef USE_ALPHATEST\nuniform alphaTest: f32;\n#endif\n\n${qn}\n${sr}\n${hr}\n${dr}\n@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${fr(!1)}\n#ifdef USE_ALPHATEST\n if (baseColor.a < uniforms.alphaTest) { discard; }\n#else\n if (baseColor.a < 0.01) { discard; }\n#endif\n\n${Jn("baseColor")}\n${lr("baseColor")}\n${rr("baseColor")}\n fragmentOutputs.color = baseColor;\n}\n`,zr=`\nattribute vec3 position;\nattribute vec3 previous;\nattribute vec3 next;\nattribute float side;\nattribute float width;\nattribute vec2 uv;\nattribute vec4 color;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute vec2 uv2;\nvarying vec2 vUV1;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying vec4 projPosition;\nvarying float linearDepth;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nvec3 trailDirection(vec3 d) {\n float l = dot(d, d);\n return l > 1e-12 ? d * inversesqrt(l) : vec3(0.0);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nvec3 trailSide(vec3 previousPoint, vec3 point, vec3 nextPoint) {\n vec3 incoming = trailDirection(point - previousPoint);\n vec3 outgoing = trailDirection(nextPoint - point);\n vec3 tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = dot(outgoing, outgoing) > 0.0 ? outgoing : incoming;\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n vec3 sight = projection[3][3] > 0.5 ? vec3(0.0, 0.0, 1.0) : point;\n vec3 side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${Bn}\nvoid main() {\n vec3 point = (view * vec4(position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (width > 0.0) {\n vec3 previousPoint = (view * vec4(previous, 1.0)).xyz;\n vec3 nextPoint = (view * vec4(next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * width * side);\n }\n gl_Position = projection * vec4(point, 1.0);\n${Un("point")}\n#ifdef SOFT_PARTICLES\n projPosition = gl_Position;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n linearDepth = abs(point.z);\n#endif\n vUV = uv;\n#ifdef UV1\n vUV1 = uv2;\n#endif\n vColor = color;\n}\n`,_r=`\nattribute position: vec3f;\nattribute previous: vec3f;\nattribute next: vec3f;\nattribute side: f32;\nattribute width: f32;\nattribute uv: vec2f;\nattribute color: vec4f;\n\nuniform view: mat4x4f;\nuniform projection: mat4x4f;\n\nvarying vUV: vec2f;\nvarying vColor: vec4f;\n#ifdef UV1\n// Along the trail and across it, without the sheet's cell (UV channel 1).\nattribute uv2: vec2f;\nvarying vUV1: vec2f;\n#endif\n\n#ifdef SOFT_PARTICLES\nvarying projPosition: vec4f;\nvarying linearDepth: f32;\n#endif\n\n// The unit tangent of a segment, or zero for a segment of no length.\nfn trailDirection(d: vec3f) -> vec3f {\n let l = dot(d, d);\n return select(vec3f(0.0), d * inverseSqrt(max(l, 1e-24)), l > 1e-12);\n}\n\n// The direction a ribbon point is widened along, in view space: across the trail's tangent and\n// the line of sight, as Unity's View alignment and Niagara's ribbon facing do. Stays finite at\n// repeated points, at a hairpin and for a segment pointing at the camera.\nfn trailSide(previousPoint: vec3f, point: vec3f, nextPoint: vec3f) -> vec3f {\n let incoming = trailDirection(point - previousPoint);\n let outgoing = trailDirection(nextPoint - point);\n var tangent = incoming + outgoing;\n if (dot(tangent, tangent) < 1e-6) {\n // A hairpin turns the two directions against each other: face the way it now goes.\n tangent = select(incoming, outgoing, dot(outgoing, outgoing) > 0.0);\n }\n // The line of sight: to the point for a perspective camera, the view axis for an orthographic one.\n let sight = select(point, vec3f(0.0, 0.0, 1.0), uniforms.projection[3][3] > 0.5);\n var side = cross(tangent, sight);\n if (dot(side, side) < 1e-12) {\n side = cross(tangent, vec3f(0.0, 0.0, 1.0));\n }\n if (dot(side, side) < 1e-12) {\n side = vec3f(1.0, 0.0, 0.0);\n }\n return normalize(side);\n}\n\n${Dn}\n@vertex\nfn main(input: VertexInputs) -> FragmentInputs {\n var point = (uniforms.view * vec4f(vertexInputs.position, 1.0)).xyz;\n // A swept trail lays its vertices out on the CPU and gives them no width.\n if (vertexInputs.width > 0.0) {\n let previousPoint = (uniforms.view * vec4f(vertexInputs.previous, 1.0)).xyz;\n let nextPoint = (uniforms.view * vec4f(vertexInputs.next, 1.0)).xyz;\n point += trailSide(previousPoint, point, nextPoint) * (0.5 * vertexInputs.width * vertexInputs.side);\n }\n let clipPosition = uniforms.projection * vec4f(point, 1.0);\n vertexOutputs.position = clipPosition;\n${kn("point")}\n#ifdef SOFT_PARTICLES\n vertexOutputs.projPosition = clipPosition;\n // View depth is +z ahead of a left-handed camera and -z ahead of a right-handed one.\n vertexOutputs.linearDepth = abs(point.z);\n#endif\n vertexOutputs.vUV = vertexInputs.uv;\n#ifdef UV1\n vertexOutputs.vUV1 = vertexInputs.uv2;\n#endif\n vertexOutputs.vColor = vertexInputs.color;\n}\n`;const Ar=["IMAGEPROCESSING","WHITEBALANCE","VIGNETTE","VIGNETTEBLENDMODEMULTIPLY","VIGNETTEBLENDMODEOPAQUE","TONEMAPPING","CONTRAST","COLORCURVES","COLORGRADING","COLORGRADING3D","SAMPLER3DGREENDEPTH","SAMPLER3DBGRMAP","DITHER","IMAGEPROCESSINGPOSTPROCESS","EXPOSURE","SKIPFINALCOLORCLAMP"],Pr=["position","uv","offset","color","size","rotation","uvTile"],Or=["position","previous","next","side","width","uv","color"],Tr=["vFogInfos","vFogColor"];function Vr(t){return t===Rs.StretchedBillBoard||t===Rs.Beam}const Er=new Set([r.ALPHA_SUBTRACT,r.ALPHA_MAXIMIZED,r.ALPHA_ONEONE,r.ALPHA_PREMULTIPLIED,r.ALPHA_PREMULTIPLIED_PORTERDUFF,r.ALPHA_SCREENMODE,r.ALPHA_ONEONE_ONEONE,r.ALPHA_ALPHATOCOLOR,r.ALPHA_REVERSEONEMINUS,r.ALPHA_SRC_DSTONEMINUSSRCALPHA,r.ALPHA_ONEONE_ONEZERO,r.ALPHA_EXCLUSION,r.ALPHA_MAX]),$r=new Set([r.ALPHA_MULTIPLY,r.ALPHA_MIN]),Cr=new Set([r.ALPHA_COMBINE,r.ALPHA_PREMULTIPLIED,r.ALPHA_PREMULTIPLIED_PORTERDUFF,r.ALPHA_INTERPOLATE,r.ALPHA_SRC_DSTONEMINUSSRCALPHA,r.ALPHA_LAYER_ACCUMULATE,r.ALPHA_REPLACE_COLOR]);function Ir(t){const e=t.materialBlendMode;if(!t.materialTransparent||e===r.ALPHA_DISABLE)return{output:"straight",fogTarget:"color"};const i=Er.has(e)?"premultiply":$r.has(e)?"multiply":"straight";return{output:i,fogTarget:"multiply"===i?"white":Cr.has(e)||"straight"===i&&e!==r.ALPHA_ADD?"color":"black"}}function Nr(t,e){return t.renderMode===Rs.Trail?function(t,e){const i=Fr(t),s=[...Or],n=["view","projection",...Tr],r=[];null!==t.texture&&(i.push("USE_MAP"),r.push("map"));Lr(t,i,n,r),Rr(t,e,i,n,r),Ur(t,e,i,n,r),rn(t)&&s.push("uv2");return{name:"quarksTrail",vertex:{glsl:zr,wgsl:_r},fragment:{glsl:wr,wgsl:Mr},defines:i,attributes:s,uniforms:n,samplers:r}}(t,e):function(t,e){const i=t.renderMode,s=i===Rs.Mesh,n=`quarksParticle_${i}`;let r,o;s?(r={glsl:Xn,wgsl:Zn},o={glsl:yr,wgsl:gr}):Vr(i)?(r={glsl:Sr,wgsl:br},o={glsl:mr,wgsl:pr}):(r={glsl:vr,wgsl:xr},o={glsl:mr,wgsl:pr});const a=Fr(t),h=[...Pr],l=["world","view","projection",...Tr],c=[];(function(t){return null!==t.texture||t.renderMode===Rs.Mesh})(t)&&(a.push("USE_MAP"),c.push("map"));const u=s&&null!==t.reflectionAtlas&&e.envAtlasReady;u&&(a.push("USE_ENVMAP_ATLAS"),c.push("envAtlas"),l.push("reflectionLevel"));Mn(t)&&(a.push("UV_TILE"),l.push("tileCountX","tileCountY"),t.blendTiles&&a.push("TILE_BLEND"));Rr(t,e,a,l,c),i===Rs.VerticalBillBoard&&a.push("VERTICAL");i===Rs.HorizontalBillBoard&&a.push("HORIZONTAL");i===Rs.Beam&&a.push("BEAM");wn(i)&&(t.pivot&&(a.push("PIVOT"),l.push("pivot")),zn(t)&&(a.push("SIZE_LIMITS"),l.push("sizeLimits")));const d=s&&"unlit"!==(t.lighting??"fixed");s&&!d&&a.push("MESH_UNLIT");d&&l.push("lightDirection","lightColor","ambientColor");const f=s?t.rim:void 0;f&&(a.push("MESH_RIM"),"fade"===f.mode?a.push("MESH_RIM_FADE"):"mix"===f.mode&&a.push("MESH_RIM_MIX"),l.push("rimColor","rimParams"));(u||f)&&l.push("eyePosition");Lr(t,a,l,c),Ur(t,e,a,l,c),s&&(h.push("normal"),rn(t)&&e.meshUV2&&(a.push("MESH_UV2"),h.push("uv2")));Vr(i)&&h.push("velocity");return{name:n,vertex:r,fragment:o,defines:a,attributes:h,uniforms:l,samplers:c}}(t,e)}function Fr(t){const{output:e,fogTarget:i}=Ir(t),s=[];return"premultiply"===e?s.push("BLEND_PREMULTIPLY"):"multiply"===e&&s.push("BLEND_MULTIPLY"),t.applyFog&&(s.push("FOG"),"black"===i?s.push("FOG_ADDITIVE"):"white"===i&&s.push("FOG_MULTIPLY")),s}function Br(t,e){const i={defines:[],uniforms:[],samplers:[]};if(!e||!function(t,e){return!(!1===t.applyImageProcessing||!e)&&(!!e.IMAGEPROCESSINGPOSTPROCESS||e.IMAGEPROCESSING&&"multiply"!==Ir(t).output)}(t,e))return i;for(const t of Ar){const s=e[t];"number"==typeof s?i.defines.push(`${t} ${s}`):s&&i.defines.push(t)}return g(i.uniforms,e),v(i.samplers,e),i}function Ur(t,e,i,s,n){const r=Br(t,e.imageProcessing);i.push(...r.defines),s.push(...r.uniforms),n.push(...r.samplers)}function Rr(t,e,i,s,n){t.softParticles&&null!==e.depth&&(i.push("SOFT_PARTICLES"),e.depth.packed&&i.push("SOFT_DEPTH_PACKED"),s.push("softParams","projParams"),n.push("depthTexture")),t.materialAlphaTest>0&&(i.push("USE_ALPHATEST"),s.push("alphaTest"))}function Lr(t,e,i,s){const{mapUV:n,uvDistortion:r,gradientMap:o,erosion:a}=t;rn(t)&&e.push("UV1"),n&&(e.push("MAP_TRANSFORM"),1===n.channel&&e.push("MAP_UV1"),i.push("mapTransform")),r&&(e.push("UV_DISTORTION"),1===r.mapUV.channel&&e.push("UV_DISTORTION_UV1"),s.push("distortionMap"),i.push("distortionTransform","distortionStrength")),o&&(e.push("GRADIENT_MAP"),s.push("gradientMap"),i.push("gradientMapRange","gradientMapChannel")),a&&(e.push("EROSION"),i.push("erosionParams","erosionEdgeColor"),a.mask&&(e.push("EROSION_MASK"),1===a.maskUV.channel&&e.push("EROSION_MASK_UV1"),s.push("erosionMask"),i.push("erosionMaskTransform")))}function Dr(t){return t.isWebGPU?b.WGSL:b.GLSL}function kr(t,e,i,s){if(s===b.WGSL)return x.ShadersStoreWGSL[t+"VertexShader"]=e.wgsl,void(x.ShadersStoreWGSL[t+"FragmentShader"]=i.wgsl);S.ShadersStore[t+"VertexShader"]=e.glsl,S.ShadersStore[t+"FragmentShader"]=i.glsl}class qr{constructor(t,e,i=null){this.parentNode=null,this.visibleSystems=[],this.boundsMin_=new ht,this.boundsMax_=new ht,this.imageProcessingObserver=null,this.time=0,this.underusedFills=0,this.scene=e,this.depth=i,this.maxParticles=0,this.systems=new Set,this.settings=_n(t)}attachTo(t){this.parentNode=t,this.mesh.parent=t}configureMesh(){const t=this.mesh;t.alwaysSelectAsActiveMesh=!0,t.doNotSyncBoundingInfo=!0,t.parent=this.parentNode,t.freezeWorldMatrix(h.Identity());const e=t.getWorldMatrix();t.computeWorldMatrix=()=>e,t.setBoundingInfo(new w(a.Zero(),a.Zero())),t.layerMask=this.settings.layerMask,t.renderingGroupId=this.settings.renderingGroupId,t.alphaIndex=this.settings.renderOrder,t.applyFog=!1,t.isPickable=!1,t.checkCollisions=!1,t.doNotSerialize=!0}refreshBoundingInfo(){const t=this.boundsMin_,e=this.boundsMax_;let i=1/0,s=1/0,n=1/0,r=-1/0,o=-1/0,a=-1/0,h=!1;const l=this.visibleSystems;for(let c=0;c<l.length;c++){const u=l[c];if(0!==u.particleNum&&"function"==typeof u.getWorldBounds){if(!u.getWorldBounds(t,e))return void(this.mesh.alwaysSelectAsActiveMesh=!0);h=!0,t.x<i&&(i=t.x),t.y<s&&(s=t.y),t.z<n&&(n=t.z),e.x>r&&(r=e.x),e.y>o&&(o=e.y),e.z>a&&(a=e.z)}}if(!h)return;const c=this.mesh.getBoundingInfo(),u=c.minimum,d=c.maximum;u.x===i&&u.y===s&&u.z===n&&d.x===r&&d.y===o&&d.z===a||(u.set(i,s,n),d.set(r,o,a),c.reConstruct(u,d)),this.mesh.alwaysSelectAsActiveMesh=!1}static writeBound(t,e){e(t);const i=t.getEffect();i?.isReady()&&e(i)}bindFog(t){if(!this.settings.applyFog)return;const e=this.scene;t.onBindObservable.add(()=>{const i=t.getEffect();if(!i)return;const s=e.fogEnabled?e.fogMode:z.FOGMODE_NONE;i.setFloat4("vFogInfos",s,e.fogStart,e.fogEnd,e.fogDensity),i.setColor3("vFogColor",e.fogColor)})}imageProcessing(){if(!1===this.settings.applyImageProcessing)return null;const t={IMAGEPROCESSING:!1,WHITEBALANCE:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,EXPOSURE:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,SKIPFINALCOLORCLAMP:!1};return this.scene.imageProcessingConfiguration.prepareDefines(t),t}bindImageProcessing(t,e){if(this.releaseImageProcessing(),!1===this.settings.applyImageProcessing)return;const i=this.scene.imageProcessingConfiguration;let s=e,n=Br(this.settings,s),r=n.defines.join("\n");const o=()=>{n.samplers.includes("txColorTransform")&&i.colorGradingTexture?t.setTexture("txColorTransform",i.colorGradingTexture):t.removeTexture("txColorTransform")};o(),this.imageProcessingObserver=i.onUpdateParameters.add(()=>{const e=this.imageProcessing(),i=Br(this.settings,e),a=i.defines.join("\n");if(a!==r){const o=t.options;Jr(o.defines,n.defines,i.defines),Jr(o.uniforms,n.uniforms,i.uniforms),Jr(o.samplers,n.samplers,i.samplers),s=e,n=i,r=a}o()}),t.onBindObservable.add(()=>{if(!s?.IMAGEPROCESSING||s.IMAGEPROCESSINGPOSTPROCESS||0===n.defines.length)return;const e=t.getEffect();e&&i.bind(e)})}releaseImageProcessing(){this.imageProcessingObserver?.remove(),this.imageProcessingObserver=null}usesUV1(){return rn(this.settings)}bindSurface(t){const{mapUV:e,uvDistortion:i,gradientMap:s,erosion:n}=this.settings;if(i?.map&&t.setTexture("distortionMap",i.map),s?.ramp&&t.setTexture("gradientMap",s.ramp),n?.mask&&t.setTexture("erosionMask",n.mask),this.writeSurfaceParams(t),!(e||i||n?.mask||s))return;const r=t=>t-2*Math.floor(t/2),o=new l,a=new l,h=new l,u=new c(0,1),d=(t,e,i)=>i.set(t.tiling[0],t.tiling[1],t.offset[0]+r(t.scroll[0]*e),t.offset[1]+r(t.scroll[1]*e)),f=()=>{const e=this.time,i=t.getEffect(),{mapUV:s,uvDistortion:n,gradientMap:r,erosion:l}=this.settings;if(s&&(d(s,e,o),t.setVector4("mapTransform",o),i?.setVector4("mapTransform",o)),n&&(d(n.mapUV,e,a),t.setVector4("distortionTransform",a),i?.setVector4("distortionTransform",a)),l?.mask&&(d(l.maskUV,e,h),t.setVector4("erosionMaskTransform",h),i?.setVector4("erosionMaskTransform",h)),r?.ramp){const e=r.ramp.getSize().width,s=e>0?.5/e:0;u.set(s,1-s),t.setVector2("gradientMapRange",u),i?.setVector2("gradientMapRange",u)}};f(),t.onBindObservable.add(f)}writeSurfaceParams(t){const{uvDistortion:e,gradientMap:i,erosion:s}=this.settings;if(e?.map&&t.setFloat("distortionStrength",e.strength),i?.ramp){const[e,s,n,r]=Ws[i.channel];t.setVector4("gradientMapChannel",new l(e,s,n,r))}s&&(t.setVector2("erosionParams",new c(s.softness,s.edgeWidth)),t.setVector3("erosionEdgeColor",new a(s.edgeColor[0],s.edgeColor[1],s.edgeColor[2])))}applyLiveSettings(t){Object.assign(this.settings,t);const e=this.mesh.material;e instanceof f&&this.writeLiveUniforms(e)}writeLiveUniforms(t){this.writeSoftParams(t),this.writeSurfaceParams(t)}addSystem(t){this.systems.add(t)}removeSystem(t){this.systems.delete(t)}getVisibleSystems(){const t=this.visibleSystems;let e=0;for(const i of this.systems)i.emitter.visible&&!0!==i.culled&&(t[e++]=i);return t.length=e,t}applyDepthTexture(t){t instanceof M&&(t={texture:t,encoding:"linear",packed:!1});const e=this.depth;if(this.depth=t,!this.settings.softParticles)return;if(!e!=!t||e?.packed!==t?.packed)return void this.rebuildMaterial();const i=this.mesh.material;t&&i instanceof f&&i.setTexture("depthTexture",t.texture)}bindSoft(t){if(this.writeSoftParams(t),this.drawsSoft()){t.setTexture("depthTexture",this.depth.texture);const e=new l(1,0,0,1);t.onBindObservable.add(()=>{const i=this.scene.activeCamera;i&&this.depth&&($n(i,this.depth.encoding,e),qr.writeBound(t,t=>t.setVector4("projParams",e)))})}}writeSoftParams(t){this.drawsSoft()&&t.setVector2("softParams",new c(this.settings.softNearFade,1/Math.max(this.settings.softFarFade-this.settings.softNearFade,1e-4))),this.settings.materialAlphaTest>0&&t.setFloat("alphaTest",this.settings.materialAlphaTest)}drawsSoft(){return this.settings.softParticles&&null!==this.depth}applyMeshLighting(t){}fitBuffers(t){if(t>this.maxParticles)return this.underusedFills=0,void this.expandBuffers(t);this.maxParticles>this.initialCapacity&&t<this.maxParticles/4?++this.underusedFills>=qr.SHRINK_AFTER_FILLS&&(this.underusedFills=0,this.maxParticles=Math.max(this.initialCapacity,this.maxParticles/2),this.resizeBuffers()):this.underusedFills=0}dispose(){this.releaseImageProcessing(),this.mesh.dispose()}}function Jr(t,e,i){for(const i of e){const e=t.lastIndexOf(i);-1!==e&&t.splice(e,1)}t.push(...i)}qr.SHRINK_AFTER_FILLS=300;class Gr extends qr{static whiteTexture(t){let e=Gr.whiteTextureByScene.get(t);if(!e){e=m.CreateRGBATexture(new Uint8Array([255,255,255,255]),1,1,t),e.name="quarksMeshWhite",Gr.whiteTextureByScene.set(t,e);const i=e;e.onDisposeObservable.addOnce(()=>{Gr.whiteTextureByScene.get(t)===i&&Gr.whiteTextureByScene.delete(t)})}return e}constructor(t,e,i=null){super(t,e,i),this.shaderMaterial=null,this.cancelAtlasRebuild=null,this.disposed=!1,this.fixedLightDirection=new a,this.fixedLightColor=new a,this.fixedAmbientColor=new a,this.warnedUV2=!1,this.initialCapacity=1e3,this.gatherScratch=[],this.vector_=new ht,this.vector2_=new ht,this.vector3_=new ht,this.quaternion_=new at,this.quaternion2_=new at,this.quaternion3_=new at,this.quaternion4_=new at,this.quaternion5_=new at,this.rotationMat_=new zt,this.rotationMat2_=new zt,this.clearedInstanceUploaded=!1,this.beamEnd_=new ht,this.storeFixedLighting(Ls()),this.maxParticles=this.initialCapacity,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh?.dispose(),this.mesh=new p("spriteBatch",this.scene),this.configureMesh();const t=new y;t.positions=this.settings.instancingGeometry,t.indices=this.settings.instancingIndices;const e=this.settings.instancingGeometry.length/3,i=this.settings.instancingUVs;i&&i.length>=2*e?t.uvs=i:t.uvs=new Float32Array(2*e),this.meshUV2()&&(t.uvs2=this.settings.instancingUVs2),this.settings.instancingNormals&&(t.normals=this.settings.instancingNormals),t.applyToMesh(this.mesh,!1),this.buildExpandableBuffers()}meshUV2(){const t=this.settings.instancingUVs2;if(this.settings.renderMode!==Rs.Mesh||!t||!this.usesUV1())return!1;const e=this.settings.instancingGeometry.length/3*2;return t.length===e||(this.warnedUV2||(this.warnedUV2=!0,console.warn(`[babylon.quarks] instancingUVs2 has ${t.length} values for ${e/2} vertices (two per vertex expected); UV channel 1 reads the first UV set instead.`)),!1)}disposeExpandableBuffers(){this.offsetVB?.dispose(),this.colorVB?.dispose(),this.sizeVB?.dispose(),this.uvTileVB?.dispose(),this.rotationVB?.dispose(),this.velocityVB?.dispose(),this.velocityVB=void 0,this.velocityBuffer=void 0}buildExpandableBuffers(){const e=this.scene.getEngine();this.offsetBuffer=new Float32Array(3*this.maxParticles),this.offsetVB=new t(e,this.offsetBuffer,"offset",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.offsetVB),this.colorBuffer=new Float32Array(4*this.maxParticles),this.colorVB=new t(e,this.colorBuffer,"color",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.colorVB),this.sizeBuffer=new Float32Array(3*this.maxParticles),this.sizeVB=new t(e,this.sizeBuffer,"size",!0,!1,3,!0),this.mesh.setVerticesBuffer(this.sizeVB),this.uvTileBuffer=new Float32Array(this.maxParticles),this.uvTileVB=new t(e,this.uvTileBuffer,"uvTile",!0,!1,1,!0),this.mesh.setVerticesBuffer(this.uvTileVB),this.settings.renderMode===Rs.Mesh?(this.rotationBuffer=new Float32Array(4*this.maxParticles),this.rotationVB=new t(e,this.rotationBuffer,"rotation",!0,!1,4,!0)):(this.rotationBuffer=new Float32Array(this.maxParticles),this.rotationVB=new t(e,this.rotationBuffer,"rotation",!0,!1,1,!0)),this.mesh.setVerticesBuffer(this.rotationVB),Vr(this.settings.renderMode)&&(this.velocityBuffer=new Float32Array(4*this.maxParticles),this.velocityVB=new t(e,this.velocityBuffer,"velocity",!0,!1,4,!0),this.mesh.setVerticesBuffer(this.velocityVB)),this.mesh.forcedInstanceCount=0,this.mesh.doNotSyncBoundingInfo=!0}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.resizeBuffers()}resizeBuffers(){this.disposeExpandableBuffers(),this.buildExpandableBuffers(),this.sortScratch=void 0,this.gatherScratch.length=0}sizeLimits(){const{minParticleSize:t,maxParticleSize:e}=this.settings;return wn(this.settings.renderMode)&&zn(this.settings)?new c(Math.max(0,t),Math.min(e,1e9)):null}sortInstances(t,e,i){if(t<2)return;const s=this.sortScratch??(this.sortScratch=new Fn(this.maxParticles));s.ensure(t);const n=s.keys,r=this.settings.sortMode;if("distance"===r){const e=this.scene.activeCameras?.[0]??this.scene.activeCamera;if(!e)return;const i=e.globalPosition,r=i.x,o=i.y,a=i.z,h=this.offsetBuffer;for(let e=0,i=0;e<t;e++,i+=3){const t=h[i]-r,l=h[i+1]-o,c=h[i+2]-a;n[e]=s.floatKey(t*t+l*l+c*c,!0)}}else{const e="youngestInFront"===r,i=this.visibleSystems;let o=0;for(let t=0;t<i.length;t++){const r=i[t],a=r.particleNum,h=r.store;if(0===a)continue;if(void 0===h){const t=r.particles;for(let i=0;i<a;i++)n[o++]=s.floatKey(t[i].age,e);continue}const l=h.scalars,c=We.SCALAR_STRIDE;for(let t=0,i=We.AGE;t<a;t++,i+=c)n[o++]=s.floatKey(l[i],e)}if(o!==t)return}const o=function(t,e){const i=t.keys,s=t.counts;let n=t.orderA,r=t.orderB;for(let t=0;t<e;t++)n[t]=t;for(let t=0;t<32;t+=11){s.fill(0);for(let r=0;r<e;r++)s[i[n[r]]>>>t&Nn]++;if(s[i[n[0]]>>>t&Nn]===e)continue;let o=0;for(let t=0;t<In;t++){const e=s[t];s[t]=o,o+=e}for(let o=0;o<e;o++){const e=n[o];r[s[i[e]>>>t&Nn]++]=e}const a=n;n=r,r=a}return n}(s,t);this.offsetBuffer=this.gatherInto(0,this.offsetBuffer,o,t,3),this.sizeBuffer=this.gatherInto(1,this.sizeBuffer,o,t,3),this.colorBuffer=this.gatherInto(2,this.colorBuffer,o,t,4),this.uvTileBuffer=this.gatherInto(3,this.uvTileBuffer,o,t,1),this.rotationBuffer=this.gatherInto(4,this.rotationBuffer,o,t,e?4:1),i&&this.velocityBuffer&&(this.velocityBuffer=this.gatherInto(5,this.velocityBuffer,o,t,4))}gatherInto(t,e,i,s,n){let r=this.gatherScratch[t];return void 0!==r&&r.length===e.length||(r=new Float32Array(e.length)),function(t,e,i,s,n){if(1===n)for(let n=0;n<s;n++)e[n]=t[i[n]];else if(3===n)for(let n=0,r=0;n<s;n++,r+=3){const s=3*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2]}else if(4===n)for(let n=0,r=0;n<s;n++,r+=4){const s=4*i[n];e[r]=t[s],e[r+1]=t[s+1],e[r+2]=t[s+2],e[r+3]=t[s+3]}else for(let r=0;r<s;r++){const s=i[r]*n,o=r*n;for(let i=0;i<n;i++)e[o+i]=t[s+i]}}(e,r,i,s,n),this.gatherScratch[t]=e,r}rebuildMaterial(){const t=this.settings.renderMode===Rs.Mesh,e=this.settings.texture??(t?Gr.whiteTexture(this.scene):null),i=this.settings.reflectionAtlas,s=t&&!!i&&!i.isReady();if(this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,s&&i){const t=i.onLoadObservable;if(t){const e=t.addOnce(()=>{this.cancelAtlasRebuild=null,this.disposed||this.rebuildMaterial()});this.cancelAtlasRebuild=()=>t.remove(e)}}const n=this.usesEnvAtlas(),o=this.imageProcessing(),h=Nr(this.settings,{depth:this.depth,envAtlasReady:n,meshUV2:this.meshUV2(),imageProcessing:o}),{defines:l,attributes:c,uniforms:u,samplers:d}=h,m=h.name,p=this.settings.lighting??"fixed",y=t&&"unlit"!==p,g=t?this.settings.rim:void 0,v=n||!!g,x=Dr(this.scene.getEngine());kr(m,h.vertex,h.fragment,x);const S=new f(m,this.scene,{vertex:m,fragment:m},{attributes:c,uniforms:u,samplers:d,defines:l,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:x});if(e&&S.setTexture("map",e),n&&i&&S.setTexture("envAtlas",i),v){const t=new a;S.setVector3("eyePosition",t),S.onBindObservable.add(()=>{const e=this.scene.activeCamera;e&&(t.copyFrom(e.globalPosition),qr.writeBound(S,e=>e.setVector3("eyePosition",t)))})}if(Mn(this.settings)&&(S.setFloat("tileCountX",this.settings.uTileCount),S.setFloat("tileCountY",this.settings.vTileCount)),this.bindSoft(S),this.writeSpriteParams(S,n),y&&(this.writeFixedLighting(S),"scene"===p)){const t=new a,e=new a,i=new a;S.onBindObservable.add(()=>{const s=Gr.readSceneLight(this.scene,t,e,i);qr.writeBound(S,n=>s?n.setVector3("lightDirection",t).setVector3("lightColor",e).setVector3("ambientColor",i):this.writeFixedLighting(n))})}this.bindFog(S),this.bindImageProcessing(S,o),this.bindSurface(S),S.backFaceCulling="both"!==this.settings.renderFace,S.cullBackFaces="back"!==this.settings.renderFace,this.settings.materialTransparent?S.alphaMode=this.settings.materialBlendMode:S.alphaMode=r.ALPHA_DISABLE,S.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,S.forceDepthWrite=this.settings.materialDepthWrite,S.disableDepthWrite=!this.settings.materialDepthWrite,S.depthFunction=this.settings.materialDepthTest?0:r.ALWAYS,this.shaderMaterial?.dispose(!1,!1),this.mesh.material=S,this.shaderMaterial=S}writeSpriteParams(t,e){e&&t.setFloat("reflectionLevel",this.settings.reflectionLevel);const i=this.settings.renderMode===Rs.Mesh?this.settings.rim:void 0;i&&(t.setVector3("rimColor",new a(i.color[0],i.color[1],i.color[2])),t.setVector2("rimParams",new c(i.power,i.strength)));const s=wn(this.settings.renderMode)?this.settings.pivot:void 0;s&&t.setVector3("pivot",new a(s.x,s.y,s.z));const n=this.sizeLimits();n&&t.setVector2("sizeLimits",n)}writeLiveUniforms(t){super.writeLiveUniforms(t),this.writeSpriteParams(t,this.usesEnvAtlas())}usesEnvAtlas(){const t=this.settings.reflectionAtlas;return this.settings.renderMode===Rs.Mesh&&!!t&&t.isReady()}applyMeshLighting(t){this.storeFixedLighting(t);const e=this.shaderMaterial;null!==e&&this.settings.renderMode===Rs.Mesh&&"unlit"!==this.settings.lighting&&this.writeFixedLighting(e)}storeFixedLighting(t){this.fixedLightDirection.copyFrom(t.direction),this.fixedLightColor.set(t.color.r,t.color.g,t.color.b),this.fixedAmbientColor.set(t.ambient.r,t.ambient.g,t.ambient.b)}writeFixedLighting(t){t.setVector3("lightDirection",this.fixedLightDirection),t.setVector3("lightColor",this.fixedLightColor),t.setVector3("ambientColor",this.fixedAmbientColor)}static readSceneLight(t,e,i,s){const n=t.lights;for(let r=0;r<n.length;r++){const o=n[r],a=o.getClassName();if("DirectionalLight"!==a&&"HemisphericLight"!==a||!o.isEnabled())continue;const h=o.intensity,l=o.diffuse,c=t.ambientColor;i.set(l.r*h,l.g*h,l.b*h),s.set(c.r,c.g,c.b);const u=o.direction;if("DirectionalLight"===a)e.copyFrom(u);else{e.copyFrom(u).scaleInPlace(-1);const t=o.groundColor;t&&(s.x+=t.r*h,s.y+=t.g*h,s.z+=t.b*h)}return!0}return!1}update(){let t=0,e=0;const i=this.settings.renderMode,s=i===Rs.Mesh,n=i===Rs.StretchedBillBoard,r=i===Rs.Beam,o=n||r,a=wn(i),h=this.getVisibleSystems();for(let t=0;t<h.length;t++)e+=h[t].particleNum;this.fitBuffers(e);for(let e=0;e<h.length;e++){const i=h[e],o=i.particleNum;if(0===o)continue;const l=i.particles,c=this.quaternion2_,u=this.vector2_,d=this.vector3_,f=i.worldSpace,m=i.emitter.matrixWorld;if(s&&!f)m.decompose(u,c,d);else{const t=m.elements;d.set(Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]),Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}n&&!f&&this.rotationMat_.setFromMatrix4(m);const p=Math.abs(d.x),y=Math.abs(d.y),g=Math.abs(d.z),v=n?i.rendererEmitterSettings:void 0,x=void 0===v||0===v.speedFactor?.001:v.speedFactor,S=v?.lengthFactor??0,b=i.store,w=void 0!==b,M=void 0!==b&&!0!==i.onlyUsedByOther,z=i.simulationResidual??0,_=0===z?0:z/(i.simulationStep??z);w&&(0!==_&&o>0&&b.previousColor!==b.color?Gr.continueColor(this.colorBuffer,4*t,b,o,_):this.colorBuffer.set(b.color.subarray(0,4*o),4*t));let A=!1;if(void 0!==b&&f)0!==_&&o>0?Gr.extrapolate(this.offsetBuffer,3*t,b,o,_):this.offsetBuffer.set(b.position.subarray(0,3*o),3*t),0!==_&&o>0&&b.previousSize!==b.size?Gr.continueVector3(this.sizeBuffer,3*t,b.size,b.previousSize,o,_):this.sizeBuffer.set(b.size.subarray(0,3*o),3*t),A=!0;else if(M&&o>0){const e=3*t,i=e+3*o,s=this.offsetBuffer;0!==_?Gr.extrapolate(s,e,b,o,_):s.set(b.position.subarray(0,3*o),e);const n=m.elements,r=n[0],a=n[1],h=n[2],l=n[3],c=n[4],u=n[5],d=n[6],f=n[7],v=n[8],x=n[9],S=n[10],w=n[11],M=n[12],z=n[13],P=n[14],O=n[15];for(let t=e;t<i;t+=3){const e=s[t],i=s[t+1],n=s[t+2],o=1/(l*e+f*i+w*n+O);s[t]=(r*e+c*i+v*n+M)*o,s[t+1]=(a*e+u*i+x*n+z)*o,s[t+2]=(h*e+d*i+S*n+P)*o}const T=this.sizeBuffer;0!==_&&b.previousSize!==b.size?Gr.continueVector3(T,e,b.size,b.previousSize,o,_):T.set(b.size.subarray(0,3*o),e);for(let t=e;t<i;t+=3)T[t]*=p,T[t+1]*=y,T[t+2]*=g;A=!0}const P=t;if(M&&!s){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),P);const i=this.rotationBuffer;if(i.set(e.rotation.subarray(0,o),P),0!==z){const t=e.angularVelocity;for(let e=0;e<o;e++)i[P+e]+=t[e]*z}n&&this.velocityBuffer&&Gr.writeVelocities(this.velocityBuffer,4*P,e,o,_,f?null:this.rotationMat_,x,S),t+=o}else if(M&&b.rotationQuaternion.length>0){const e=b;this.uvTileBuffer.set(e.uvTile.subarray(0,o),P),Gr.writeQuaternions(this.rotationBuffer,4*P,e,o,_,f?null:c),t+=o}else for(let e=0;e<o;e++,t++){const i=l[e];if(s){let e=i.rotation;const s=i.angularVelocity;let n;if(0!==_&&s instanceof at&&(e=this.quaternion4_.copy(e).multiply(Gr.partialTurn(s,_,this.quaternion5_))),f)n=e;else{let t;t=i.parentMatrix?this.quaternion3_.setFromRotationMatrix(i.parentMatrix):c,n=this.quaternion_,n.copy(t).multiply(e)}const r=4*t;this.rotationBuffer[r]=n.x,this.rotationBuffer[r+1]=n.y,this.rotationBuffer[r+2]=n.z,this.rotationBuffer[r+3]=n.w}else{const e=i.angularVelocity;this.rotationBuffer[t]=i.rotation+("number"==typeof e?e*z:0)}if(!A){const e=i.position,s=i.previousPosition;let n=e.x+(e.x-s.x)*_,r=e.y+(e.y-s.y)*_,o=e.z+(e.z-s.z)*_;if(!f){const t=(i.parentMatrix??m).elements,e=1/(t[3]*n+t[7]*r+t[11]*o+t[15]),s=(t[0]*n+t[4]*r+t[8]*o+t[12])*e,a=(t[1]*n+t[5]*r+t[9]*o+t[13])*e;o=(t[2]*n+t[6]*r+t[10]*o+t[14])*e,n=s,r=a}const a=3*t;this.offsetBuffer[a]=n,this.offsetBuffer[a+1]=r,this.offsetBuffer[a+2]=o;const h=i.size,l=3*t;f||i.parentMatrix?(this.sizeBuffer[l]=h.x,this.sizeBuffer[l+1]=h.y,this.sizeBuffer[l+2]=h.z):(this.sizeBuffer[l]=h.x*p,this.sizeBuffer[l+1]=h.y*y,this.sizeBuffer[l+2]=h.z*g)}if(!w){const e=i.color,s=4*t;this.colorBuffer[s]=e.x,this.colorBuffer[s+1]=e.y,this.colorBuffer[s+2]=e.z,this.colorBuffer[s+3]=e.w}if(this.uvTileBuffer[t]=i.uvTile,n&&this.velocityBuffer){const e=i.velocity,s=i.previousVelocity,n=e.x+(e.x-s.x)*_,r=e.y+(e.y-s.y)*_,o=e.z+(e.z-s.z)*_,a=this.vector_;a.set(n,r,o),f||(i.parentMatrix?(this.rotationMat2_.setFromMatrix4(i.parentMatrix),a.applyMatrix3(this.rotationMat2_)):a.applyMatrix3(this.rotationMat_));const h=4*t;this.velocityBuffer[h]=a.x*x,this.velocityBuffer[h+1]=a.y*x,this.velocityBuffer[h+2]=a.z*x,this.velocityBuffer[h+3]=S}}const O=i.tint;void 0!==O&&t>P&&Gr.applyTint(this.colorBuffer,4*P,t-P,O),a&&void 0!==i.flip&&(void 0!==b?Gr.applyFlip(this.sizeBuffer,3*P,b.flip,o):Gr.applyFlipFromParticles(this.sizeBuffer,3*P,l,o)),r&&this.velocityBuffer&&this.writeBeams(i,P,t-P)}this.mesh.forcedInstanceCount=t,this.refreshBoundingInfo(),0!==t?(this.clearedInstanceUploaded=!1,"none"!==this.settings.sortMode&&this.sortInstances(t,s,o),this.offsetVB.update(this.offsetBuffer.subarray(0,3*t)),this.sizeVB.update(this.sizeBuffer.subarray(0,3*t)),this.colorVB.update(this.colorBuffer.subarray(0,4*t)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,t)),this.rotationVB.update(this.rotationBuffer.subarray(0,s?4*t:t)),o&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4*t))):this.clearedInstanceUploaded||(this.uploadClearedInstance(s,o),this.clearedInstanceUploaded=!0)}writeBeams(t,e,i){const s=this.velocityBuffer,n=this.offsetBuffer,r=this.beamEnd_,o="function"==typeof t.getBeamEnd&&t.getBeamEnd(r);for(let t=e;t<e+i;t++){const e=3*t,i=4*t;s[i]=o?r.x-n[e]:0,s[i+1]=o?r.y-n[e+1]:0,s[i+2]=o?r.z-n[e+2]:0,s[i+3]=0}}static applyTint(t,e,i,s){for(let n=0,r=e;n<i;n++,r+=4)t[r]*=s.x,t[r+1]*=s.y,t[r+2]*=s.z,t[r+3]*=s.w}static applyFlip(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n];0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static applyFlipFromParticles(t,e,i,s){for(let n=0,r=e;n<s;n++,r+=3){const e=i[n].flip;0!==e&&(1&e&&(t[r]=-t[r]),2&e&&(t[r+1]=-t[r+1]))}}static writeQuaternions(t,e,i,s,n,r){const o=i.rotationQuaternion,a=i.angularVelocityQuaternion,h=null!==r,l=h?r.x:0,c=h?r.y:0,u=h?r.z:0,d=h?r.w:1;for(let i=0,r=0,f=e;i<s;i++,r+=4,f+=4){let e=o[r],i=o[r+1],s=o[r+2],m=o[r+3];if(0!==n){const t=a[r]*n,o=a[r+1]*n,h=a[r+2]*n,l=1+(a[r+3]-1)*n,c=1/Math.sqrt(t*t+o*o+h*h+l*l),u=t*c,d=o*c,f=h*c,p=l*c,y=e*p+m*u+i*f-s*d,g=i*p+m*d+s*u-e*f,v=s*p+m*f+e*d-i*u;m=m*p-e*u-i*d-s*f,e=y,i=g,s=v}if(h){const t=l*m+d*e+c*s-u*i,n=c*m+d*i+u*e-l*s,r=u*m+d*s+l*i-c*e;m=d*m-l*e-c*i-u*s,e=t,i=n,s=r}t[f]=e,t[f+1]=i,t[f+2]=s,t[f+3]=m}}static writeVelocities(t,e,i,s,n,r,o,a){const h=i.velocity,l=i.previousVelocity.length>=3*s?i.previousVelocity:h,c=null!==r?r.elements:null;for(let i=0,r=0,u=e;i<s;i++,r+=3,u+=4){let e=h[r],i=h[r+1],s=h[r+2];if(0!==n&&(e+=(e-l[r])*n,i+=(i-l[r+1])*n,s+=(s-l[r+2])*n),null!==c){const t=c[0]*e+c[3]*i+c[6]*s,n=c[1]*e+c[4]*i+c[7]*s;s=c[2]*e+c[5]*i+c[8]*s,e=t,i=n}t[u]=e*o,t[u+1]=i*o,t[u+2]=s*o,t[u+3]=a}}static partialTurn(t,e,i){const s=t.x*e,n=t.y*e,r=t.z*e,o=1+(t.w-1)*e,a=1/Math.sqrt(s*s+n*n+r*r+o*o);return i.x=s*a,i.y=n*a,i.z=r*a,i.w=o*a,i}static continueVector3(t,e,i,s,n,r){for(let o=0,a=0;o<n;o++,a+=3){const n=i[a]+(i[a]-s[a])*r,o=i[a+1]+(i[a+1]-s[a+1])*r,h=i[a+2]+(i[a+2]-s[a+2])*r;t[e+a]=n>0?n:0,t[e+a+1]=o>0?o:0,t[e+a+2]=h>0?h:0}}static continueColor(t,e,i,s,n){const r=i.color,o=i.previousColor;for(let i=0,a=0;i<s;i++,a+=4){const i=r[a]+(r[a]-o[a])*n,s=r[a+1]+(r[a+1]-o[a+1])*n,h=r[a+2]+(r[a+2]-o[a+2])*n,l=r[a+3]+(r[a+3]-o[a+3])*n;t[e+a]=i>0?i:0,t[e+a+1]=s>0?s:0,t[e+a+2]=h>0?h:0,t[e+a+3]=l>0?l:0}}static extrapolate(t,e,i,s,n){const r=i.position,o=i.previousPosition;for(let i=0,a=0;i<s;i++,a+=3){const i=r[a],s=r[a+1],h=r[a+2];t[e+a]=i+(i-o[a])*n,t[e+a+1]=s+(s-o[a+1])*n,t[e+a+2]=h+(h-o[a+2])*n}}uploadClearedInstance(t,e){this.colorBuffer[3]=0,this.sizeBuffer[0]=0,this.sizeBuffer[1]=0,this.sizeBuffer[2]=0,this.colorVB.update(this.colorBuffer.subarray(0,4)),this.sizeVB.update(this.sizeBuffer.subarray(0,3)),this.offsetVB.update(this.offsetBuffer.subarray(0,3)),this.uvTileVB.update(this.uvTileBuffer.subarray(0,1)),t?this.rotationVB.update(this.rotationBuffer.subarray(0,4)):this.rotationVB.update(this.rotationBuffer.subarray(0,1)),e&&this.velocityVB&&this.velocityBuffer&&this.velocityVB.update(this.velocityBuffer.subarray(0,4))}dispose(){this.disposed=!0,this.cancelAtlasRebuild?.(),this.cancelAtlasRebuild=null,this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}Gr.whiteTextureByScene=new WeakMap;const Wr=16;function jr(t){const e=Math.round(Number(t?.tessellation)||0);return Math.min(16,Math.max(0,e))}function Qr(t){const e=Number(t?.curveTension)||0;return Math.min(1,Math.max(0,e))}const Hr=["stretch","tile","distributePerSegment","repeatPerSegment"];function Yr(t){const e=t?.textureMode;return void 0!==e&&Hr.includes(e)?e:"stretch"}function Xr(t){const e=Number(t?.textureScale);return Number.isFinite(e)&&e>0?e:1}function Zr(t){const e=Number(t?.minVertexDistance);return Number.isFinite(e)&&e>0?e:0}function Kr(t){const e=Number(t?.lifetime);return Number.isFinite(e)&&e>0?e:1/0}class to{constructor(){this.position=new Float32Array(0),this.side=new Float32Array(0),this.size=new Float32Array(0),this.color=new Float32Array(0),this.distance=new Float32Array(0)}reserve(t){if(t>this.size.length){const e=Math.max(t,2*this.size.length,64);this.position=new Float32Array(3*e),this.side=new Float32Array(3*e),this.size=new Float32Array(e),this.color=new Float32Array(4*e),this.distance=new Float32Array(e)}return this}writePoint(t,e,i,s,n){const r=3*t;if(n){const t=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);this.position[r]=(n[0]*e+n[4]*i+n[8]*s+n[12])*t,this.position[r+1]=(n[1]*e+n[5]*i+n[9]*s+n[13])*t,this.position[r+2]=(n[2]*e+n[6]*i+n[10]*s+n[14])*t}else this.position[r]=e,this.position[r+1]=i,this.position[r+2]=s}writeSide(t,e,i,s,n){const r=3*t;n?(this.side[r]=n[0]*e+n[4]*i+n[8]*s,this.side[r+1]=n[1]*e+n[5]*i+n[9]*s,this.side[r+2]=n[2]*e+n[6]*i+n[10]*s):(this.side[r]=e,this.side[r+1]=i,this.side[r+2]=s)}writeColor(t,e,i,s,n){const r=4*t;this.color[r]=e,this.color[r+1]=i,this.color[r+2]=s,this.color[r+3]=n}}function eo(t,e,i){return Math.sqrt(Math.sqrt((t[i]-t[e])**2+(t[i+1]-t[e+1])**2+(t[i+2]-t[e+2])**2))}class io extends qr{constructor(t,e,i=null){super(t,e,i),this.uv1Buffer=null,this.drawsNothing=!1,this.initialCapacity=1024,this.vector2_=new ht,this.vector3_=new ht,this.quaternion_=new at,this.samples_=new to,this.curve_=new to,this.cutScratch_=new to,this.maxParticles=this.initialCapacity,this.setupBuffers(),this.rebuildMaterial()}setupBuffers(){this.mesh?.dispose(),this.mesh=new p("trailBatch",this.scene),this.configureMesh(),this.buildGeometryBuffers()}buildGeometryBuffers(){const e=this.maxParticles;this.positionBuffer=new Float32Array(3*e),this.previousBuffer=new Float32Array(3*e),this.nextBuffer=new Float32Array(3*e),this.uvBuffer=new Float32Array(2*e),this.uv1Buffer=this.usesUV1()?new Float32Array(2*e):null,this.sideBuffer=new Float32Array(e),this.widthBuffer=new Float32Array(e),this.colorBuffer=new Float32Array(4*e),this.indexBuffer=new Uint32Array(3*e);for(let t=0;t<this.sideBuffer.length;t+=2)this.sideBuffer[t]=1,this.sideBuffer[t+1]=-1;this.positionBuffer[0]=0,this.positionBuffer[1]=0,this.positionBuffer[2]=0,this.positionBuffer[3]=1,this.positionBuffer[4]=0,this.positionBuffer[5]=0,this.positionBuffer[6]=0,this.positionBuffer[7]=1,this.positionBuffer[8]=0,this.positionBuffer[9]=1,this.positionBuffer[10]=1,this.positionBuffer[11]=0,this.indexBuffer[0]=0,this.indexBuffer[1]=1,this.indexBuffer[2]=2,this.indexBuffer[3]=1,this.indexBuffer[4]=3,this.indexBuffer[5]=2,this.mesh.setVerticesData(t.PositionKind,this.positionBuffer,!0),this.mesh.setVerticesData(t.UVKind,this.uvBuffer,!0),this.uv1Buffer&&this.mesh.setVerticesData(t.UV2Kind,this.uv1Buffer,!0),this.mesh.setVerticesData(t.ColorKind,this.colorBuffer,!0,4),this.mesh.setIndices(this.indexBuffer,null,!0),this.drawsNothing=!1,this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=6);const i=this.scene.getEngine();this.previousVB=new t(i,this.previousBuffer,"previous",!0,!1,3,!1),this.nextVB=new t(i,this.nextBuffer,"next",!0,!1,3,!1),this.sideVB=new t(i,this.sideBuffer,"side",!0,!1,1,!1),this.widthVB=new t(i,this.widthBuffer,"width",!0,!1,1,!1),this.mesh.setVerticesBuffer(this.previousVB),this.mesh.setVerticesBuffer(this.nextVB),this.mesh.setVerticesBuffer(this.sideVB),this.mesh.setVerticesBuffer(this.widthVB),this.mesh.subMeshes&&this.adoptMeshBounds()}expandBuffers(t){for(;t>=this.maxParticles;)this.maxParticles*=2;this.resizeBuffers()}resizeBuffers(){this.previousVB?.dispose(),this.nextVB?.dispose(),this.sideVB?.dispose(),this.widthVB?.dispose(),this.buildGeometryBuffers()}rebuildMaterial(){const t=this.imageProcessing(),e=Nr(this.settings,{depth:this.depth,envAtlasReady:!1,meshUV2:!1,imageProcessing:t}),{defines:i,attributes:s,uniforms:n,samplers:o}=e,a=e.name,h=Dr(this.scene.getEngine());kr(a,e.vertex,e.fragment,h);const l=new f(a,this.scene,{vertex:a,fragment:a},{attributes:s,uniforms:n,samplers:o,defines:i,needAlphaBlending:this.settings.materialTransparent,shaderLanguage:h});this.settings.texture&&l.setTexture("map",this.settings.texture),this.bindFog(l),this.bindImageProcessing(l,t),this.bindSoft(l),this.bindSurface(l),l.backFaceCulling=!1,this.settings.materialTransparent?l.alphaMode=this.settings.materialBlendMode:l.alphaMode=r.ALPHA_DISABLE,l.needDepthPrePass=this.settings.materialDepthWrite&&this.settings.materialTransparent,l.forceDepthWrite=this.settings.materialDepthWrite,l.disableDepthWrite=!this.settings.materialDepthWrite,l.depthFunction=this.settings.materialDepthTest?0:r.ALWAYS,this.mesh.material?.dispose(!1,!1),this.mesh.material=l}trailSamples(t){return this.samples_.reserve(t)}cutLastSegment(t,e,i,s,n){const r=e-1-i,o=this.cutScratch_.reserve(i+1);o.position.set(t.position.subarray(3*r,3*e)),o.side.set(t.side.subarray(3*r,3*e)),o.size.set(t.size.subarray(r,e)),o.color.set(t.color.subarray(4*r,4*e)),o.distance.set(t.distance.subarray(r,e));for(let e=1;e<=i;e++){const a=s*e,h=Math.min(i-1,Math.floor(a)),l=a-h,c=r+e;for(let e=0;e<3;e++)t.position[3*c+e]=o.position[3*h+e]*(1-l)+o.position[3*h+3+e]*l,n&&(t.side[3*c+e]=o.side[3*h+e]*(1-l)+o.side[3*h+3+e]*l);t.size[c]=o.size[h]*(1-l)+o.size[h+1]*l,t.distance[c]=o.distance[h]*(1-l)+o.distance[h+1]*l;for(let e=0;e<4;e++)t.color[4*c+e]=o.color[4*h+e]*(1-l)+o.color[4*h+4+e]*l}}tessellate(t,e,i,s,n,r){const o=this.curve_.reserve((i-1)*(s+1)+1),a=t.position,h=t.side,l=o.position,c=o.side,u=1-n;let d=0;for(let n=0;n+1<i;n++){const i=3*n,f=i+3;let m=0,p=0,y=0,g=0,v=0,x=0,S=i,b=f;if(n+1<e){S=3*(n>0?n-1:n),b=3*(n+2<e?n+2:n+1);const t=eo(a,i,f);if(t>1e-6){const e=eo(a,S,i),s=eo(a,f,b);y=u,g=u,e>1e-6&&(m=u*t/e,p=-u*t/(e+t)),s>1e-6&&(v=-u*t/(t+s),x=u*t/s)}}const w=0===m&&0===p&&0===y&&0===g&&0===v&&0===x,M=r?Math.sqrt(h[i]*h[i]+h[i+1]*h[i+1]+h[i+2]*h[i+2]):0,z=r?Math.sqrt(h[f]*h[f]+h[f+1]*h[f+1]+h[f+2]*h[f+2]):0;for(let e=0;e<=s;e++,d++){const u=e/(s+1),_=u*u,A=_*u,P=w?1-u:2*A-3*_+1,O=A-2*_+u,T=w?u:-2*A+3*_,V=A-_,E=3*d;for(let t=0;t<3;t++){const e=a[i+t],s=a[f+t],n=m*(e-a[S+t])+p*(s-a[S+t])+y*(s-e),r=g*(s-e)+v*(a[b+t]-e)+x*(a[b+t]-s);l[E+t]=P*e+O*n+T*s+V*r}if(r){let t=0,e=0,s=0;for(let n=0;n<3;n++){const r=h[i+n],o=h[f+n],a=P*r+O*(m*(r-h[S+n])+p*(o-h[S+n])+y*(o-r))+T*o+V*(g*(o-r)+v*(h[b+n]-r)+x*(h[b+n]-o));0===n?t=a:1===n?e=a:s=a}let n=Math.sqrt(t*t+e*e+s*s);if(n<=1e-6*Math.max(M,z,1e-6)){const r=u<.5?i:f;t=h[r],e=h[r+1],s=h[r+2],n=u<.5?M:z}const r=n>0?(M+(z-M)*u)/n:0;c[E]=t*r,c[E+1]=e*r,c[E+2]=s*r}o.size[d]=t.size[n]+(t.size[n+1]-t.size[n])*u,o.distance[d]=t.distance[n]+(t.distance[n+1]-t.distance[n])*u;const $=4*n,C=4*d;for(let e=0;e<4;e++)o.color[C+e]=t.color[$+e]+(t.color[$+4+e]-t.color[$+e])*u}}const f=3*(i-1),m=3*d;for(let t=0;t<3;t++)l[m+t]=a[f+t],c[m+t]=h[f+t];o.size[d]=t.size[i-1],o.distance[d]=t.distance[i-1];for(let e=0;e<4;e++)o.color[4*d+e]=t.color[4*(i-1)+e];return o}writeSweptPair(t,e,i,s,n,r,o,a){const h=this.positionBuffer;h[t]=e+n*a,h[t+1]=i+r*a,h[t+2]=s+o*a,h[t+3]=e-n*a,h[t+4]=i-r*a,h[t+5]=s-o*a}static ensureWorldMatrix(t){const e=t.emitter;!e.computeWorldMatrix||e.isSynchronized&&e.isSynchronized()||e.computeWorldMatrix(!0)}update(){let t=0,e=0,i=0;const s=this.getVisibleSystems();for(let t=0;t<s.length;t++){const e=s[t],n=e.particles,r=jr(e.rendererEmitterSettings);for(let t=0;t<e.particleNum;t++){const e=n[t].historyCount;0!==e&&(i+=2*(e*(r+1)+1))}}this.fitBuffers(i);for(let i=0;i<s.length;i++){const n=s[i],r=t;io.ensureWorldMatrix(n);const o=this.quaternion_,a=this.vector2_,h=this.vector3_,l=n.emitter.matrixWorld;l.decompose(a,o,h);const c=n.particles,u=n.particleNum,d=this.settings.uTileCount,f=this.settings.vTileCount,m=1/d,p=1/f,y=n.worldSpace,g=(Math.abs(h.x)+Math.abs(h.y)+Math.abs(h.z))/3,v=n.rendererEmitterSettings,x=Boolean(v.uvFromHead),S=this.uv1Buffer,b=Boolean(v.colorFromParticle),w=y||Boolean(v.recordWorldSpace),M=v.sideAxis,z=v.followLocalOrigin?0:n.simulationResidual??0,_=0===z?0:z/(n.simulationStep??z),A=Math.abs(_)<1e-4?0:_,P=jr(v),O=Qr(v),T=Yr(v),V="stretch"===T?0:"tile"===T?1:"repeatPerSegment"===T?3:2,E=Xr(v),$=Zr(v)>0;for(let i=0;i<u;i++){const s=c[i],n=s.historyCount;if(0===n)continue;const r=s.historyCapacity,o=s.historyPositions,a=s.historySizes,h=s.historyDistances,u=s.historySides,v=void 0!==M&&u.length>=3*r,z=b?s.store.color:s.historyColors,_=4*s.storeIndex,{column:T,row:C}=Gn(s.uvTile,d,f),I=(s.parentMatrix??l).elements,N=y||s.parentMatrix?1:g,F=w||s.parentMatrix?1:g,B=s.age<s.life,U=B&&A>0,R=n+(U?1:0),L=this.trailSamples(R);let D=s.getHistoryIndex(0);for(let t=0;t<n;t++){const e=o;if(L.writePoint(t,e[3*D],e[3*D+1],e[3*D+2],w?null:I),v){const e=u;L.writeSide(t,e[3*D],e[3*D+1],e[3*D+2],w?null:I)}L.size[t]=a[D],L.distance[t]=h[D];const i=b?_:4*D;L.writeColor(t,z[i],z[i+1],z[i+2],z[i+3]),D=D+1===r?0:D+1}if(U){const t=s.previousPosition,e=s.position,i=n;let r=e.x+(e.x-t.x)*A,a=e.y+(e.y-t.y)*A,h=e.z+(e.z-t.z)*A;if(L.writePoint(i,r,a,h,y?null:I),w&&!y){const t=1/(I[3]*r+I[7]*a+I[11]*h+I[15]),e=(I[0]*r+I[4]*a+I[8]*h+I[12])*t,i=(I[1]*r+I[5]*a+I[9]*h+I[13])*t;h=(I[2]*r+I[6]*a+I[10]*h+I[14])*t,r=e,a=i}const l=3*s.getHistoryIndex(n-1),c=r-o[l],u=a-o[l+1],d=h-o[l+2];L.distance[i]=L.distance[i-1]+Math.sqrt(c*c+u*u+d*d),v&&L.writeSide(i,M.x,M.y,M.z,I),L.size[i]=L.size[i-1];const f=s.color;L.writeColor(i,f.x,f.y,f.z,f.w)}const k=P>0?this.tessellate(L,n,R,P,O,v):L,q=P>0?(R-1)*(P+1)+1:R,J=P+1,G=B&&A<0&&n>1;let W=1+A;if(G&&$){const t=k.distance,e=t[q-1]-t[q-1-J];if(e>1e-9){const t=s.previousPosition,i=s.position;let n=i.x-t.x,r=i.y-t.y,o=i.z-t.z;if(w&&!y){const t=I[0]*n+I[4]*r+I[8]*o,e=I[1]*n+I[5]*r+I[9]*o;o=I[2]*n+I[6]*r+I[10]*o,n=t,r=e}const a=Math.sqrt(n*n+r*r+o*o);W=1+A*Math.min(1,a/e)}}G&&this.cutLastSegment(k,q,J,W,v);const j=n-1+(U?A:G?W-1:0),Q=1/Math.max(.001,j),H=(R-2)*J,Y=k.position,X=k.distance,Z=X[0],K=X[q-1],tt=0===V&&K-Z>1e-6,et=1/Math.max(1e-6,K-Z),it=F*E,st=Math.floor(Z*it),nt=(f-C-1)*p,rt=(f-C)*p;for(let i=0;i<q;i++,t+=2){const s=3*i,r=i>0?s-3:s,o=i+1<q?s+3:s,a=Y[s],h=Y[s+1],l=Y[s+2],c=k.size[i],u=3*t;if(v){const e=k.side;this.writeSweptPair(u,a,h,l,e[s],e[s+1],e[s+2],.5*c),this.widthBuffer[t]=0,this.widthBuffer[t+1]=0}else this.positionBuffer[u]=a,this.positionBuffer[u+1]=h,this.positionBuffer[u+2]=l,this.positionBuffer[u+3]=a,this.positionBuffer[u+4]=h,this.positionBuffer[u+5]=l,this.widthBuffer[t]=c*N,this.widthBuffer[t+1]=c*N;this.previousBuffer[u]=Y[r],this.previousBuffer[u+1]=Y[r+1],this.previousBuffer[u+2]=Y[r+2],this.previousBuffer[u+3]=Y[r],this.previousBuffer[u+4]=Y[r+1],this.previousBuffer[u+5]=Y[r+2],this.nextBuffer[u]=Y[o],this.nextBuffer[u+1]=Y[o+1],this.nextBuffer[u+2]=Y[o+2],this.nextBuffer[u+3]=Y[o],this.nextBuffer[u+4]=Y[o+1],this.nextBuffer[u+5]=Y[o+2];const d=2*t;let f;if(tt){const t=(X[i]-Z)*et;f=(x?1-t:t)*E}else if(1===V)f=x?(K-X[i])*it:X[i]*it-st;else{let t=i/J;if(i>H&&(U||G)){const e=(i-H)/J;t=U?n-1+A*e:n-2+W*e}if(3!==V){const e=Math.min(1,t*Q);f=(x?1-e:e)*E}else f=(x?j-t:t)*E}const p=(f+T)*m;this.uvBuffer[d]=p,this.uvBuffer[d+1]=nt,this.uvBuffer[d+2]=p,this.uvBuffer[d+3]=rt,S&&(S[d]=f,S[d+1]=0,S[d+2]=f,S[d+3]=1);const y=k.color,g=4*i,b=4*t;this.colorBuffer[b]=y[g],this.colorBuffer[b+1]=y[g+1],this.colorBuffer[b+2]=y[g+2],this.colorBuffer[b+3]=y[g+3],this.colorBuffer[b+4]=y[g],this.colorBuffer[b+5]=y[g+1],this.colorBuffer[b+6]=y[g+2],this.colorBuffer[b+7]=y[g+3],i+1<q&&(this.indexBuffer[3*e]=t,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+2,e++,this.indexBuffer[3*e]=t+2,this.indexBuffer[3*e+1]=t+1,this.indexBuffer[3*e+2]=t+3,e++)}}const C=n.tint;if(void 0!==C){const e=this.colorBuffer;for(let i=4*r,s=4*t;i<s;i+=4)e[i]*=C.x,e[i+1]*=C.y,e[i+2]*=C.z,e[i+3]*=C.w}this.measureSystemBounds(n,r,t)}this.refreshBoundingInfo(),this.uploadGeometry(t,e)}measureSystemBounds(t,e,i){if(i<=e||"function"!=typeof t.setWorldBounds)return;const s=this.positionBuffer;let n=1/0,r=1/0,o=1/0,a=-1/0,h=-1/0,l=-1/0;for(let t=3*e,c=3*i;t<c;t+=3){const e=s[t],i=s[t+1],c=s[t+2];e<n&&(n=e),e>a&&(a=e),i<r&&(r=i),i>h&&(h=i),c<o&&(o=c),c>l&&(l=c)}const c=this.widthBuffer;let u=0;for(let t=e;t<i;t+=2){const e=c[t];e>u&&(u=e)}t.setWorldBounds(n,r,o,a,h,l,u)}uploadGeometry(e,i){const s=this.mesh.geometry,n=s?.getIndexBuffer();if(e>0&&i>0){this.mesh.updateVerticesData(t.PositionKind,this.positionBuffer.subarray(0,3*e)),this.mesh.updateVerticesData(t.UVKind,this.uvBuffer.subarray(0,2*e)),this.uv1Buffer&&this.mesh.updateVerticesData(t.UV2Kind,this.uv1Buffer.subarray(0,2*e)),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,3*i),0),this.previousVB.update(this.previousBuffer.subarray(0,3*e)),this.nextVB.update(this.nextBuffer.subarray(0,3*e)),this.widthVB.update(this.widthBuffer.subarray(0,e));const s=this.mesh.getVertexBuffer(t.ColorKind);s&&s.update(this.colorBuffer.subarray(0,4*e)),this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.mesh.subMeshes[0].indexCount=3*i,this.mesh.subMeshes[0].verticesCount=e),this.drawsNothing=!1}else this.mesh.subMeshes&&this.mesh.subMeshes.length>0&&(this.drawsNothing||(this.indexBuffer.fill(0,0,6),n&&this.scene.getEngine().updateDynamicIndexBuffer(n,this.indexBuffer.subarray(0,6),0),this.drawsNothing=!0),this.mesh.subMeshes[0].indexCount=6,this.mesh.subMeshes[0].verticesCount=1)}adoptMeshBounds(){const t=this.mesh.getBoundingInfo();for(const e of this.mesh.subMeshes)e.setBoundingInfo(t)}dispose(){this.mesh.material&&this.mesh.material.dispose(),super.dispose()}}class so extends n{get batches(){return this.batchList}get systemToBatchIndex(){return this.batchIndexOf}constructor(t,e){super(t,e),this.batchList=[],this.batchIndexOf=new Map,this.elapsed=0,this.depth=null,this.systems=[],this.orderedSystems=[],this.orderedSystemsStale=!0,this.batchEmptyFrames=[],this.adaptivePerformanceState={enabled:!1,targetFrameMs:16.7,minQuality:.35,maxQuality:1,decreaseStep:.08,increaseStep:.02,currentQuality:1,lastFrameCpuMs:0},this.lastAppliedQuality=Number.NaN,this.meshLighting=Ls(),this.cullingEnabled=!0,this.catchUpBudgetMs=2,this.simulationBudgetMs=1/0,this.cameraPlanes=[],this.cameraMasks=[],this.cameraCount=0,this.boundsMin=new ht,this.boundsMax=new ht}collectCameras(){var t;const e=this.getScene(),n=e.activeCameras,r=e.activeCamera,o=n&&n.length>0?n:r?[r]:[];for(let e=0;e<o.length;e++){const n=o[e];n.getViewMatrix(),n.getProjectionMatrix();const r=(t=this.cameraPlanes)[e]??(t[e]=[0,1,2,3,4,5].map(()=>new s(0,0,0,0)));i.GetPlanesToRef(n.getTransformationMatrix(),r),this.cameraMasks[e]=n.layerMask}return this.cameraCount=o.length,o.length}isSystemInView(t){const e=this.boundsMin,i=this.boundsMax;if(!t.getWorldBounds(e,i))return!0;const s=t.layers.mask;for(let t=0;t<this.cameraCount;t++){if(0===(this.cameraMasks[t]&s))continue;const n=this.cameraPlanes[t];let r=!0;for(let t=0;t<6;t++){const s=n[t],o=s.normal,a=o.x>=0?i.x:e.x,h=o.y>=0?i.y:e.y,l=o.z>=0?i.z:e.z;if(o.x*a+o.y*h+o.z*l+s.d<0){r=!1;break}}if(r)return!0}return!1}static clamp(t,e,i){return Math.max(e,Math.min(i,t))}addSystem(t){if(this.isDisposed())throw new Error("BatchedRenderer.addSystem: the renderer has been disposed");const e=t;if(e.emitter.getScene()!==this.getScene())throw new Error("BatchedRenderer.addSystem: the system belongs to another scene");const i=e._renderer;void 0!==i&&i!==this&&i.deleteSystem(t),e._renderer=this,this.removeFromBatch(t),-1===this.systems.indexOf(t)&&(this.systems.push(t),this.orderedSystemsStale=!0),this.adaptivePerformanceState.enabled&&e.setQualityFactor(this.adaptivePerformanceState.currentQuality),this.assignToBatch(e)}assignToBatch(t){const e=t,i=t.getRendererSettings(),s=_n(i);for(let t=0;t<this.batchList.length;t++)if(On(this.batchList[t].settings,s))return this.batchList[t].addSystem(e),void this.batchIndexOf.set(e,t);let n;const r=this.getScene();switch(i.renderMode){case Rs.Trail:n=new io(i,r,this.depth);break;case Rs.Mesh:case Rs.BillBoard:case Rs.VerticalBillBoard:case Rs.HorizontalBillBoard:case Rs.StretchedBillBoard:case Rs.Beam:n=new Gr(i,r,this.depth);break;default:throw new Error(`Unsupported render mode: ${i.renderMode}`)}n.attachTo(this),n.applyMeshLighting(this.meshLighting),n.addSystem(e),this.batchList.push(n),this.batchEmptyFrames.push(0),this.batchIndexOf.set(e,this.batchList.length-1)}deleteSystem(t){const e=this.removeFromBatch(t),i=this.systems.indexOf(t);-1!==i&&(this.systems.splice(i,1),this.orderedSystemsStale=!0);const s=this.orderedSystems.indexOf(t);return-1!==s&&this.orderedSystems.splice(s,1),e}removeFromBatch(t){const e=this.batchIndexOf.get(t);return void 0!==e&&(this.batchList[e].removeSystem(t),this.batchIndexOf.delete(t),!0)}updateSystem(t){const e=this.batchIndexOf.get(t);if(void 0!==e){const i=this.batchList[e],s=_n(t.getRendererSettings());if(1===i.systems.size&&An(i.settings,s)&&!this.batchList.some(t=>t!==i&&On(t.settings,s)))return void i.applyLiveSettings(s)}this.removeFromBatch(t),this.addSystem(t)}setDepthTexture(t,e={}){this.depth=t?En(t,e):null;for(const t of this.batchList)t.applyDepthTexture(this.depth)}get depthTexture(){return this.depth?.texture??null}set depthTexture(t){this.setDepthTexture(t)}get depthEncoding(){return this.depth?.encoding??null}setMeshLighting(t){const e=this.meshLighting;t.direction&&(e.direction=t.direction.clone()),t.color&&(e.color=t.color.clone()),t.ambient&&(e.ambient=t.ambient.clone());for(const t of this.batchList)t.applyMeshLighting(e)}getMeshLighting(){const t=this.meshLighting;return{direction:t.direction.clone(),color:t.color.clone(),ambient:t.ambient.clone()}}configureAdaptivePerformance(t={}){const e=this.adaptivePerformanceState,i=so.clamp(t.minQuality??e.minQuality,.1,1),s=so.clamp(t.maxQuality??e.maxQuality,i,1);e.targetFrameMs=Math.max(t.targetFrameMs??e.targetFrameMs,.1),e.minQuality=i,e.maxQuality=s,e.decreaseStep=Math.max(t.decreaseStep??e.decreaseStep,.001),e.increaseStep=Math.max(t.increaseStep??e.increaseStep,.001),e.currentQuality=so.clamp(e.currentQuality,e.minQuality,e.maxQuality),e.enabled=!0,this.lastAppliedQuality=Number.NaN}disableAdaptivePerformance(t=!0){this.adaptivePerformanceState.enabled=!1,t&&(this.adaptivePerformanceState.currentQuality=this.adaptivePerformanceState.maxQuality,this.applyAdaptiveQuality())}getAdaptivePerformanceState(){return{...this.adaptivePerformanceState}}applyAdaptiveQuality(){const t=this.adaptivePerformanceState.currentQuality;if(t!==this.lastAppliedQuality){for(let e=0;e<this.systems.length;e++)this.systems[e].setQualityFactor(t);this.lastAppliedQuality=t}}_invalidateUpdateOrder(){this.orderedSystemsStale=!0}orderSystems(){if(!this.orderedSystemsStale)return this.orderedSystems;const t=[],e=new Set,i=new Set,s=new Set(this.systems),n=r=>{if(!i.has(r)&&!e.has(r)){e.add(r);for(const t of(t=>{const e=[];for(const i of t.behaviors??[]){if("EmitSubParticleSystem"!==i.type)continue;const t=i.subParticleSystem,n="object"==typeof t?t.system:void 0;void 0!==n&&s.has(n)&&e.push(n)}return e})(r))n(t);e.delete(r),i.add(r),t.push(r)}};for(const t of this.systems)n(t);return t.reverse(),this.orderedSystems=t,this.orderedSystemsStale=!1,t}update(t){this.elapsed+=t;const e=this.adaptivePerformanceState,i=e.enabled?performance.now():0;e.enabled&&this.applyAdaptiveQuality();const s=this.orderSystems(),n=this.cullingEnabled?this.collectCameras():0,r=this.simulationBudgetMs!==1/0||this.catchUpBudgetMs!==1/0?performance.now():0,o=this.simulationBudgetMs===1/0?1/0:r+this.simulationBudgetMs,a=this.catchUpBudgetMs===1/0?1/0:r+this.catchUpBudgetMs;for(let e=0;e<s.length;e++){const i=s[e];i.emitter.visible&&(i.culled=n>0&&"always"!==i.cullingMode&&!0!==i.onlyUsedByOther&&!this.isSystemInView(i),i.update(t,o,a)),s[e]!==i&&e--}this.refreshBatches(),e.enabled&&(e.lastFrameCpuMs=performance.now()-i,e.lastFrameCpuMs>e.targetFrameMs?e.currentQuality=so.clamp(e.currentQuality-e.decreaseStep,e.minQuality,e.maxQuality):e.currentQuality=so.clamp(e.currentQuality+e.increaseStep,e.minQuality,e.maxQuality))}refreshBatches(){const t=this.batchEmptyFrames;for(let e=0;e<this.batchList.length;e++){const i=this.batchList[e];if(i.time=this.elapsed,i.systems.size>0){t[e]=0,i.update();continue}const s=(t[e]??0)+1;t[e]=s,1===s?i.update():s>so.EMPTY_BATCH_GRACE_FRAMES&&(this.removeBatch(e),e--)}}removeBatch(t){this.batchList[t].dispose(),this.batchList.splice(t,1),this.batchEmptyFrames.splice(t,1);for(const[e,i]of this.batchIndexOf)i>t&&this.batchIndexOf.set(e,i-1)}getBatchRenderStats(){return this.batchList.map((t,e)=>{let i=0;const s=[];for(const e of t.systems){const t=e;i+=t.particleNum,s.push(t.emitter.name)}return{batchIndex:e,renderMode:t.settings.renderMode,instanceCount:t.mesh.forcedInstanceCount??0,particleCount:i,systemNames:s}})}dispose(){for(const t of this.batchList)t.dispose();this.batchList.length=0,this.batchEmptyFrames.length=0;for(const t of this.systems)t._renderer===this&&(t._renderer=void 0);this.systems.length=0,this.orderedSystems=[],this.orderedSystemsStale=!0,this.batchIndexOf.clear(),super.dispose()}}so.EMPTY_BATCH_GRACE_FRAMES=120;const no=new WeakMap,ro=new WeakMap;function oo(t,e,i){if(no.has(t))return;const s={textures:new Set(e),materials:new Set(i)};for(const t of[...s.textures,...s.materials])ro.set(t,(ro.get(t)??0)+1);no.set(t,s),t.onDisposeObservable.addOnce(()=>ao(t))}function ao(t){const e=no.get(t);if(void 0!==e){no.delete(t);for(const t of[...e.materials,...e.textures]){const e=(ro.get(t)??1)-1;e>0?ro.set(t,e):(ro.delete(t),t.dispose())}}}function ho(t){t.dispose(),ao(t)}const lo=[0,0,0],co=new ht,uo=new ht,fo=1e-12;function mo(t,e,i,s){const n=4*e,r=i[e];if(r>fo){const e=s/r;return t[n]*=e,t[n+1]*=e,void(t[n+2]*=e)}const o=(e+1)%3,a=(e+2)%3;i[o]>fo&&i[a]>fo?(co.set(t[4*o],t[4*o+1],t[4*o+2]),uo.set(t[4*a],t[4*a+1],t[4*a+2]),co.cross(uo).normalize().multiplyScalar(s),t[n]=co.x,t[n+1]=co.y,t[n+2]=co.z):(t[n]=0===e?s:0,t[n+1]=1===e?s:0,t[n+2]=2===e?s:0)}let po=0;class yo extends n{get matrixWorld(){const t=this.getWorldMatrix(),e=t.updateFlag,i=this.system?.scalingMode??"hierarchy";if(e===this._matrixWorldFlag&&i===this._matrixWorldMode)return this._matrixWorld;this._matrixWorldFlag=e,this._matrixWorldMode=i;const s=this._matrixWorld.elements,n=t.m;for(let t=0;t<16;t++)s[t]=n[t];if(this._shapeScale.set(1,1,1),"hierarchy"===i||"local"===i&&!this.parent)return this._matrixWorld;const r=this.scaling,o=this.scalingDeterminant,a=lo;for(let t=0;t<3;t++){const e=4*t;a[t]=Math.sqrt(s[e]*s[e]+s[e+1]*s[e+1]+s[e+2]*s[e+2])}for(let t=0;t<3;t++){const e="local"===i?Math.abs((0===t?r.x:1===t?r.y:r.z)*o):1;"shape"===i&&this._shapeScale.setComponent(t,a[t]),mo(s,t,a,e)}return this._matrixWorld}get shapeScale(){return this._shapeScale}get visible(){return this.isEnabled()}set visible(t){this.setEnabled(t)}get uuid(){return Ns(this)}constructor(t,e){super("particleEmitter",e||void 0),this._matrixWorld=new ft,this._matrixWorldFlag=-1,this._shapeScale=new ht(1,1,1),this.system=t}dispose(t,e=!1){this.isDisposed()||(super.dispose(t,e),po>0||this.system.dispose?.())}clone(t){const e=this.system.clone().emitter;return e.name=t??this.name,e.position.copyFrom(this.position),e.rotation.copyFrom(this.rotation),e.scaling.copyFrom(this.scaling),this.rotationQuaternion&&(e.rotationQuaternion=this.rotationQuaternion.clone()),e.setEnabled(this.isEnabled(!1)),e}toJSON(t,e={}){return{uuid:Ns(this),type:"ParticleEmitter",name:this.name,position:[this.position.x,this.position.y,this.position.z],rotation:[this.rotation.x,this.rotation.y,this.rotation.z],quaternion:this.rotationQuaternion?[this.rotationQuaternion.x,this.rotationQuaternion.y,this.rotationQuaternion.z,this.rotationQuaternion.w]:void 0,scale:[this.scaling.x,this.scaling.y,this.scaling.z],visible:this.isEnabled(!1),ps:this.system.toJSON(t,e)}}}class go{static runOnAllParticleEmitters(t,e){go.traverseNode(t,t=>{t instanceof yo&&e(t)})}static addToBatchRenderer(t,e){go.runOnAllParticleEmitters(t,t=>{e.addSystem(t.system)})}static play(t){go.runOnAllParticleEmitters(t,t=>{t.system.play()})}static resume(t){go.runOnAllParticleEmitters(t,t=>{t.system.resume()})}static stop(t){go.runOnAllParticleEmitters(t,t=>{t.system.stop()})}static pause(t){go.runOnAllParticleEmitters(t,t=>{t.system.pause()})}static restart(t){go.runOnAllParticleEmitters(t,t=>{t.system.restart()})}static setStopAction(t,e){go.runOnAllParticleEmitters(t,t=>{t.system.stopAction=e})}static setAutoDestroy(t,e){go.runOnAllParticleEmitters(t,t=>{t.system.autoDestroy=e})}static endEmit(t){go.runOnAllParticleEmitters(t,t=>{t.system.endEmit()})}static isEffectFinished(t){let e=!1,i=!0;return go.runOnAllParticleEmitters(t,t=>{e=!0,t.system.isFinished()||(i=!1)}),e&&i}static instantiate(t,e){const i=new Map,s=new Map,r=new Set([t,...t.getDescendants(!1)]),o=t=>{let e=s.get(t);return void 0===e&&(e=t.clone(t.name,null,!0),e.setEnabled(t.isEnabled(!1)),s.set(t,e)),e},a=(t,e,s)=>{let h;if(t instanceof yo)h=t.clone(s),i.set(t,h);else if(t instanceof p)h=o(t),void 0!==s&&(h.name=s);else if(t instanceof _){const e=r.has(t.sourceMesh)?o(t.sourceMesh):void 0;h=t.clone(s??t.name,null,!0,e),h.setEnabled(t.isEnabled(!1))}else{if(!(t instanceof n))return null;h=new n(s??t.name,t.getScene()),h.position.copyFrom(t.position),h.rotation.copyFrom(t.rotation),h.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(h.rotationQuaternion=t.rotationQuaternion.clone()),h.setEnabled(t.isEnabled(!1))}h.parent=e;for(const e of t.getChildren())a(e,h);return h},h=a(t,null,e);!function(t,e){for(let i=t;null!==i;i=i.parent){const t=no.get(i);if(void 0!==t)return void oo(e,t.textures,t.materials)}}(t,h);for(const t of i.values()){const e=t.system;for(const t of e.behaviors)if(t instanceof ci){const e=i.get(t.subParticleSystem);void 0!==e&&(t.subParticleSystem=e)}const n=e.emitterShape;if(n instanceof Bs&&void 0!==n.mesh){const t=s.get(n.mesh);void 0!==t&&(n.mesh=t)}}return h}static getDuration(t){const e=[];go.runOnAllParticleEmitters(t,t=>{e.push(t.system)});const i=new Map;for(let t=0;t<e.length;t++){const s=e[t];for(const t of s.behaviors){if(!(t instanceof ci))continue;const n=t.subParticleSystem?.system;if(void 0!==n&&"object"==typeof n){e.includes(n)||e.push(n);const t=i.get(n)??[];t.push(s),i.set(n,t)}}}const s=new Map,n=t=>{const e=s.get(t);if(void 0!==e)return e;s.set(t,1/0);const r=t.playbackSpeed,o=go.maxOf(t.startLife)/r;let a;if(r>0)if(t.onlyUsedByOther){a=0;for(const e of i.get(t)??[])a=Math.max(a,n(e));a+=t.duration/r+o}else a=t.looping?1/0:(go.maxOf(t.startDelay,0)+t.duration)/r+o;else a=1/0;return s.set(t,a),a};let r=0;for(const t of e)r=Math.max(r,n(t));return r}static maxOf(t,e){if(t instanceof re)return t.value;if(t instanceof oe)return Math.max(t.a,t.b);if(t instanceof ce)return Math.max(go.maxOf(t.curve1,e),go.maxOf(t.curve2,e));let i=-1/0;for(let s=0;s<=32;s++){const n=[];t.startGen(n);const r="function"===t.type?t.genValue(n,e??s/32):t.genValue(n);i=Math.max(i,r)}return i}static traverseNode(t,e){e(t);const i=t.getChildren();for(const t of i)go.traverseNode(t,e)}}class vo{constructor(t,e){this.template=t,this.options=e,this.idle=[],this.playing=new Set,this.systemsOf=new Map,this.restOf=new Map,this.disposed=!1,this.onSystemFinished=t=>{const e=t.particleSystem;for(const t of this.playing){const i=this.systemsOf.get(t);if(void 0!==i&&i.includes(e))return void(go.isEffectFinished(t)&&this.release(t))}};for(let t=0;t<(e.prewarm??0);t++){const t=this.makeCopy();if(null===t)break;this.idle.push(t)}}get activeCount(){return this.playing.size}get idleCount(){return this.idle.length}acquire(t,e=null){if(this.disposed)return null;const i=this.idle.pop()??this.makeCopy();if(null===i)return null;const s=void 0===t||"number"==typeof t.x?{position:t,parent:e}:t;return this.placeCopy(i,s),i.setEnabled(!0),this.playing.add(i),go.restart(i),go.play(i),i}stop(t){this.playing.has(t)&&go.endEmit(t)}release(t){this.playing.delete(t)&&(t.isDisposed()?this.forget(t):(go.stop(t),t.setEnabled(!1),t.parent=null,this.disposed||this.idle.push(t)))}dispose(){this.disposed=!0;for(const t of[...this.playing,...this.idle])this.playing.delete(t),this.disposeCopy(t);this.idle.length=0}makeCopy(){if(this.idle.length+this.playing.size>=(this.options.maxSize??1/0))return null;const t=go.instantiate(this.template),e=[];return go.runOnAllParticleEmitters(t,t=>{const i=t.system;i.ignoreStopAction=!0,i.addEventListener("finished",this.onSystemFinished),e.push(i)}),this.systemsOf.set(t,e),this.restOf.set(t,{position:t.position.clone(),rotation:t.rotation.clone(),rotationQuaternion:t.rotationQuaternion?.clone()??null,scaling:t.scaling.clone()}),go.addToBatchRenderer(t,this.options.renderer),t.setEnabled(!1),t.parent=null,t.onDisposeObservable.addOnce(()=>this.forget(t)),t}placeCopy(t,e){const i=this.restOf.get(t);t.parent=e.parent??null;const s=e.position??i.position,n=e.scaling??i.scaling;t.position.copyFromFloats(s.x,s.y,s.z),t.scaling.copyFromFloats(n.x,n.y,n.z),void 0!==e.rotationQuaternion?t.rotationQuaternion=e.rotationQuaternion.clone():void 0!==e.rotation?(t.rotationQuaternion=null,t.rotation.copyFromFloats(e.rotation.x,e.rotation.y,e.rotation.z)):(t.rotationQuaternion=i.rotationQuaternion?.clone()??null,t.rotation.copyFrom(i.rotation))}forget(t){for(const e of this.systemsOf.get(t)??[])e.removeEventListener("finished",this.onSystemFinished),this.options.renderer.deleteSystem(e),e.dispose();this.systemsOf.delete(t),this.restOf.delete(t),this.playing.delete(t);const e=this.idle.indexOf(t);-1!==e&&this.idle.splice(e,1)}disposeCopy(t){this.forget(t),ho(t)}}const xo=new WeakMap,So=new WeakMap,bo=new WeakSet,wo=new WeakMap,Mo=new WeakSet,zo=new WeakSet;function _o(t){if(!t?.isCube)return null;const e=t.files??t._files;return 6===e?.length?e.slice():null}function Ao(t){return t.getScene?.()??null}function Po(t,e=Ao(t)){return e&&xo.get(t)?.get(e)||null}function Oo(t,e){const i=Ao(e)??Ao(t);i?Vo(t,i,e):console.warn("[babylon.quarks] cacheEnvAtlas: neither the atlas nor the cube has a scene; not cached")}function To(t,e){wo.delete(t);const i=xo.get(t);if(i)for(const[t,s]of[...i])e&&t!==e||(i.delete(t),bo.has(s)&&s.dispose())}function Vo(t,e,i){let s=xo.get(t);s||(s=new Map,xo.set(t,s)),s.set(e,i),!Mo.has(i)&&i.onDisposeObservable&&(Mo.add(i),i.onDisposeObservable.addOnce(()=>{xo.get(t)?.get(e)===i&&xo.get(t).delete(e)})),!zo.has(t)&&t.onDisposeObservable&&(zo.add(t),t.onDisposeObservable.addOnce(()=>{zo.delete(t),To(t)}))}async function Eo(t,e){if("undefined"==typeof document||"undefined"==typeof Image)throw new Error("createEnvAtlasFromFaceUrls requires a DOM Image/canvas environment");const i=await Promise.all(t.map(t=>function(t){return new Promise((e,i)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>e(s),s.onerror=()=>i(new Error(`Failed to load env face ${t}`)),s.src=t})}(t))),s=i[0].width||i[0].naturalWidth;if(!s)throw new Error("Env atlas face image has zero size");const n=document.createElement("canvas");n.width=3*s,n.height=2*s;const r=n.getContext("2d");if(!r)throw new Error("Could not create env atlas canvas");for(let t=0;t<6;t++)r.drawImage(i[t],t%3*s,Math.floor(t/3)*s,s,s);const o=new A(n.toDataURL("image/jpeg",.92),e,{noMipmap:!0,invertY:!1,samplingMode:A.LINEAR_LINEAR});return o.name="quarksEnvAtlas",o}const $o={createFromFaceUrls:Eo};function Co(t,e,i){const s=Po(t,e);if(s)return i(s),s;let n=So.get(t);n||(n=new Map,So.set(t,n));const r=n,o=()=>{const s=r.get(e);if(s)return void s.then(t=>{t&&i(t)});const n=_o(t);if(!n||wo.get(t)===n.join("\n"))return;let o=!1;const a=t.onDisposeObservable?.addOnce(()=>o=!0),h=()=>{r.delete(e),a&&t.onDisposeObservable.remove(a)},l=$o.createFromFaceUrls(n,e).then(s=>(h(),o||e.isDisposed?(s.dispose(),null):(bo.add(s),Vo(t,e,s),i(s),s))).catch(e=>(h(),wo.set(t,n.join("\n")),console.warn("[babylon.quarks] Failed to build env atlas from cubemap faces",e),null));r.set(e,l)};if(t.isReady())o();else{const e=t.onLoadObservable;e?e.addOnce(()=>o()):o()}return Po(t,e)}const Io=new Set(["SizeOverLife","SizeBySpeed"]),No=new Set(["ColorOverLife","ColorBySpeed"]),Fo=new Set(["ApplyForce","Noise","TurbulenceField","GravityForce","RotationOverLife","Rotation3DOverLife","RotationBySpeed","SpeedOverLife","FrameOverLife","ForceOverLife","VelocityOverLife","InheritVelocity","OrbitOverLife","WidthOverLength","ChangeEmitDirection","EmitSubParticleSystem","LimitSpeedOverLife","ApplyCollision"]);class Bo{constructor(){this.fusionSteps=[],this.changesSize=!0,this.changesColor=!0}steps(t){const e=this.plan;if(void 0!==e&&e.length===t.length){let i=!0;for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}if(i)return this.fusionSteps}this.plan=t.slice(),this.fusionSteps=ls(t);let i=!1,s=!1;for(let e=0;e<t.length;e++){const n=t[e].type;Io.has(n)?i=!0:No.has(n)?s=!0:Fo.has(n)||(i=!0,s=!0)}return this.changesSize=i,this.changesColor=s,this.fusionSteps}}function Uo(t){return Math.sqrt(Math.max(t[0]*t[0]+t[1]*t[1]+t[2]*t[2],t[4]*t[4]+t[5]*t[5]+t[6]*t[6],t[8]*t[8]+t[9]*t[9]+t[10]*t[10]))}class Ro{constructor(){this.min=new ht,this.max=new ht,this.padding=0,this.valid=!1,this.stepsSince=0,this.maxSize=0,this.maxSpeedSq=0,this.inWorld=!1,this.geometryRadius=1}get due(){return this.stepsSince>=4||!this.valid}store(t,e,i,s,n,r,o,a,h,l,c,u,d,f){if(0===t)return void(this.valid=!1);this.stepsSince=e?0:this.stepsSince+1,this.maxSize=h,this.maxSpeedSq=l;const m=Math.sqrt(l),p=c.renderMode;let y=m*f*(this.stepsSince+1);if(p===Rs.Mesh)y+=h*this.meshGeometryRadius(c.instancingGeometry);else if(p===Rs.StretchedBillBoard){const t=u;y+=h*(1+(t.lengthFactor??0)+m*(t.speedFactor??0))}else{const t=c.pivot;y+=h*(.75+(void 0===t?0:Math.abs(t.x)+Math.abs(t.y)+Math.abs(t.z)))}this.min.set(i,s,n),this.max.set(r,o,a),this.padding=y,this.inWorld=d,this.valid=!0}setWorld(t,e,i,s,n,r,o){this.min.set(t,e,i),this.max.set(s,n,r),this.padding=o,this.inWorld=!0,this.valid=!0}worldPadding(t){return this.inWorld?this.padding:this.padding*Uo(t.matrixWorld.elements)}toWorld(t,e,i){if(!this.valid)return!1;const s=this.min,n=this.max;if(this.inWorld){const i=this.padding;return t.set(s.x-i,s.y-i,s.z-i),e.set(n.x+i,n.y+i,n.z+i),!0}const r=i.matrixWorld.elements,o=this.padding*Uo(r);let a=1/0,h=1/0,l=1/0,c=-1/0,u=-1/0,d=-1/0;for(let t=0;t<8;t++){const e=1&t?n.x:s.x,i=2&t?n.y:s.y,o=4&t?n.z:s.z,f=1/(r[3]*e+r[7]*i+r[11]*o+r[15]),m=(r[0]*e+r[4]*i+r[8]*o+r[12])*f,p=(r[1]*e+r[5]*i+r[9]*o+r[13])*f,y=(r[2]*e+r[6]*i+r[10]*o+r[14])*f;m<a&&(a=m),m>c&&(c=m),p<h&&(h=p),p>u&&(u=p),y<l&&(l=y),y>d&&(d=y)}return t.set(a-o,h-o,l-o),e.set(c+o,u+o,d+o),!0}meshGeometryRadius(t){if(t!==this.geometryRadiusFor){let e=0;for(let i=0;i+2<t.length;i+=3){const s=t[i]*t[i]+t[i+1]*t[i+1]+t[i+2]*t[i+2];s>e&&(e=s)}this.geometryRadius=Math.sqrt(e),this.geometryRadiusFor=t}return this.geometryRadius}}function Lo(t){return t.cycle>=1?Math.floor(t.cycle):1}function Do(t){return t.interval>0?t.interval:0}class ko{constructor(t,e){this.system=t,this.spawner=e,this.memory=[],this.pathMatrix=new ft,this.temp=new ht}rollGenerators(){const t=this.system,e=this.memory;t.emissionBursts.forEach(t=>t.count.startGen(e)),t.emissionOverDistance.startGen(e),t.startDelay.startGen(e);const i=t.startDelay.genValue(e,0);return t.emissionOverTime.startGen(e),i}hasPendingEmission(t){const e=this.system;if(void 0===t||t===e.emissionState){if(e.isEmitEnded)return!1;if(e.looping)return!0;if(e.onlyUsedByOther)return!1;t=e.emissionState}if(t.waitEmiting>0)return!0;if(t.burstIndex<e.emissionBursts.length)return!0;if(this.hasPendingBurstWaves(t))return!0;if(t.time>=e.duration)return!1;const i=t.time/e.duration;return this.emitsFrom(e.emissionOverTime,i)||this.emitsFrom(e.emissionOverDistance,i)}emitsFrom(t,e){if(t.genValue(this.memory,e)>0)return!0;if("function"!==t.type)return!1;if(t instanceof ce)return this.emitsFrom(t.curve1,e)||this.emitsFrom(t.curve2,e);if(t instanceof le){for(let i=0;i<t.functions.length;i++)if(t.getEndX(i)>e&&t.functions[i][0].p.some(t=>t>0))return!0;return!1}for(let i=1;i<=64;i++)if(t.genValue(this.memory,e+(1-e)*i/64)>0)return!0;return!1}hasPendingBurstWaves(t){const e=t.burstWaves;if(void 0===e)return!1;const i=this.system.emissionBursts,s=this.system.duration;for(let n=0;n<t.burstIndex&&n<i.length;n++){const t=i[n],r=e[n]??0;if(r<Lo(t)&&(0===r||t.time+r*Do(t)<=s))return!0}return!1}emit(t,e,i){const s=this.system;if(s.isDisposed)return;const n=s.duration,r=s.isEmitEnded&&e===s.emissionState;e.time>n&&(s.looping?(e.time-=n,e.burstIndex=0,void 0!==e.burstWaves&&(e.burstWaves.length=0)):s.isEmitEnded||s.onlyUsedByOther||s.endEmit());const o=s.emissionFactor();s.emissionBursts.length>0&&!r&&this.emitBursts(e,i);let a=0,h=0,l=0,c=0;const u=e.previousWorldPos;if(!s.isEmitEnded){const r=e.time/n;if(e.waitEmiting+=t*s.emissionOverTime.genValue(this.memory,r)*o,void 0!==u){this.temp.set(i.elements[12],i.elements[13],i.elements[14]),c=u.distanceTo(this.temp);const t=s.emissionOverDistance.genValue(this.memory,r)*o;if(t>0){l=e.travelDistance,e.travelDistance+=c;const i=Math.floor(e.travelDistance*t);i>0&&(e.travelDistance-=i/t,s.worldSpace&&c>0?(a=i,h=1/t):e.waitEmiting+=i)}else e.travelDistance=0}}const d=Math.floor(e.waitEmiting);d>0&&(this.spawner.spawn(d,e,i),e.waitEmiting-=d),a>0&&this.spawnAlongPath(a,e,i,u,l,h,c),void 0===e.previousWorldPos&&(e.previousWorldPos=new ht),e.previousWorldPos.set(i.elements[12],i.elements[13],i.elements[14]),e.time+=t}emitBursts(t,e){const i=this.system.emissionBursts,s=this.system.duration,n=i.length,r=t.time,o=t.burstWaves??(t.burstWaves=[]);for(;t.burstIndex<n&&i[t.burstIndex].time<=r;)o[t.burstIndex]=0,t.burstIndex++;const a=t.burstIndex;for(let n=0;n<a;n++){const a=i[n],h=Lo(a);let l=o[n]??0;if(l>=h)continue;const c=Do(a);for(;l<h;){const i=a.time+l*c;if(l>0&&i>s){l=h;break}if(i>r)break;t.burstWaveIndex=l,this.fireBurstWave(a,t,e),l++}o[n]=l}}fireBurstWave(t,e,i){if(T()>=t.probability)return;const s=t.count.genValue(this.memory,e.time/this.system.duration),n=this.system.emissionFactor(),r=Math.abs(n-1)<.001?s:Math.floor(s*n+T());e.isBursting=!0,e.burstParticleCount=r,this.spawner.spawn(r,e,i),e.isBursting=!1}spawnAlongPath(t,e,i,s,n,r,o){const a=this.pathMatrix.copy(i),h=i.elements,l=a.elements,c=h[12],u=h[13],d=h[14];for(let i=1;i<=t;i++){const t=i*r-n,h=t<=0?0:t>=o?1:t/o;l[12]=s.x+(c-s.x)*h,l[13]=s.y+(u-s.y)*h,l[14]=s.z+(d-s.z)*h,this.spawner.spawn(1,e,a)}}}class qo{constructor(){this.listeners={}}add(t,e){this.listeners[t]=[...this.listeners[t]??[],e]}removeAll(t){if(void 0!==t)delete this.listeners[t];else for(const t of Object.keys(this.listeners))delete this.listeners[t]}remove(t,e){const i=this.listeners[t];if(void 0===i)return;const s=i.indexOf(e);-1!==s&&(this.listeners[t]=i.filter((t,e)=>e!==s))}has(t){const e=this.listeners[t];return void 0!==e&&e.length>0}fire(t){const e=this.listeners[t.type];if(void 0!==e)for(let i=0;i<e.length;i++)e[i](t)}}const Jo=new Float32Array([-.5,-.5,0,.5,-.5,0,.5,.5,0,-.5,.5,0]),Go=new Float32Array([0,0,1,0,1,1,0,1]),Wo=new Uint32Array([0,1,2,0,2,3]),jo=new WeakMap,Qo=new WeakMap;function Ho(t){let e=jo.get(t);return void 0!==e&&e.length===t.length/3*2||(e=new Float32Array(t.length/3*2),jo.set(t,e)),e}function Yo(t){let e=Qo.get(t);if(!e){e=new Float32Array(t.length);for(let t=2;t<e.length;t+=3)e[t]=1;Qo.set(t,e)}return e}function Xo(t){return t?t instanceof Float32Array?t:new Float32Array(t):void 0}const Zo=1/60;class Ko{constructor(){this.accumulator=0,this.pendingCatchUp=0,this.delayLeft=0}reset(){this.accumulator=0,this.pendingCatchUp=0}setStartDelay(t){this.delayLeft=t>0?t:0}get delaying(){return this.delayLeft>0}static frameSeconds(t,e){if(!(t>0))return 0;return(t>.1?.1:t)*e}consumeStartDelay(t){if(this.delayLeft<=0)return t;if(this.delayLeft-=t,this.delayLeft>=0)return 0;const e=Math.min(-this.delayLeft,.1);return this.delayLeft=0,e}accrue(t,e=1){this.accumulator+=t;const i=e>1?Math.ceil(8*e):8,s=Math.min(i,Math.max(0,Math.round(this.accumulator/Zo-1e-9)));return this.accumulator-=s*Zo,s}get residual(){return this.accumulator>Zo?Zo:this.accumulator<-Zo?-Zo:this.accumulator}deferCatchUp(t){this.pendingCatchUp=Math.min(2,this.pendingCatchUp+t)}get owesCatchUp(){return this.pendingCatchUp>0}takeCatchUpSteps(){const t=Math.floor(this.pendingCatchUp/Zo);return this.pendingCatchUp=0,t}}const ta=new ht;function ea(t,e,i,s){const n=t[i],r=t[s];return t[i]=r,t[s]=n,i!==s&&(e.swapRows(i,s),r.setStoreIndex(i),n.setStoreIndex(s)),n}const ia=1e-6;function sa(t,e){return t.loopEnd>t.loopStart?1/0:Math.max(t.loopEnd,ia)*e}function na(t){return t?.getScene()?t:null}const ra=new ht(0,0,1),oa=new at,aa=new at,ha=new ht,la=new ht,ca=new zt;class ua{constructor(t){this.system=t,this.ringCursor=0}swapRows(t,e){const i=this.system.particles,s=i[t],n=i[e];i[t]=n,i[e]=s,this.system.store.swapRows(t,e),n.setStoreIndex(t),s.setStoreIndex(e)}reverseRows(t,e){for(;t<e;t++,e--)this.swapRows(t,e)}rotateRows(t,e){t<=0||t>=e||(this.reverseRows(0,t-1),this.reverseRows(t,e-1),this.reverseRows(0,e-1))}fitRing(){const t=this.system,e=t.maxParticles,i=t.particleNum;void 0===e||i<=e||"disabled"===t.ringBufferMode||t.rendererSettings.renderMode!==Rs.Trail&&(this.rotateRows((this.ringCursor+i-e)%i,i),t.particleNum=e,this.ringCursor=0)}rebind(){const t=this.system.particles;for(let e=0;e<t.length;e++)t[e].rebind()}grow(t){const e=this.system,i=e.particles.length;e.store.ensureCapacity(i+1)&&this.rebind(),e.particles.push(t?new Ke(e.store,i):new Ye(e.store,i))}spawn(t,e,i){const s=this.system,n=ha,r=la;i.decompose(n,aa,r);const o=ca.setFromMatrix4(i),a=s.behaviors,h=a.length,l=s.rendererSettings.renderMode,c=l===Rs.Trail,u=!c,d=l===Rs.Mesh,f=s.startRotation,m=s.startSize,p="rotation"===f.type,y="vec3function"===m.type,g=e.time/s.duration,v=c?s.rendererEmitterSettings:void 0,x=Boolean(v?.followLocalOrigin),S=s.worldSpace,b="shape"===s.scalingMode?s.emitter.shapeScale:void 0,w=s.particles,M=s.maxParticles,z=void 0!==M&&"disabled"!==s.ringBufferMode&&!c;void 0!==M&&(t=z?Math.min(t,M):Math.min(t,Math.max(0,M-s.particleNum)));for(let n=0;n<t;n++){let t;if(e.burstParticleIndex=n,z&&s.particleNum>=M?(this.ringCursor>=s.particleNum&&(this.ringCursor=0),t=w[this.ringCursor],this.ringCursor=(this.ringCursor+1)%s.particleNum):(z&&0!==this.ringCursor&&(this.rotateRows(this.ringCursor,s.particleNum),this.ringCursor=0),s.particleNum++,w.length<s.particleNum&&this.grow(c),t=w[s.particleNum-1]),t.reset(),t.serial=(t.serial??0)+1,t.speedModifier=1,s.finishedEventFired=!1,s.startColor.startGen(t.memory),s.startColor.genColor(t.memory,t.startColor,g),t.color.copy(t.startColor),s.startSpeed.startGen(t.memory),t.startSpeed=s.startSpeed.genValue(t.memory,g),s.startLife.startGen(t.memory),t.life=s.startLife.genValue(t.memory,g),t.age=0,m.startGen(t.memory),y)m.genValue(t.memory,t.startSize,g);else{const e=m.genValue(t.memory,g);t.startSize.set(e,e,e)}if(s.startTileIndex.startGen(t.memory),t.uvTile=s.startTileIndex.genValue(t.memory),t.size.copy(t.startSize),u){const e=t;if(f.startGen(t.memory),d)e.rotation instanceof at||(e.rotation=oa),e.angularVelocity instanceof at&&e.angularVelocity.set(0,0,0,1),p?f.genValue(t.memory,e.rotation,1,g):e.rotation.setFromAxisAngle(ra,f.genValue(e.memory,g));else{e.rotation=p?0:f.genValue(e.memory,g),e.angularVelocity=0;const t=s.flip;e.flip=void 0===t?0:(T()<t.x?1:0)|(T()<t.y?2:0)}}else if(v){const e=t;v.startLength.startGen(e.memory),e.length=v.startLength.genValue(e.memory,g),e.ensureHistoryCapacity(Math.max(1,Math.ceil(e.length))),e.resetHistory()}s.emitterShape.initialize(t,e),void 0!==b&&t.position.multiply(b),s.alignToDirection&&u&&da(t,d);const l=e.particle,_=e.inherit;if(void 0!==l&&void 0!==_&&0!==_&&fa(t,l,_,u),c&&x){const e=t;e.localPosition||(e.localPosition=new ht),e.localPosition.copy(e.position)}S?(t.position.applyMatrix4(i),t.startSize.multiply(r).abs(),t.size.copy(t.startSize),t.velocity.applyMatrix3(o),t.rotation&&t.rotation instanceof at&&t.rotation.multiplyQuaternions(aa,t.rotation)):s.onlyUsedByOther&&(t.parentMatrix=i);for(let e=0;e<h;e++)a[e].initialize(t,s);s.store.recordMemory(t.storeIndex,t.memory)}}}function da(t,e){const i=t.velocity,s=i.x*i.x+i.y*i.y+i.z*i.z;if(0!==s)if(e){const e=t.rotation;ha.copy(i).divideScalar(Math.sqrt(s)),aa.setFromUnitVectors(ra,ha),e.multiplyQuaternions(aa,e)}else 0===i.x&&0===i.y||(t.rotation=t.rotation+Math.atan2(-i.x,i.y))}function fa(t,e,i,s){if(i&hi.color&&(t.startColor.multiply(e.color),t.color.copy(t.startColor)),i&hi.size&&(t.startSize.multiply(e.size),t.size.copy(t.startSize)),i&hi.rotation&&s){const i=t,s=e.rotation;"number"==typeof i.rotation?"number"==typeof s&&(i.rotation+=s):s instanceof at&&i.rotation.multiplyQuaternions(s,i.rotation)}i&hi.lifetime&&e.life>0&&(t.life*=Math.max(0,1-e.age/e.life))}function ma(t,e,i,s,n={}){return{param:t,json:n.json,get:e,isDefault:t=>t===i,toJSON:t=>t,fromJSON:s,clone:t=>t}}function pa(t){return"number"==typeof t?t:void 0}function ya(t){return"number"==typeof t?yn(t):void 0}function ga(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:void 0}function va(t){return"number"==typeof t?0!==t:"boolean"==typeof t?t:void 0}function xa(t,e,i,s,n=!0){const r=JSON.stringify(i().toJSON());return{param:t,always:n,get:e,isDefault:t=>JSON.stringify(t.toJSON())===r,toJSON:t=>t.toJSON(),fromJSON:t=>"number"==typeof t?new re(t):s(t),clone:t=>t.clone()}}function Sa(t){const e=t;if(void 0!==e)return void 0===e.z?[e.x,e.y]:[e.x,e.y,e.z]}const ba=[ma("stopAction",t=>t.stopAction,"none",cn),ma("looping",t=>t.looping,!0,va),ma("prewarm",t=>t.prewarm,!1,va),ma("prewarmTime",t=>t.prewarmTime,0,pa),ma("duration",t=>t.duration,1,pa),xa("startDelay",t=>t.startDelay,()=>new re(0),de,!1),xa("startLife",t=>t.startLife,()=>new re(5),de),xa("startSpeed",t=>t.startSpeed,()=>new re(0),de),xa("startRotation",t=>t.startRotation,()=>new re(0),t=>Te(t)),xa("startSize",t=>t.startSize,()=>new re(1),t=>Te(t)),xa("startColor",t=>t.startColor,()=>new we(new Ct(1,1,1,1)),t=>Me(t)),xa("emissionOverTime",t=>t.emissionOverTime,()=>new re(10),de),xa("emissionOverDistance",t=>t.emissionOverDistance,()=>new re(0),de),{param:"emissionBursts",get:t=>t.emissionBursts,isDefault:t=>0===t.length,toJSON:t=>t.map(t=>({time:t.time,count:t.count.toJSON(),probability:t.probability,interval:t.interval,cycle:t.cycle})),fromJSON:t=>Array.isArray(t)?xn(t.map(t=>({time:t.time,count:"number"==typeof t.count?new re(t.count):de(t.count),probability:t.probability,interval:t.interval,cycle:t.cycle??t.cycleCount}))):void 0,clone:t=>t.map(t=>({...t,count:t.count.clone()}))},ma("maxParticles",t=>t.maxParticles,void 0,pa),ma("ringBufferMode",t=>t.ringBufferMode,"disabled",un),{param:"ringBufferLoopRange",get:t=>t.ringBufferLoopRange,isDefault:t=>0===t.x&&1===t.y,toJSON:Sa,fromJSON:t=>Array.isArray(t)?dn(new Tt(t[0],t[1])):void 0,clone:t=>t.clone()},ma("onlyUsedByOther",t=>t.onlyUsedByOther,!1,va),ma("renderMode",t=>t.renderMode,Rs.BillBoard,pa),ma("renderOrder",t=>t.renderOrder,0,pa),ma("renderingGroupId",t=>t.renderingGroupId,0,pa),ma("applyFog",t=>t.applyFog,!0,t=>!1!==t),ma("applyImageProcessing",t=>t.applyImageProcessing,!0,t=>!1!==t),ma("playbackSpeed",t=>t.playbackSpeed,1,pa),ma("cullingMode",t=>t.cullingMode,"always",ln),ma("scalingMode",t=>t.scalingMode,"local",fn),ma("seed",t=>t.seed,void 0,pa),ma("sortMode",t=>t.sortMode,"none",an),ma("renderFace",t=>t.renderFace,"both",hn),ma("alignToDirection",t=>t.alignToDirection,!1,t=>!0===t),ma("minParticleSize",t=>t.minParticleSize,0,pa),ma("maxParticleSize",t=>t.maxParticleSize,1/0,pa),ma("layerMask",t=>t.layers.mask,268435455,pa,{json:"layers"}),xa("startTileIndex",t=>t.startTileIndex,()=>new re(0),de),ma("uTileCount",t=>t.uTileCount,1,ya),ma("vTileCount",t=>t.vTileCount,1,ya),ma("blendTiles",t=>t.blendTiles,!1,va),ma("softParticles",t=>t.softParticles,!1,va),ma("softFarFade",t=>t.softFarFade,1,ga),ma("softNearFade",t=>t.softNearFade,0,ga),ma("blendMode",t=>t.blending,r.ALPHA_ADD,pa,{json:"blending"}),ma("transparent",t=>t.transparent,!0,va),ma("depthTest",t=>t.depthTest,!0,va),ma("depthWrite",t=>t.depthWrite,!1,va),ma("alphaTest",t=>t.alphaTest,0,pa),ma("worldSpace",t=>t.worldSpace,!1,va),{param:"pivot",get:t=>t.pivot,isDefault:t=>void 0===t,toJSON:Sa,fromJSON:t=>Array.isArray(t)?new ht(t[0]??0,t[1]??0,t[2]??0):void 0,clone:t=>t?.clone()},{param:"flip",get:t=>t.flip,isDefault:t=>void 0===t,toJSON:Sa,fromJSON:t=>Array.isArray(t)?new Tt(t[0]??0,t[1]??0):void 0,clone:t=>t?.clone()}];function wa(t){return t.json??t.param}function Ma(t){const e={};for(const i of ba){const s=i.get(t);!i.always&&i.isDefault(s)||(e[wa(i)]=i.toJSON(s))}return e}function za(t){const e={};for(const i of ba)e[i.param]=i.clone(i.get(t));return e}const _a=new WeakMap,Aa=new WeakMap,Pa=new WeakMap;function Oa(t,e){const i=(_a.get(t)??0)+1;return _a.set(t,i),`${e}_${i}`}function Ta(t){const e={};return t?.uvFromHead&&(e.uvFromHead=!0),t?.colorFromParticle&&(e.colorFromParticle=!0),t?.dieWithParticle&&(e.dieWithParticle=!0),t?.recordWorldSpace&&(e.recordWorldSpace=!0),e}function Va(t){const e={},i=jr(t),s=Qr(t);return i>0&&(e.tessellation=i),s>0&&(e.curveTension=s),e}function Ea(t){const e={},i=Yr(t),s=Xr(t),n=Zr(t),r=Kr(t);return"stretch"!==i&&(e.textureMode=i),1!==s&&(e.textureScale=s),n>0&&(e.minVertexDistance=n),r!==1/0&&(e.lifetime=r),e}function $a(t){return t?.followLocalOrigin?{followLocalOrigin:!0}:{}}function Ca(t){const e=t?.sideAxis;return e?{sideAxis:[e.x,e.y,e.z]}:{}}function Ia(t){if(null==t)return{};let e,i,s;Array.isArray(t)?[e,i,s]=t:"object"==typeof t&&({x:e,y:i,z:s}=t);const n=t=>"number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):NaN,[r,o,a]=[n(e),n(i),n(s)];return Number.isFinite(r)&&Number.isFinite(o)&&Number.isFinite(a)&&r*r+o*o+a*a>0?{sideAxis:new ht(r,o,a)}:(te(`sideAxis ${JSON.stringify(t)} is not a direction and is ignored`),{})}function Na(t,e){const i=void 0===e||"string"==typeof e?{geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}}:e,s=function(t,e){const i=t.rendererSettings,s=[i.instancingGeometry,i.instancingIndices,i.instancingUVs,i.instancingUVs2,i.instancingNormals];let n=Aa.get(e);void 0===n&&(n=[],Aa.set(e,n));const r=n.find(t=>t.arrays.every((t,e)=>t===s[e]));if(void 0!==r)return r.uuid;const o=Oa(e,"quarks_geometry");return n.push({arrays:s,uuid:o}),e.geometries[o]={uuid:o,type:"QuarksGeometry",positions:Array.from(t.rendererSettings.instancingGeometry),indices:Array.from(t.rendererSettings.instancingIndices),uvs:t.rendererSettings.instancingUVs?Array.from(t.rendererSettings.instancingUVs):void 0,...t.rendererSettings.instancingUVs2?{uvs2:Array.from(t.rendererSettings.instancingUVs2)}:{},normals:t.rendererSettings.instancingNormals?Array.from(t.rendererSettings.instancingNormals):void 0},o}(t,i),n=function(t,e){let i=Pa.get(e);void 0===i&&(i=new Map,Pa.set(e,i));const s=i,n=(t,i=!1,n="texture")=>{if(!(t instanceof A||i&&t))return void(t&&console.warn(`[quarks] ${n} is not a url-backed Texture and is not written to the file`));let r=s.get(t);return void 0===r&&(r=Oa(e,"quarks_texture"),s.set(t,r),e.textures[r]=t),r},r=n(t.rendererSettings.texture,!0),o=n(t.rendererSettings.reflectionAtlas),a=t.erosion,h=t.uvDistortion,l=t.gradientMap,c=(t,e)=>void 0!==e?{[t]:e}:{},u=Oa(e,"quarks_material");return e.materials[u]={uuid:u,type:"QuarksMaterial",transparent:t.rendererSettings.materialTransparent,alphaMode:t.rendererSettings.materialBlendMode,depthTest:t.rendererSettings.materialDepthTest,depthWrite:t.rendererSettings.materialDepthWrite,alphaTest:t.rendererSettings.materialAlphaTest,texture:r,reflectionAtlas:o,reflectionLevel:t.rendererSettings.reflectionLevel,..."fixed"!==t.lighting?{lighting:t.lighting}:{},...t.rim?{rim:{...t.rim,color:[...t.rim.color]}}:{},...c("mapUV",t.mapUV?Gs(t.mapUV):void 0),...l?{gradientMap:{ramp:n(l.ramp,!1,"gradientMap.ramp"),..."r"!==l.channel?{channel:l.channel}:{}}}:{},...a?{erosion:{...c("mask",n(a.mask,!1,"erosion.mask")),...c("maskUV",Gs(a.maskUV)),...a.softness!==Hs?{softness:a.softness}:{},...0!==a.edgeWidth?{edgeWidth:a.edgeWidth}:{},...a.edgeColor.some(t=>1!==t)?{edgeColor:[...a.edgeColor]}:{}}}:{},...h?{uvDistortion:{map:n(h.map,!1,"uvDistortion.map"),...c("mapUV",Gs(h.mapUV,Zs)),...h.strength!==Ks?{strength:h.strength}:{}}}:{},sourceMaterial:t.material??void 0},u}(t,i),r=function(t){if(t.renderMode===Rs.Trail){const e=t.rendererEmitterSettings;return{startLength:e.startLength.toJSON(),...$a(e),...Ta(e),...Va(e),...Ea(e),...Ca(e)}}if(t.renderMode===Rs.StretchedBillBoard)return{speedFactor:t.rendererEmitterSettings.speedFactor,lengthFactor:t.rendererEmitterSettings.lengthFactor};return}(t);return{version:"3.0",shape:Ts(t.emitterShape),...Ma(t),instancingGeometry:s,...r?{rendererEmitterSettings:r}:{},material:n,behaviors:t.behaviors.map(e=>Hi(e,t))}}function Fa(t,e,i){const s=t.shape?Zt("shape",()=>Os(t.shape,e)):void 0;let n;if(t.renderMode===Rs.Trail){const e=t.rendererEmitterSettings;n={startLength:void 0!==e?.startLength?de(e.startLength):new re(30),followLocalOrigin:Boolean(e?.followLocalOrigin),...Ta(e),...Va(e),...Ea(e),...Ia(e?.sideAxis)}}else if(t.renderMode===Rs.StretchedBillBoard){const e={...t.rendererEmitterSettings};void 0!==t.speedFactor&&(e.speedFactor=t.speedFactor),n=e}else n={};const o=t.material?e.materials?.[t.material]:void 0,a=t=>"string"==typeof t?e.textures?.[t]??null:t??null,h=a(o?.texture??t.texture),l=h instanceof A?h:null,c=o?.sourceMaterial??(o?{...o,reflectionAtlas:a(o.reflectionAtlas)}:void 0),u=o?.erosion,d=o?.gradientMap,f=o?.uvDistortion,m=function(t){if(t&&"positions"in t&&t.positions){const e=Xo(t.positions);return{positions:e,indices:Cs(e,t.indices instanceof Uint16Array||t.indices instanceof Uint32Array?t.indices:t.indices?new Uint32Array(t.indices):void 0),uvs:Xo(t.uvs),uvs2:Xo(t.uvs2),normals:Xo(t.normals)}}const e=t&&"data"in t?t.data:t,i=e&&"attributes"in e?e.attributes:void 0,s=i?.position?.array;if(e&&"attributes"in e&&i&&s){const t=new Float32Array(s);let n;return e.index?.array&&(n=new("Uint16Array"===e.index.type?Uint16Array:Uint32Array)(e.index.array)),{positions:t,indices:Cs(t,n),uvs:Xo(i.uv?.array),uvs2:Xo((i.uv1??i.uv2)?.array),normals:Xo(i.normal?.array)}}return{positions:Jo,indices:Wo,uvs:Go}}("string"==typeof t.instancingGeometry?e.geometries?.[t.instancingGeometry]:t.instancingGeometry),p=function(t){const e={},i=t;for(const t of ba){const s=i[wa(t)];if(null==s)continue;const n=Zt(wa(t),()=>t.fromJSON(s));void 0!==n&&(e[t.param]=n)}return void 0===e.stopAction&&!0===i.autoDestroy&&(e.stopAction="destroy"),e}(t);return{...p,scene:i,shape:s,instancingGeometry:m.positions,instancingIndices:m.indices,instancingUVs:m.uvs,instancingUVs2:m.uvs2,instancingNormals:m.normals,rendererEmitterSettings:n,texture:l,material:c,blendMode:o?.alphaMode??p.blendMode??r.ALPHA_ADD,transparent:o?.transparent??p.transparent??!0,depthTest:o?.depthTest??p.depthTest??!0,depthWrite:o?.depthWrite??p.depthWrite??!1,alphaTest:o?.alphaTest??p.alphaTest??0,behaviors:[],lighting:o?.lighting,rim:o?.rim,mapUV:o?.mapUV,gradientMap:d&&"object"==typeof d?{...d,ramp:a(d.ramp)}:void 0,erosion:u&&"object"==typeof u?{...u,mask:a(u.mask)}:void 0,uvDistortion:f&&"object"==typeof f?{...f,map:a(f.map)}:void 0}}const Ba=new ht,Ua=new at,Ra=new ht,La=new ht,Da=new at,ka=new ht,qa=new ht,Ja=new at,Ga=new ht;class Wa{get autoDestroy(){return"destroy"===this.stopAction}set autoDestroy(t){t?this.stopAction="destroy":"destroy"===this.stopAction&&(this.stopAction="none")}get prewarmTime(){return this.prewarmTimeValue}set prewarmTime(t){this.prewarmTimeValue=t>0?t:0}get duration(){return this.durationValue}set duration(t){this.durationValue=t>Zo?t:Zo}set time(t){const e=this.duration;let i=Number.isFinite(t)&&t>0?t:0;i>=e&&(i=this.looping?i%e:e);const s=this.emissionState;s.time=i,s.isBursting=!1,s.burstIndex=0,s.burstWaveIndex=0,s.burstWaves=void 0,this.markBurstsBefore(i)}get time(){return this.emissionState.time}get isEmitEnded(){return this.emitEnded}hasPendingEmission(t){return this.emission.hasPendingEmission(t)}isFinished(){return!(this.particleNum>0||this.hasPendingSubEmission())&&(!!this.onlyUsedByOther||(this.looping?this.emitEnded:!this.hasPendingEmission()))}get layers(){return this.layerMaskProxy}get texture(){return this.rendererSettings.texture}set texture(t){this.rendererSettings.texture=t,this.neededToUpdateRender=!0}get material(){return this.materialRef}set material(t){this.materialRef=t,this.applyMaterialSettings(t)}get uTileCount(){return this.rendererSettings.uTileCount}set uTileCount(t){this.rendererSettings.uTileCount=yn(t),this.neededToUpdateRender=!0}get vTileCount(){return this.rendererSettings.vTileCount}set vTileCount(t){this.rendererSettings.vTileCount=yn(t),this.neededToUpdateRender=!0}get blendTiles(){return this.rendererSettings.blendTiles}set blendTiles(t){this.rendererSettings.blendTiles=t,this.neededToUpdateRender=!0}get softParticles(){return this.rendererSettings.softParticles}set softParticles(t){this.rendererSettings.softParticles=t,this.neededToUpdateRender=!0}get sortMode(){return this.rendererSettings.sortMode??"none"}set sortMode(t){this.rendererSettings.sortMode=an(t),this.neededToUpdateRender=!0}get renderFace(){return this.rendererSettings.renderFace??"both"}set renderFace(t){this.rendererSettings.renderFace=hn(t),this.neededToUpdateRender=!0}get minParticleSize(){return this.rendererSettings.minParticleSize??0}set minParticleSize(t){this.rendererSettings.minParticleSize=Math.max(0,t),this.neededToUpdateRender=!0}get maxParticleSize(){return this.rendererSettings.maxParticleSize??1/0}set maxParticleSize(t){this.rendererSettings.maxParticleSize=t>0?t:1/0,this.neededToUpdateRender=!0}get pivot(){return this.rendererSettings.pivot}set pivot(t){this.rendererSettings.pivot=mn(t),this.neededToUpdateRender=!0}get lighting(){return this.rendererSettings.lighting??"fixed"}set lighting(t){this.rendererSettings.lighting=on(t),this.neededToUpdateRender=!0}get rim(){return this.rendererSettings.rim}set rim(t){this.rendererSettings.rim=Ds(t),this.neededToUpdateRender=!0}get mapUV(){return this.rendererSettings.mapUV}set mapUV(t){this.rendererSettings.mapUV=sn(t),this.neededToUpdateRender=!0}get gradientMap(){return this.rendererSettings.gradientMap}set gradientMap(t){this.rendererSettings.gradientMap=js(t),this.neededToUpdateRender=!0}get erosion(){return this.rendererSettings.erosion}set erosion(t){this.rendererSettings.erosion=Ys(t),this.neededToUpdateRender=!0}get uvDistortion(){return this.rendererSettings.uvDistortion}set uvDistortion(t){this.rendererSettings.uvDistortion=tn(t),this.neededToUpdateRender=!0}measureMotionScale(t){if(!this.worldSpace)return 1;const e=t.elements;return(Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2])+Math.sqrt(e[4]*e[4]+e[5]*e[5]+e[6]*e[6])+Math.sqrt(e[8]*e[8]+e[9]*e[9]+e[10]*e[10]))/3}get softNearFade(){return this.rendererSettings.softNearFade}set softNearFade(t){this.rendererSettings.softNearFade=gn(t,0),this.neededToUpdateRender=!0}get softFarFade(){return this.rendererSettings.softFarFade}set softFarFade(t){this.rendererSettings.softFarFade=gn(t,1),this.neededToUpdateRender=!0}get instancingGeometry(){return this.rendererSettings.instancingGeometry}set instancingGeometry(t){this.restartKeepingPause();const e=this.rendererSettings,i=t.length/3*2,s=e.instancingGeometry;var n,r;e.instancingGeometry=t,t.length===s.length&&function(t,e){for(let i=0;i<t.length;i++)if(t[i]>=e)return!1;return!0}(e.instancingIndices,t.length/3)||(e.instancingIndices=Cs(t)),e.instancingUVs?.length===i&&(n=e.instancingUVs,r=s,void 0===n||n!==jo.get(r))||(e.instancingUVs=Ho(t)),e.instancingNormals&&(e.instancingNormals.length!==t.length||function(t,e){return void 0!==t&&t===Qo.get(e)}(e.instancingNormals,s))&&(e.instancingNormals=Yo(t)),e.instancingUVs2&&e.instancingUVs2.length!==i&&(e.instancingUVs2=void 0),this.ensureMeshNormals(),this.neededToUpdateRender=!0}ensureMeshNormals(){const t=this.rendererSettings;t.renderMode!==Rs.Mesh||t.instancingNormals||(t.instancingNormals=Yo(t.instancingGeometry))}restartKeepingPause(){const t=this.paused;this.restart(),this.particles.length=0,this.paused=t}get instancingIndices(){return this.rendererSettings.instancingIndices}set instancingIndices(t){this.rendererSettings.instancingIndices=t,this.neededToUpdateRender=!0}get instancingUVs(){return this.rendererSettings.instancingUVs??Ho(this.rendererSettings.instancingGeometry)}set instancingUVs(t){this.rendererSettings.instancingUVs=t,this.neededToUpdateRender=!0}get instancingUVs2(){return this.rendererSettings.instancingUVs2}set instancingUVs2(t){this.rendererSettings.instancingUVs2=t,this.neededToUpdateRender=!0}get blending(){return this.rendererSettings.materialBlendMode}set blending(t){this.rendererSettings.materialBlendMode=t,this.neededToUpdateRender=!0}get transparent(){return this.rendererSettings.materialTransparent}set transparent(t){this.rendererSettings.materialTransparent=t,this.neededToUpdateRender=!0}get depthTest(){return this.rendererSettings.materialDepthTest}set depthTest(t){this.rendererSettings.materialDepthTest=t,this.neededToUpdateRender=!0}get depthWrite(){return this.rendererSettings.materialDepthWrite}set depthWrite(t){this.rendererSettings.materialDepthWrite=t,this.neededToUpdateRender=!0}get alphaTest(){return this.rendererSettings.materialAlphaTest}set alphaTest(t){this.rendererSettings.materialAlphaTest=pn(t),this.neededToUpdateRender=!0}get renderMode(){return this.rendererSettings.renderMode}set renderMode(t){if(this.rendererSettings.renderMode!==t){let e=!1;switch(this.rendererSettings.renderMode===Rs.Trail&&(e=!0),this.rendererSettings.renderMode===Rs.Mesh&&(this.startRotation=new re(0)),t){case Rs.Trail:this.rendererEmitterSettings={startLength:new re(30),followLocalOrigin:!1},e=!0;break;case Rs.Mesh:this.rendererEmitterSettings={},this.startRotation=new me(new ht(0,1,0),new re(0));break;case Rs.StretchedBillBoard:this.rendererEmitterSettings={speedFactor:0,lengthFactor:2};break;case Rs.BillBoard:case Rs.VerticalBillBoard:case Rs.HorizontalBillBoard:case Rs.Beam:this.rendererEmitterSettings={}}this.rendererSettings.renderMode=t,e&&this.restartKeepingPause(),this.ensureMeshNormals(),this.neededToUpdateRender=!0}}get renderOrder(){return this.rendererSettings.renderOrder}set renderOrder(t){this.rendererSettings.renderOrder=t,this.neededToUpdateRender=!0}get renderingGroupId(){return this.rendererSettings.renderingGroupId}set renderingGroupId(t){this.rendererSettings.renderingGroupId=t,this.neededToUpdateRender=!0}get applyFog(){return this.rendererSettings.applyFog}set applyFog(t){this.rendererSettings.applyFog=t,this.neededToUpdateRender=!0}get applyImageProcessing(){return!1!==this.rendererSettings.applyImageProcessing}set applyImageProcessing(t){this.rendererSettings.applyImageProcessing=t,this.neededToUpdateRender=!0}get playbackSpeed(){return this.playbackSpeedValue}set playbackSpeed(t){this.playbackSpeedValue=t>0&&t<1/0?t:0}get timeDilation(){return this.timeDilationValue}set timeDilation(t){this.timeDilationValue=t>0&&t<1/0?t:0}get emissionMultiplier(){return this.emissionMultiplierValue}set emissionMultiplier(t){this.emissionMultiplierValue=Number.isFinite(t)&&t>=0?t:0}get seed(){return this.seedValue}set seed(t){this.seedValue=t,this.rng=void 0===t?void 0:$(t),void 0!==this.emissionState&&0===this.emissionState.time&&0===this.particleNum&&(this.emission.memory.length=0,this.initSystemGenerators())}constructor(t){var e,i;if(this.ignoreStopAction=!1,this.prewarmTimeValue=0,this.durationValue=1,this.store=new We(64),this.emitterVelocity=new ht,this.finishedEventFired=!1,this.clock=new Ko,this.tempEmitterPos=new ht,this.stepMatrix=new ft,this.spawner=new ua(this),this.emission=new ko(this,this.spawner),this.events=new qo,this.materialRef=null,this.qualityFactor=1,this.destroyed=!1,this.behaviorPlan=new Bo,this.playbackSpeedValue=1,this.timeDilationValue=1,this.emissionMultiplierValue=1,this.cullingMode="always",this.scalingMode="local",this.motionScale=1,this.alignToDirection=!1,this.culled=!1,this.bounds=new Ro,this.firstTimeUpdate=!0,this.beamEndScratch=new ht,this.rebindParticles=()=>this.spawner.rebind(),this.particleDiedEvent={type:"particleDied",particleSystem:this},this.fireParticleDied=t=>{const e=this.particleDiedEvent;e.particle=t,this.events.fire(e),e.particle=void 0},this.ringStep={pause:!0,loopStart:0,loopEnd:1},this.stopActionPending=!1,this.sceneRef=t.scene,this.layerMaskProxy={mask:t.layerMask??268435455},Object.defineProperty(this.layerMaskProxy,"mask",{enumerable:!0,get:()=>this.rendererSettings.layerMask,set:t=>{this.rendererSettings.layerMask=t,this.neededToUpdateRender=!0}}),this.stopAction=cn(t.stopAction??(!0===t.autoDestroy?"destroy":void 0)),this.duration=t.duration??1,this.startDelay=t.startDelay??new re(0),this.looping=t.looping??!0,this.prewarm=t.prewarm??!1,this.prewarmTime=t.prewarmTime??0,this.startLife=t.startLife??new re(5),this.startSpeed=t.startSpeed??new re(0),this.startRotation=t.startRotation??new re(0),this.startSize=t.startSize??new re(1),this.startColor=t.startColor??new we(new Ct(1,1,1,1)),this.emissionOverTime=t.emissionOverTime??new re(10),this.emissionOverDistance=t.emissionOverDistance??new re(0),this.emissionBursts=xn(t.emissionBursts),this.maxParticles="number"==typeof(e=t.maxParticles)&&e>=0&&e<1/0?Math.floor(e):void 0,this.ringBufferMode=un(t.ringBufferMode),this.ringBufferLoopRange=dn(t.ringBufferLoopRange),this.onlyUsedByOther=t.onlyUsedByOther??!1,this.emitterShape=t.shape??new _s,this.behaviors=t.behaviors??[],this.worldSpace=t.worldSpace??!1,this.rendererEmitterSettings=t.rendererEmitterSettings??{},t.renderMode===Rs.Trail){const t={...this.rendererEmitterSettings};this.rendererEmitterSettings=t,t.startLength=t.startLength??new re(30),t.followLocalOrigin=t.followLocalOrigin??!1}if(t.renderMode===Rs.StretchedBillBoard){const e={...this.rendererEmitterSettings};this.rendererEmitterSettings=e,void 0!==t.speedFactor&&(e.speedFactor=t.speedFactor),e.speedFactor=e.speedFactor??0,e.lengthFactor=e.lengthFactor??0}this.rendererSettings={instancingGeometry:t.instancingGeometry??Jo,instancingIndices:t.instancingIndices??Wo,instancingUVs:t.instancingUVs??(t.instancingGeometry?Ho(t.instancingGeometry):Go),instancingUVs2:t.instancingUVs2,instancingNormals:t.instancingNormals,renderMode:t.renderMode??Rs.BillBoard,renderOrder:t.renderOrder??0,uTileCount:yn(t.uTileCount),vTileCount:yn(t.vTileCount),blendTiles:t.blendTiles??!1,softParticles:t.softParticles??!1,softNearFade:gn(t.softNearFade,0),softFarFade:gn(t.softFarFade,1),materialBlendMode:t.blendMode??r.ALPHA_ADD,materialTransparent:t.transparent??!0,materialDepthTest:t.depthTest??!0,materialDepthWrite:t.depthWrite??!1,materialAlphaTest:pn(t.alphaTest),texture:t.texture??null,reflectionTexture:null,reflectionLevel:1,reflectionAtlas:null,layerMask:t.layerMask??268435455,pivot:mn(t.pivot),sortMode:an(t.sortMode),renderFace:hn(t.renderFace),minParticleSize:Math.max(0,t.minParticleSize??0),maxParticleSize:t.maxParticleSize??1/0,renderingGroupId:t.renderingGroupId??0,applyFog:t.applyFog??!0,applyImageProcessing:t.applyImageProcessing??!0,lighting:on(t.lighting),rim:Ds(t.rim),mapUV:sn(t.mapUV),gradientMap:js(t.gradientMap),erosion:Ys(t.erosion),uvDistortion:tn(t.uvDistortion)},this.flip=(i=t.flip)&&(i.x>0||i.y>0)?i.clone():void 0,this.playbackSpeed=t.playbackSpeed??1,this.cullingMode=ln(t.cullingMode),this.scalingMode=fn(t.scalingMode),this.alignToDirection=!0===t.alignToDirection,this.seed=t.seed,this.ensureMeshNormals(),this.materialRef=t.material??null,this.applyMaterialSettings(this.materialRef,{blendMode:t.blendMode,transparent:t.transparent,depthTest:t.depthTest,depthWrite:t.depthWrite,alphaTest:t.alphaTest,texture:t.texture,layerMask:t.layerMask}),this.neededToUpdateRender=!0,this.particles=[],this.startTileIndex=t.startTileIndex||new re(0),this.emitter=new yo(this,t.scene),this.paused=!1,this.particleNum=0,this.emissionState={isBursting:!1,burstParticleIndex:0,burstParticleCount:0,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,travelDistance:0},this.initSystemGenerators(),this.emitEnded=!1,this.prewarmed=!1}watchEnvAtlas(t,e){t?.onDisposeObservable.addOnce(()=>{if(this.destroyed||this.rendererSettings.reflectionAtlas!==t)return;this.rendererSettings.reflectionAtlas=null,e?.reflectionAtlas===t&&(e.reflectionAtlas=null),this.neededToUpdateRender=!0;const i=this.rendererSettings.reflectionTexture;i?.isCube&&i.getScene()&&this.sceneRef&&Co(i,this.sceneRef,t=>{this.destroyed||this.rendererSettings.reflectionTexture!==i||(this.rendererSettings.reflectionAtlas=t,e&&null==e.reflectionAtlas&&(e.reflectionAtlas=t),this.watchEnvAtlas(t,e),this.neededToUpdateRender=!0)})})}applyMaterialSettings(t,e={}){if(!this.rendererSettings)return;const i=function(t,e,i){const s=void 0!==e.texture?e.texture:[t?.albedoTexture,t?.diffuseTexture,t?.emissiveTexture,t?.opacityTexture,t?.baseTexture].find(t=>t instanceof A)??i.texture??null,n=t?.reflectionTexture??t?.environmentTexture??i.reflectionTexture??null,r="number"==typeof n?.level?n.level:1,o=e.blendMode??("number"==typeof t?.alphaMode?t.alphaMode:i.materialBlendMode),a=e.transparent??("function"==typeof t?.needAlphaBlending?t.needAlphaBlending():"number"==typeof t?.alpha?t.alpha<1:i.materialTransparent),h=e.depthTest??("boolean"==typeof t?.disableDepthTest?!t.disableDepthTest:i.materialDepthTest),l=e.depthWrite??("boolean"==typeof t?.disableDepthWrite?!t.disableDepthWrite:"boolean"==typeof t?.forceDepthWrite?t.forceDepthWrite:i.materialDepthWrite),c=e.alphaTest??(()=>{const e=t?.transparencyMode,s=1===e||3===e;return s&&"number"==typeof t?.alphaCutOff?t.alphaCutOff:s&&"number"==typeof t?.alphaCutOffValue?t.alphaCutOffValue:t?0:i.materialAlphaTest})();return{texture:s,reflectionTexture:n,reflectionLevel:"number"==typeof t?.reflectionLevel?t.reflectionLevel:r,reflectionAtlas:na(t?.reflectionAtlas)??na(e.reflectionAtlas)??na(i.reflectionAtlas),blendMode:o,transparent:a,depthTest:h,depthWrite:l,alphaTest:c}}(t,e,this.rendererSettings);this.rendererSettings.texture=i.texture,this.rendererSettings.reflectionTexture=i.reflectionTexture,this.rendererSettings.reflectionLevel=i.reflectionLevel;let s=i.reflectionAtlas;const n=i.reflectionTexture;!s&&n?.isCube&&(s=Po(n,this.sceneRef),!s&&this.sceneRef&&(Co(n,this.sceneRef,e=>{this.rendererSettings.reflectionAtlas!==e&&(this.rendererSettings.reflectionAtlas=e,t&&!na(t.reflectionAtlas)&&(t.reflectionAtlas=e),this.watchEnvAtlas(e,t),this.neededToUpdateRender=!0)}),s=Po(n,this.sceneRef))),this.rendererSettings.reflectionAtlas=s,this.watchEnvAtlas(s,t),this.rendererSettings.materialBlendMode=i.blendMode,this.rendererSettings.materialTransparent=i.transparent,this.rendererSettings.materialDepthTest=i.depthTest,this.rendererSettings.materialDepthWrite=i.depthWrite,this.rendererSettings.materialAlphaTest=pn(i.alphaTest),void 0!==e.layerMask&&(this.rendererSettings.layerMask=e.layerMask),this.neededToUpdateRender=!0}pause(){this.paused=!0}play(){this.destroyed||(this.isFinished()&&this.restart(),this.resume())}resume(){this.destroyed||(this.paused=!1,this.previousEmitterMatrix=void 0)}stop(){this.restart(),this.pause()}clear(){this.particleNum=0,this.bounds.valid=!1;for(const t of this.behaviors)t instanceof ci&&t.clearEmissions()}clearTrails(){if(this.rendererSettings.renderMode===Rs.Trail)for(let t=0;t<this.particleNum;t++)this.particles[t].resetHistory()}setQualityFactor(t){this.qualityFactor=Math.max(.1,Math.min(1,t))}emissionFactor(){return this.qualityFactor*this.emissionMultiplierValue}endEmit(){this.emitEnded=!0,this.events.fire({type:"emitEnd",particleSystem:this})}get isDisposed(){return this.destroyed}dispose(){this.destroyed||(this.destroyed=!0,this.particleNum=0,this._renderer&&this._renderer.deleteSystem(this),function(t){po++;try{t.dispose()}finally{po--}}(this.emitter),this.events.fire({type:"destroy",particleSystem:this}))}initSystemGenerators(){const t=this.rng,e=void 0===t?void 0:E(t);try{this.clock.setStartDelay(this.emission.rollGenerators())}finally{void 0!==t&&E(e??null)}}restart(){this.destroyed||(this.emission.memory.length=0,this.paused=!1,this.particleNum=0,this.bounds.valid=!1,this.clock.reset(),void 0!==this.seedValue&&(this.rng=$(this.seedValue)),this.emissionState.isBursting=!1,this.emissionState.burstIndex=0,this.emissionState.burstWaveIndex=0,this.emissionState.burstWaves=void 0,this.emissionState.time=0,this.emissionState.waitEmiting=0,this.emissionState.travelDistance=0,this.emissionState.previousWorldPos=void 0,this.emissionState.burstParticleIndex=0,this.emissionState.burstParticleCount=0,this.emissionBursts.forEach(t=>Object.assign(t,vn(t))),this.emissionBursts.sort((t,e)=>t.time-e.time),this.behaviors.forEach(t=>t.reset()),this.emitterShape.reset?.(),this.emitEnded=!1,this.finishedEventFired=!1,this.stopActionPending=!1,this.prewarmed=!1,this.initSystemGenerators(),this.previousEmitterPos=void 0,this.previousEmitterMatrix=void 0,this.emitterVelocity.set(0,0,0))}update(t,e=1/0,i){if(this.paused||this.destroyed)return;const s=this.playbackSpeed*this.timeDilationValue;if(t=Ko.frameSeconds(t,s),this.culled)return"pauseAndCatchUp"===this.cullingMode&&this.clock.deferCatchUp(t),void(this.previousEmitterMatrix=void 0);if(this.clock.owesCatchUp){if(this.catchUp(i??performance.now()+Wa.catchUpBudgetMs),this.paused||this.destroyed)return;(this.previousEmitterMatrix??(this.previousEmitterMatrix=new ft)).copy(this.emitter.matrixWorld)}if(this.firstTimeUpdate&&(this.firstTimeUpdate=!1,this.emitter.computeWorldMatrix(!0)),!this.looping&&this.finishedEventFired&&0===this.particleNum){if(this.applyStopAction(),this.destroyed)return;return void this.clock.accrue(t,s)}if(this.looping&&this.prewarm&&!this.prewarmed&&(this.runPrewarm(),this.paused||this.destroyed))return;this.neededToUpdateRender&&(this._renderer&&this._renderer.updateSystem(this),this.neededToUpdateRender=!1);const n=this.emitter.matrixWorld.elements;if(this.tempEmitterPos.set(n[12],n[13],n[14]),void 0!==this.previousEmitterPos&&t>0&&this.emitterVelocity.copy(this.tempEmitterPos).sub(this.previousEmitterPos).divideScalar(t),(this.previousEmitterPos??(this.previousEmitterPos=new ht)).copy(this.tempEmitterPos),this.clock.delaying&&(!this.prewarm||!this.looping)&&0===(t=this.clock.consumeStartDelay(t)))return;const r=this.clock.accrue(t,s);if(0===r)return;const o=this.emitter.matrixWorld,a=this.previousEmitterMatrix,h=r>1&&void 0!==a&&!a.equals(o);h&&(a.decompose(Ba,Ua,Ra),o.decompose(La,Da,ka));let l=o;for(let t=0;t<r;t++){if(h&&t+1<r){const e=(t+1)/r;qa.copy(Ba).lerp(La,e),Ja.copy(Ua).slerp(Da,e),Ga.copy(Ra).lerp(ka,e),l=this.stepMatrix.compose(qa,Ja,Ga)}else l=o;if(this.simulateStep(Zo,l),this.paused||this.destroyed)break;if(e!==1/0&&t+1<r&&performance.now()>=e)break}this.destroyed||(this.previousEmitterMatrix??(this.previousEmitterMatrix=new ft)).copy(l)}catchUp(t){let e=this.clock.takeCatchUpSteps();for(;e-- >0&&(this.simulateStep(Zo),!this.paused&&!this.destroyed)&&!(e>0&&performance.now()>=t););}markBurstsBefore(t){const e=this.emissionState,i=this.emissionBursts,s=e.burstWaves??(e.burstWaves=[]);for(;e.burstIndex<i.length&&i[e.burstIndex].time<t;){const n=i[e.burstIndex],r=Lo(n),o=Do(n);let a=0;if(o>0)for(;a<r&&n.time+a*o<t;)a++;else a=r;s[e.burstIndex]=a,e.burstIndex++}}runPrewarm(){this.prewarmed=!0;const t=this.prewarmTime>0?this.prewarmTime:this.duration,e=Math.min(this.duration,t,Math.max(0,Wa.maxPrewarmSeconds)),i=Math.round(e/Zo);if(e<this.duration){const t=this.emissionState;t.time=this.duration-i*Zo,this.markBurstsBefore(t.time)}for(let t=0;t<i;t++)if(this.simulateStep(Zo),this.paused||this.destroyed)return}getWorldBounds(t,e){if(!this.bounds.toWorld(t,e,this.emitter))return!1;if(this.rendererSettings.renderMode===Rs.Beam){const i=this.beamEndScratch;if(!this.getBeamEnd(i))return!0;const s=this.bounds.worldPadding(this.emitter);t.set(Math.min(t.x,i.x-s),Math.min(t.y,i.y-s),Math.min(t.z,i.z-s)),e.set(Math.max(e.x,i.x+s),Math.max(e.y,i.y+s),Math.max(e.z,i.z+s))}return!0}getBeamEnd(t){const e=this.beamEnd;if(void 0===e)return!1;const i=e;if("function"==typeof i.getAbsolutePosition){const e=i.getAbsolutePosition();t.set(e.x,e.y,e.z)}else{const i=e;t.set(i.x,i.y,i.z)}return!0}setWorldBounds(t,e,i,s,n,r,o){this.bounds.setWorld(t,e,i,s,n,r,o)}get simulationStep(){return Zo}get simulationResidual(){return this.paused?0:this.clock.residual}simulateStep(t,e=this.emitter.matrixWorld){const i=this.rng;if(void 0===i)return void this.stepOnce(t,e);const s=E(i);try{this.stepOnce(t,e)}finally{E(s)}}stepOnce(t,e){if(this.destroyed)return;this.spawner.fitRing(),this.motionScale=this.measureMotionScale(e),this.onlyUsedByOther||this.emission.emit(t,this.emissionState,e);const i=this.particles,s=this.behaviors,n=this.particleNum,r=this.store,o=this.rendererSettings.renderMode,a=o===Rs.Trail,h=this.behaviorPlan.steps(s),l=this.behaviorPlan.changesSize,c=this.behaviorPlan.changesColor;!function(t,e,i,s,n,r){const o=3*e;t.useSizeSnapshot(i),t.useColorSnapshot(s),t.previousPosition.set(t.position.subarray(0,o)),i&&t.previousSize.set(t.size.subarray(0,o)),n&&(t.keepPreviousVelocity()&&r(),t.previousVelocity.set(t.velocity.subarray(0,o))),s&&t.previousColor.set(t.color.subarray(0,4*e))}(r,n,l,c,o===Rs.StretchedBillBoard,this.rebindParticles),this.emitterShape.update(this,t),function(t,e,i,s,n,r){for(let o=0;o<t.length;o++){const a=t[o],h=a.behaviors;for(let t=0;t<h.length;t++)h[t].frameUpdate(n);if(0===s)continue;if(void 0!==a.run){a.run(e,i,s,n,r);continue}const l=h[0];if(void 0===l.updateAll)for(let t=0;t<s;t++){const e=i[t];e.age<e.life&&l.update(e,n)}else l.updateAll(i,s,n)}}(h,s,i,n,t,r);const u=this.events.has("particleDied")?this.fireParticleDied:void 0;let d=this.particleNum;if(a){const s=this.rendererEmitterSettings;!function(t,e,i,s){const n=t.scalars,r=We.SCALAR_STRIDE,o=t.previousSize,a=t.size,h=t.previousColor,l=t.color;for(let t=0,c=0,u=0,d=0;t<e;t++,c+=3,u+=4,d+=r)0===n[d+We.AGE]&&(i&&(o[c]=a[c],o[c+1]=a[c+1],o[c+2]=a[c+2]),s&&(h[u]=l[u],h[u+1]=l[u+1],h[u+2]=l[u+2],h[u+3]=l[u+3]))}(r,n,l,c),function(t,e,i,s,n,r){if(n){for(let i=0;i<s;i++){const s=e[i];s.localPosition?(s.position.copy(s.localPosition),s.position.applyMatrix4(s.parentMatrix??r)):s.position.addScaledVector(s.velocity,t*s.speedModifier),s.age+=t}return}const o=i.scalars,a=We.SCALAR_STRIDE,h=i.position,l=i.velocity;for(let e=0,i=0,n=0;e<s;e++,i+=3,n+=a){const e=t*o[n+We.SPEED_MODIFIER];h[i]+=l[i]*e,h[i+1]+=l[i+1]*e,h[i+2]+=l[i+2]*e,o[n+We.AGE]+=t}}(t,i,r,n,Boolean(s.followLocalOrigin),e),function(t,e,i,s,n){const r=i.dieWithParticle,o=i.recordWorldSpace&&!s,a=i.sideAxis,h=s||Boolean(i.recordWorldSpace),l=Zr(i),c=Kr(i);for(let i=0;i<e;i++){const e=t[i],s=e.age<e.life;if(r&&!s){e.resetHistory();continue}let u=!1;if(l>0&&s&&e.historyCount>1){const t=e.historyDistances,i=e.historyCount;u=t[e.getHistoryIndex(i-1)]-t[e.getHistoryIndex(i-2)]<l}if(e.update(u,!o),o&&s){const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,i=e.historyPositions;ta.set(i[t],i[t+1],i[t+2]),ta.applyMatrix4(e.parentMatrix??n),i[t]=ta.x,i[t+1]=ta.y,i[t+2]=ta.z,e.measureHeadDistance()}if(c!==1/0){const t=e.historyAges,i=e.age;for(;e.historyCount>0&&i-t[e.getHistoryIndex(0)]>c;)e.dropOldest()}if(a&&s){e.ensureSideHistory();const t=(e.historyHead+e.historyCapacity-1)%e.historyCapacity*3,i=e.historySides;let s=a.x,r=a.y,o=a.z;if(h){const t=(e.parentMatrix??n).elements,i=t[0]*s+t[4]*r+t[8]*o,a=t[1]*s+t[5]*r+t[9]*o;o=t[2]*s+t[6]*r+t[10]*o,s=i,r=a}i[t]=s,i[t+1]=r,i[t+2]=o}}}(i,n,s,this.worldSpace,e),d=function(t,e,i,s){const n=e.scalars,r=We.SCALAR_STRIDE;for(let o=0;o<i;o++){const a=t[o],h=o*r;n[h+We.AGE]>=n[h+We.LIFE]&&0===a.historyCount&&(ea(t,e,o,i-1),i--,o--,void 0!==s&&s(a))}return i}(i,r,d,u)}else d=function(t,e,i,s,n,r,o,a,h,l){const c=i.scalars,u=void 0!==l&&l.pause,d=We.SCALAR_STRIDE,f=i.position,m=i.velocity,p=i.previousSize,y=i.size,g=i.previousColor,v=i.color,x=o.due,S=o.min,b=o.max;let w=x?1/0:S.x,M=x?1/0:S.y,z=x?1/0:S.z,_=x?-1/0:b.x,A=x?-1/0:b.y,P=x?-1/0:b.z,O=x?0:o.maxSize,T=x?0:o.maxSpeedSq;for(let o=0;o<s;o++){const a=o*d;let S=c[a+We.AGE];const b=3*o,V=x||0===S;if(0===S&&(n&&(p[b]=y[b],p[b+1]=y[b+1],p[b+2]=y[b+2]),r)){const t=4*o;g[t]=v[t],g[t+1]=v[t+1],g[t+2]=v[t+2],g[t+3]=v[t+3]}const E=c[a+We.LIFE],$=void 0===l?1/0:u?E:sa(l,E),C=S>=$,I=C?0:t*c[a+We.SPEED_MODIFIER],N=m[b],F=m[b+1],B=m[b+2],U=f[b]+N*I,R=f[b+1]+F*I,L=f[b+2]+B*I;if(f[b]=U,f[b+1]=R,f[b+2]=L,V&&(w=Math.min(w,U),_=Math.max(_,U),M=Math.min(M,R),A=Math.max(A,R),z=Math.min(z,L),P=Math.max(P,L),O=Math.max(O,Math.max(y[b],Math.max(y[b+1],y[b+2])))),!C)if(T=Math.max(T,N*N+F*F+B*B),S+=t,c[a+We.AGE]=S,void 0!==l){if(S>$)c[a+We.AGE]=$;else if(!u&&$===1/0&&S>=l.loopEnd*E){const t=l.loopStart*E+(S-l.loopEnd*E)%((l.loopEnd-l.loopStart)*E);c[a+We.AGE]=t>0?t:ia*E,p[b]=y[b],p[b+1]=y[b+1],p[b+2]=y[b+2];const e=4*o;g[e]=v[e],g[e+1]=v[e+1],g[e+2]=v[e+2],g[e+3]=v[e+3]}}else if(S>=E){const t=ea(e,i,o,s-1);s--,o--,void 0!==h&&h(t)}}return o.store(s,x,w,M,z,_,A,P,O,T,a.rendererSettings,a.rendererEmitterSettings,a.worldSpace,Zo),s}(t,i,r,d,l,c,this.bounds,this,u,this.ringBufferStep());this.particleNum=this.destroyed?0:d,this.notifyFinished()}hasPendingSubEmission(){for(const t of this.behaviors)if(t instanceof ci&&t.hasPendingEmission())return!0;return!1}isAlive(t=!0){return!this.isFinished()||t&&this.subEmittersAlive(new Set([this]))}subEmittersAlive(t){for(const e of this.behaviors){if(!(e instanceof ci))continue;const i=e.targetSystem;if(i instanceof Wa&&!t.has(i)&&(t.add(i),i.particleNum>0||i.hasPendingSubEmission()||i.subEmittersAlive(t)))return!0}return!1}get ringBufferActive(){return"disabled"!==this.ringBufferMode&&void 0!==this.maxParticles&&this.rendererSettings.renderMode!==Rs.Trail}ringBufferStep(){if(!this.ringBufferActive)return;const t=this.ringStep;t.pause="pauseUntilReplaced"===this.ringBufferMode;const{x:e,y:i}=this.ringBufferLoopRange,s=Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,n=Number.isFinite(i)?Math.min(1,Math.max(0,i)):1;return t.loopStart=Math.min(s,n),t.loopEnd=Math.max(s,n),t}notifyFinished(){this.isFinished()&&(this.finishedEventFired||(this.finishedEventFired=!0,this.stopActionPending=!0,this.events.fire({type:"finished",particleSystem:this})),this.applyStopAction())}applyStopAction(){this.stopActionPending&&("none"===this.stopAction||this.ignoreStopAction||this.onlyUsedByOther||this.destroyed?this.stopActionPending=!1:this.subEmittersAlive(new Set([this]))||(this.stopActionPending=!1,"disable"===this.stopAction?this.emitter.setEnabled(!1):this.dispose()))}emit(t,e,i){this.emission.emit(t,e,i)}toJSON(t,e={}){return Na(this,t)}static fromJSON(t,e,i={},s){const n=new Wa(Fa(t,e,s));return n.behaviors=(t.behaviors??[]).map((t,e)=>{const s=Zt(`behaviors[${e}]`,()=>Qi(t,n)),r=t.subParticleSystem;return s&&"EmitSubParticleSystem"===s.type&&"string"==typeof r&&(i[r]=s),s}).filter(t=>null!==t),n}addBehavior(t){this.behaviors.push(t),this._renderer?._invalidateUpdateOrder()}getRendererSettings(){return this.rendererSettings}addEventListener(t,e){this.events.add(t,e)}removeAllEventListeners(t){this.events.removeAll(t)}removeEventListener(t,e){this.events.remove(t,e)}clone(){const t=this.behaviors.map(t=>t.clone());let e;if(this.renderMode===Rs.Trail){const t=this.rendererEmitterSettings;e={startLength:t.startLength.clone(),followLocalOrigin:Boolean(t.followLocalOrigin),...Ta(t),...Va(t),...Ea(t),...t.sideAxis?{sideAxis:t.sideAxis.clone()}:{}}}else e=this.renderMode===Rs.StretchedBillBoard?{lengthFactor:this.rendererEmitterSettings.lengthFactor,speedFactor:this.rendererEmitterSettings.speedFactor}:{};const i=new Wa({...za(this),shape:this.emitterShape.clone(),instancingGeometry:this.rendererSettings.instancingGeometry,instancingIndices:this.rendererSettings.instancingIndices,instancingUVs:this.rendererSettings.instancingUVs,instancingUVs2:this.rendererSettings.instancingUVs2,instancingNormals:this.rendererSettings.instancingNormals,rendererEmitterSettings:e,material:this.materialRef,texture:this.rendererSettings.texture,behaviors:t,lighting:this.lighting,rim:this.rim,mapUV:this.mapUV,gradientMap:this.gradientMap,erosion:this.erosion,uvDistortion:this.uvDistortion,scene:this.emitter.getScene()});for(const e of t)e instanceof ci&&(e.particleSystem=i);this.tint&&(i.tint=this.tint.clone()),i.emissionMultiplier=this.emissionMultiplier;const s=this.beamEnd;return s&&(i.beamEnd="function"==typeof s.getAbsolutePosition?s:{x:s.x,y:s.y,z:s.z}),i}}function ja(t){if("ps"===t.type&&t.target instanceof yo)return t.target.system}function Qa(t){return"object"==typeof t&&null!==t}Wa.catchUpBudgetMs=2,Wa.maxPrewarmSeconds=10;class Ha extends n{constructor(t="QuarksPrefab",e){super(t,e),this.type="QuarksPrefab",this.animationData=[],this.isPlaying=!1,this.currentTime=-1e-5,this.duration=0,this._timeScale=1,this._tempAnimationJSON=[],this._autoUpdate=null,this._pendingEndEmit=new Set,this._pendingObserver=null,this._started=new Set,this._pausedSystems=new Set}get timeScale(){return this._timeScale}set timeScale(t){this._timeScale=t>0&&t<1/0?t:0;for(const t of this.animationData){const e=ja(t);void 0!==e&&(e.timeDilation=this._timeScale)}}get autoUpdate(){return null!==this._autoUpdate}set autoUpdate(t){t!==this.autoUpdate&&(t?this._autoUpdate=this.getScene().onBeforeRenderObservable.add(()=>this.update()):(this.getScene().onBeforeRenderObservable.remove(this._autoUpdate),this._autoUpdate=null))}registerBatchedRenderer(t){this._batchedRenderer=t}addParticleSystemAnimation(t,e=0,i=0,s=!1){const n={startTime:e,duration:i>0?i:t.system.duration,type:"ps",loop:s,target:t};return this.animationData.push(n),t.system.timeDilation=this._timeScale,this.updateDuration(),n}addThreeAnimation(t,e,i=0,s=e?.duration??0,n=!1,r){const o={startTime:i,duration:s>0?s:e?.duration??0,type:"three",loop:n,target:t,clip:e,clipUUID:r??e?.uuid};return this.animationData.push(o),this.updateDuration(),o}removeAnimation(t){const[e]=this.animationData.splice(t,1),i=e&&ja(e);void 0===i||this.animationData.some(t=>ja(t)===i)||(i.timeDilation=1,this._pendingEndEmit.delete(i)&&i.endEmit(),this._started.delete(i),this._pausedSystems.delete(i)),this.updateDuration()}play(){if(!this.isPlaying){this.isPlaying=!0;for(const t of this._pausedSystems)t.resume();this._pausedSystems.clear(),this.animationData.forEach(t=>{"three"===t.type&&this.isInside(t,this.currentTime)&&t.clip?.play?.()})}}pause(){this.isPlaying&&(this.isPlaying=!1,this.animationData.forEach(t=>{const e=ja(t);void 0===e?t.clip?.pause?.():e.paused||(e.pause(),this._pausedSystems.add(e))}))}stop(){this.pause(),this.currentTime=-1e-5,this.clearPending(),this._started.clear(),this._pausedSystems.clear(),this.animationData.forEach(t=>{const e=ja(t);void 0===e?t.clip?.stop?.():e.stop()})}update(t){if(this.flushPending(),!this.isPlaying)return;const e=t??this.getScene().getEngine().getDeltaTime()/1e3,i=this.currentTime,s=i+Math.max(e,0)*this._timeScale>=this.duration;if(this.currentTime=s?this.duration:i+Math.max(e,0)*this._timeScale,this.animationData.forEach(t=>{const e=this.isInside(t,i),n=this.isInside(t,this.currentTime),r=!e&&!n&&i<t.startTime&&this.currentTime>=t.startTime+t.duration;if(n&&!e)this.enterTrack(t);else if(r){this.enterTrack(t);const e=ja(t);void 0!==e?this.addPending(e):t.clip?.stop?.()}else e&&!n&&this.leaveTrack(t,!s)}),s){for(const t of this._started)this._pendingEndEmit.has(t)||t.isEmitEnded||t.endEmit();this._started.clear(),this.isPlaying=!1,this.currentTime=-1e-5}}setTime(t){const e=this.currentTime;this.currentTime=t,this.animationData.forEach(i=>{const s=this.isInside(i,t),n=this.isInside(i,e);if(s&&!n)this.enterTrack(i);else if(!s&&n)return void this.leaveTrack(i,!1);s&&"three"===i.type&&i.clip?.setTime?.(Math.max(t-i.startTime,0))})}dispose(t,e){this.autoUpdate=!1;for(const t of this._pendingEndEmit)t.endEmit();this.clearPending(),this._started.clear(),this._pausedSystems.clear(),super.dispose(t,e)}addPending(t){this._pendingEndEmit.add(t),this._pendingObserver??(this._pendingObserver=this.getScene().onAfterRenderObservable.add(()=>this.flushPending()))}flushPending(){for(const t of this._pendingEndEmit)(t.emissionState.time>0||t.isDisposed)&&(t.endEmit(),this._pendingEndEmit.delete(t));0===this._pendingEndEmit.size&&this.clearPending()}clearPending(){this._pendingEndEmit.clear(),null!==this._pendingObserver&&(this.getScene().onAfterRenderObservable.remove(this._pendingObserver),this._pendingObserver=null)}isInside(t,e){return e>=t.startTime&&e<t.startTime+t.duration}enterTrack(t){const e=ja(t);if(void 0!==e)return this._pendingEndEmit.delete(e),e.restart(),this._started.add(e),this.isPlaying||(e.pause(),this._pausedSystems.add(e)),void this._batchedRenderer?.addSystem(e);t.clip?.play?.()}leaveTrack(t,e){const i=ja(t);void 0===i?t.loop&&e?t.clip?.play?.():t.clip?.stop?.():t.loop&&e?i.restart():i.endEmit()}getDuration(){return this.duration}resolveReferences(t){const e={},i=t=>{var s;const r=Fs(t);r?e[r]=t:e[s=t.uniqueId.toString()]??(e[s]=t);const o=t.getChildren();for(const t of o)t instanceof n&&i(t)};i(t),this._tempAnimationJSON.forEach(t=>{const i=e[t.targetUUID];if("ps"===t.type&&i instanceof yo)this.addParticleSystemAnimation(i,t.startTime,t.duration,t.loop);else if("three"===t.type&&i){const e=this.resolveTimelineClip(i,t.clipUUID);this.addThreeAnimation(i,e,t.startTime,t.duration,t.loop,t.clipUUID)}}),this.updateDuration(),this._tempAnimationJSON=[]}toJSON(){return{type:this.type,name:this.name,...1!==this.timeScale?{timeScale:this.timeScale}:{},animationData:this.animationData.map(t=>({startTime:t.startTime,duration:t.duration,type:t.type,targetUUID:Ns(t.target),clipUUID:"three"===t.type?t.clipUUID??t.clip?.uuid:void 0,loop:t.loop}))}}static fromJSON(t,e){const i=new Ha(t.name||"QuarksPrefab",e);return"number"==typeof t.timeScale&&(i.timeScale=t.timeScale),Array.isArray(t.animationData)&&(i._tempAnimationJSON=t.animationData.filter(t=>"ps"===t?.type||"three"===t?.type)),i}resolveTimelineClip(t,e){const i=t,s=t.metadata,n=[i.animations,i.animationGroups,s?.animations,s?.animationGroups];for(const t of n){if(!Array.isArray(t))continue;const i=t;if(!e)return i.find(Qa);const s=i.find(t=>{return s=e,Qa(i=t)&&i.uuid===s;var i,s});if(s)return s}}updateDuration(){let t=0;this.animationData.forEach(e=>{const i=e.startTime+e.duration;i>t&&(t=i)}),this.duration=t}}const Ya=new WeakMap;function Xa(t,e,i){Ya.set(t,{source:e,loaded:i})}function Za(t){const e=Ya.get(t);return void 0!==e&&t.url===e.loaded?e.source:void 0}const Ka=2,th={[A.WRAP_ADDRESSMODE]:1e3,[A.CLAMP_ADDRESSMODE]:1001,[A.MIRROR_ADDRESSMODE]:1002};function eh(t){return!!t&&(!/^blob:/i.test(t)&&(!/^data:/i.test(t)||t.includes(",")))}function ih(t){const e=t.rotationQuaternion??u.FromEulerVector(t.rotation);return Array.from(h.Compose(t.scaling,e,t.position).asArray())}class sh{constructor(t){this.options=t,this.meta={geometries:{},materials:{},textures:{}},this.meshGeometries=new Map,this.geometryIds=new Map,this.meshMaterials=[],this.meshMaterialIds=new Map,this.extraTextures=new Map,this.nextId=0}warnDanglingLinks(t){const e=new Set,i=[],s=t=>{e.add(t.uuid),i.push(t),t.children?.forEach(s)};s(t);for(const t of i)for(const[i,s]of rh(t))""===s||e.has(s)||this.warn(`"${t.name}" has ${i} on node "${s}", which is not in what is written; it loads without that link.`)}warn(t){(this.options.onWarning??(t=>console.warn(`[quarks] ${t}`)))(t)}node(t){const e=t.getChildren(t=>t instanceof n,!0).filter(t=>!1!==this.options.filter?.(t)).map(t=>this.node(t)),i={uuid:Ns(t),type:"Group",name:t.name,matrix:ih(t)};if(t.isEnabled(!1)||(i.visible=!1),t instanceof p&&!t.isVisible&&(i.isVisible=!1),t instanceof yo)i.type="ParticleEmitter",i.ps=t.system.toJSON(this.meta);else if(t instanceof Ha){const{type:e,name:s,...n}=t.toJSON();Object.assign(i,n),i.type="QuarksPrefab"}else t instanceof p?(i.type="Mesh",i.geometry=this.meshGeometry(t),i.material=this.meshMaterial(t)):t instanceof _&&this.warn(`"${t.name}" is an instance of "${t.sourceMesh.name}"; it is written as a group.`);return e.length>0&&(i.children=e),i}id(t){return this.nextId+=1,`${t}_${this.nextId}`}meshGeometry(e){const i=e.geometry?this.geometryIds.get(e.geometry):void 0;if(void 0!==i)return i;const s=e.getVerticesData(t.PositionKind);if(!s||0===s.length)return void this.warn(`Mesh "${e.name}" has no vertices; it is written without geometry.`);const n=e.getIndices(),r=Cs(s instanceof Float32Array?s:new Float32Array(s),n&&n.length>0?Uint32Array.from(n):void 0),o=t=>{const i=e.getVerticesData(t);return i?Array.from(i):void 0},a={uuid:this.id("quarks_mesh_geometry"),type:"QuarksGeometry",positions:Array.from(s),indices:Array.from(r)},h=o(t.UVKind),l=o(t.UV2Kind),c=o(t.NormalKind);return h&&(a.uvs=h),l&&(a.uvs2=l),c&&(a.normals=c),this.meshGeometries.set(a.uuid,a),e.geometry&&this.geometryIds.set(e.geometry,a.uuid),a.uuid}meshMaterial(t){const e=t.material;if(!e)return;if(!(e instanceof P))return void this.warn(`Mesh "${t.name}" has a ${e.getClassName()}; only a StandardMaterial's blend, culling and diffuse texture are written, so it loads without a material.`);let i=this.meshMaterialIds.get(e);if(void 0!==i)return i;i=this.id("quarks_mesh_material"),this.meshMaterialIds.set(e,i);const s=1===e.diffuseColor.r&&1===e.diffuseColor.g&&1===e.diffuseColor.b,n=0===e.emissiveColor.r&&0===e.emissiveColor.g&&0===e.emissiveColor.b;1===e.alpha&&s&&n||this.warn(`Mesh "${t.name}": its material's alpha and colours are not written; it loads opaque white.`);const o={uuid:i,type:"MeshBasicMaterial"};return e.alphaMode!==r.ALPHA_COMBINE&&(o.alphaMode=e.alphaMode),e.backFaceCulling&&(o.side=0),0!==e.alphaCutOff&&(o.alphaTest=e.alphaCutOff),e.disableDepthWrite||(o.depthWrite=!0),this.meshMaterials.push({json:o,map:e.diffuseTexture}),i}texture(t){for(const[e,i]of Object.entries(this.meta.textures))if(i===t)return e;let e=this.extraTextures.get(t);return void 0===e&&(e=this.id("quarks_mesh_texture"),this.extraTextures.set(t,e)),e}finish(t){const e=this.meshMaterials.map(({json:t,map:e})=>e?{...t,map:this.texture(e)}:t);this.warnDanglingLinks(t);const i=[],s=new Map,n=[],r=[...Object.entries(this.meta.textures),...[...this.extraTextures].map(([t,e])=>[e,t])];for(const[t,e]of r){if(null===e)continue;const r={uuid:t},o=e instanceof A?this.options.imageUrl?this.options.imageUrl(e):Za(e)??e.url:null;if(eh(o)){let t=s.get(o);void 0===t&&(t=`quarks_image_${s.size+1}`,s.set(o,t),i.push({uuid:t,url:o})),r.image=t}else this.warn(`Texture "${e.name}" has no url a file can point at (made in code, a blob: url, or an image embedded in a glTF); it is written without its image and loads as no texture. Give it a file url or a data: URI before saving.`);e instanceof A&&Object.assign(r,oh(e)),n.push(r)}const o=Object.values(this.meta.materials).map(t=>{const{sourceMaterial:e,...i}=t;return i});return{metadata:{version:4.5,type:"Object3D",generator:this.options.generator??"babylon.quarks",quarksFormat:2},geometries:[...Object.values(this.meta.geometries).filter(nh),...this.meshGeometries.values()],materials:[...o,...e],textures:n,images:i,object:t}}}function nh(t){return"type"in t&&"QuarksGeometry"===t.type&&Array.isArray(t.positions)}function*rh(t){const e=t.ps;for(const t of e?.behaviors??[])"EmitSubParticleSystem"===t.type&&"subParticleSystem"in t&&"string"==typeof t.subParticleSystem&&(yield["a sub emitter",t.subParticleSystem]);"mesh_surface"===e?.shape?.type&&"string"==typeof e.shape.mesh&&(yield["a mesh surface shape",e.shape.mesh]);for(const e of t.animationData??[])"string"==typeof e.targetUUID&&(yield["a prefab animation",e.targetUUID])}function oh(t){const e={};return t.invertY||(e.invertY=!1),t.noMipmap&&(e.noMipmap=!0),t.samplingMode!==r.TEXTURE_TRILINEAR_SAMPLINGMODE&&(e.samplingMode=t.samplingMode),t.wrapU===A.WRAP_ADDRESSMODE&&t.wrapV===A.WRAP_ADDRESSMODE||(e.wrap=[th[t.wrapU]??1e3,th[t.wrapV]??1e3]),1===t.uScale&&1===t.vScale||(e.repeat=[t.uScale,t.vScale]),0===t.uOffset&&0===t.vOffset||(e.offset=[t.uOffset,t.vOffset]),0!==t.wAng&&(e.rotation=t.wAng),e}function ah(t,e={}){const i=new sh(e);let s;if(Array.isArray(t)){const n=e.name??"effect";s={uuid:`${n}-root`,type:"Group",name:n,matrix:h.Identity().asArray().slice(),children:t.map(t=>i.node(t))}}else s=i.node(t);return i.finish(s)}function hh(t){return null!==t&&"object"==typeof t}function lh(t){if(!Array.isArray(t))return te("This part is not a list; it is skipped."),[];const e=[];return t.forEach((t,i)=>{hh(t)?e.push(t):Zt(`[${i}]`,()=>te("This entry is not an object; it is skipped."))}),e}function ch(t,e){const i=hh(t)?t[e]:void 0;return Array.isArray(i)?i:[]}const uh=new WeakMap,dh=new WeakMap,fh=new WeakMap,mh=new WeakMap,ph=new WeakMap;function yh(t,e){let i=t.get(e);return void 0===i&&(i=new Map,t.set(e,i)),i}const gh=new WeakMap,vh=new WeakMap;function xh(t){if(!hh(t))return t;const e={...t};return Array.isArray(t.images)&&(e.images=t.images.map(t=>{if(!t||"object"!=typeof t)return t;const e={...t};if(gh.get(t)===e.url&&"string"==typeof e.url){gh.set(e,e.url);const i=vh.get(t);void 0!==i&&vh.set(e,i)}return e})),Array.isArray(t.geometries)&&(e.geometries=t.geometries.map(t=>t&&"object"==typeof t?{...t}:t)),e}const Sh=new WeakMap,bh=t=>t.reason??new Error("[QuarksLoader] The load was aborted."),wh=()=>new Error("[QuarksLoader] The scene was disposed while the effect loaded.");function Mh(t,e){if(e?.aborted)throw bh(e);if(t.isDisposed)throw wh()}function zh(t,e,i){return Mh(e,i),new Promise((s,n)=>{const r=()=>n(bh(i));i?.addEventListener("abort",r,{once:!0});const o=e.onDisposeObservable.addOnce(()=>n(wh()));t.then(s,n).finally(()=>{i?.removeEventListener("abort",r),e.onDisposeObservable.remove(o)})})}class _h{constructor(t,e={}){this.scene=t,this.options=e}async load(t,e={}){const{json:i,baseUrl:s}=await zh(this.fetchEffectDocument(t,e.signal),this.scene,e.signal);return this.loadFromJSON(i,s,e)}async loadFromJSON(t,e,i={}){const s=i.signal;Mh(this.scene,s);const n=e??this.options.baseUrl??"",r=xh(t);await zh(this.resolveResources(r,n),this.scene,s);const o=this.parseDocument(r,"");return await this.finishLoad(o,s),o.root}static disposeEffect(t){ho(t)}async finishLoad(t,e){try{if(this.options.waitForTextures){for(const e of t.textures)e.delayLoadState===r.DELAYLOADSTATE_NOTLOADED&&e.delayLoad();await zh(Promise.all(t.textures.map(t=>Sh.get(t))),this.scene,e)}Mh(this.scene,e)}catch(e){throw this.scene.isDisposed||ho(t.root),e}}async loadAll(t,e={}){Mh(this.scene,e.signal);const i=_h.mapPool(t,e.concurrency,async(i,s)=>{Mh(this.scene,e.signal);try{return await this.fetchEffectDocument(i,e.signal)}catch(n){if(!e.continueOnError||e.signal?.aborted||this.scene.isDisposed)throw n;return console.warn(`[QuarksLoader] Failed to fetch effect "${i}" (${s+1}/${t.length}):`,n),null}}),s=await zh(i,this.scene,e.signal);return this.loadDocuments(s,e)}async loadFromJSONAll(t,e={}){const i=t.map(t=>{if(null!==t&&"object"==typeof t&&"json"in t){const e=t;return{json:xh(e.json),baseUrl:e.baseUrl??this.options.baseUrl??""}}return{json:xh(t),baseUrl:this.options.baseUrl??""}});return this.loadDocuments(i,e)}async resolveResources(t,e=""){await _h.resolveLinkedResources(t,{baseUrl:e,resolver:this.options.resolver,scene:this.scene,onResourceError:this.options.onResourceError})}static async resolveLinkedResources(t,e={}){const i=e.baseUrl??"",s=e.resolver,n=e.scene;await _h.inlineGeometryEntries(t,async t=>{const e=await _h.resolveWith(s,t,"geometry",i);return _h.fetchJsonWith(s,e,n)},e.onResourceError),await Promise.all(ch(t,"images").map(async t=>{if(!hh(t)||"string"!=typeof t.url||!t.url)return;if(gh.get(t)===t.url)return;const e=t.url,n=await _h.resolveWith(s,e,"image",i);t.url=n,gh.set(t,n),/^(data|blob):/i.test(n)||vh.set(t,e)}))}static async resolveExternalGeometries(t,e){await _h.inlineGeometryEntries(t,e)}parse(t,e=""){return this.parseDocument(t,e).root}parseDocument(t,e){const{strict:i,onFormatWarning:s}=this.options,n=[],r=Xt({onWarning:(t,e)=>{const r=e?`${t} (at ${e})`:t;i&&n.push(r),s?s(t,e):i||console.warn(`[quarks] ${r}`)}},()=>this.readDocument(t,e));if(n.length>0){_h.disposeEffect(r.root);const t=n.length>1?` (and ${n.length-1} more)`:"";throw new Qt(`${n[0]}${t}`,n)}return r}readDocument(t,e){if(!hh(i=t)||!hh(i.object))throw new Qt('[QuarksLoader] Not an effect document: it has no "object" to load.');var i;const s=t,n=s.metadata?.quarksFormat;"number"==typeof n&&n>2&&te(`This effect was written in format ${n}, newer than the 2 this version of babylon.quarks reads; settings it does not know are left out.`);const r={ownedMaterials:[],images:{},imageSources:{},textures:{},geometries:{},materials:{},format:"number"==typeof n?n:0},{geometries:o,images:a,textures:h,materials:l}=s;o&&Zt("geometries",()=>this.parseGeometries(lh(o),r)),a&&Zt("images",()=>this.parseImages(lh(a),e,r)),h&&Zt("textures",()=>this.parseTextures(lh(h),r)),l&&Zt("materials",()=>this.parseMaterials(lh(l),r));const c=Zt("object",()=>this.parseObject(s.object,r));this.linkReferences(c);const u=[...new Set(Object.values(r.textures).filter(t=>null!==t))];return oo(c,u,r.ownedMaterials),{root:c,textures:u}}parseGeometries(t,e){for(const i of t)if("PlaneGeometry"===i.type){const t=(i.width||1)/2,s=(i.height||1)/2;e.geometries[i.uuid]={positions:new Float32Array([-t,-s,0,t,-s,0,t,s,0,-t,s,0]),indices:new Uint32Array([0,1,2,0,2,3]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),normals:new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1])}}else if("SphereGeometry"===i.type)e.geometries[i.uuid]=this.parseSphereGeometry(i);else if("BufferGeometry"===i.type&&i.data){const t=this.parseBufferGeometry(i.data);e.geometries[i.uuid]=t}else"QuarksGeometry"===i.type&&("string"!=typeof i.url||i.positions||te(`Geometry "${i.url}" is an external file; use load(), loadFromJSON(), or resolveResources() before parse().`),e.geometries[i.uuid]=this.share({positions:new Float32Array(i.positions??[]),indices:i.indices?new Uint32Array(i.indices):new Uint32Array(0),uvs:i.uvs?new Float32Array(i.uvs):void 0,uvs2:i.uvs2?new Float32Array(i.uvs2):void 0,normals:i.normals?new Float32Array(i.normals):void 0}))}share(t){if(!1===this.options.shareResources)return t;const e=yh(mh,this.scene),i=function(t){let e=2166136261,i=2654435769;const s=[t.positions,t.indices,t.uvs,t.uvs2,t.normals];let n="";for(const t of s){if(void 0===t){n+="-,";continue}const s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n+=s.length+",";for(let t=0;t<s.length;t++)e=Math.imul(e^s[t],16777619),i=Math.imul(i^s[t],1540483477)^i>>>15}return`${n}${(e>>>0).toString(16)}${(i>>>0).toString(16)}`}(t),s=e.get(i);return void 0!==s?s:(e.set(i,t),t)}static clearSharedResources(t){fh.delete(t),mh.delete(t),ph.delete(t)}static joinUrl(t,e){return/^(data|blob):/i.test(e)||/^[a-z][a-z0-9+.-]*:\/\//i.test(e)||e.startsWith("/")?e:t+e}parseSphereGeometry(t){const e=t.radius??.5,i=Math.max(3,Math.floor(t.widthSegments??16)),s=Math.max(2,Math.floor(t.heightSegments??8)),n=t.phiStart??0,r=t.phiLength??2*Math.PI,o=t.thetaStart??0,a=t.thetaLength??Math.PI,h=[],l=[],c=[],u=[],d=[];let f=0;for(let t=0;t<=s;t++){const u=[],m=t/s,p=o+m*a;for(let t=0;t<=i;t++){const s=t/i,o=n+s*r,a=-e*Math.cos(o)*Math.sin(p),d=e*Math.cos(p),y=e*Math.sin(o)*Math.sin(p);h.push(a,d,y);const g=Math.hypot(a,d,y)||1;l.push(a/g,d/g,y/g),c.push(s,1-m),u.push(f++)}d.push(u)}const m=o<=0,p=o+a>=Math.PI;for(let t=0;t<s;t++)for(let e=0;e<i;e++){const i=d[t][e+1],n=d[t][e],r=d[t+1][e],o=d[t+1][e+1];0===t&&m||u.push(i,n,o),t===s-1&&p||u.push(n,r,o)}const y=h.length/3>65535?new Uint32Array(u):new Uint16Array(u);return{positions:new Float32Array(h),indices:y,uvs:new Float32Array(c),normals:new Float32Array(l)}}parseBufferGeometry(t){let e,i,s,n=new Float32Array(0),r=new Uint32Array(0);const o=t.attributes?.uv1??t.attributes?.uv2;if(t.interleavedBuffers&&t.arrayBuffers){const r={};for(const[e,i]of Object.entries(t.interleavedBuffers)){const s=t.arrayBuffers[i.buffer];if(s){const t=new Float32Array(Array.isArray(s)?this.int32ArrayToFloat32(s):s);r[e]={data:t,stride:i.stride}}}const a=t=>{const e=t?.isInterleavedBufferAttribute&&void 0!==t.data?r[t.data]:void 0;return e?this.extractInterleavedAttribute(e.data,e.stride,t?.offset,t?.itemSize):void 0};n=a(t.attributes?.position)??n,e=a(t.attributes?.uv),i=a(o),s=a(t.attributes?.normal)}else t.attributes&&(t.attributes.position?.array&&(n=new Float32Array(t.attributes.position.array)),t.attributes.uv?.array&&(e=new Float32Array(t.attributes.uv.array)),o?.array&&(i=new Float32Array(o.array)),t.attributes.normal?.array&&(s=new Float32Array(t.attributes.normal.array)));return t.index&&(r="Uint16Array"===t.index.type?new Uint16Array(t.index.array):new Uint32Array(t.index.array)),r=Cs(n,r),{positions:n,indices:r,uvs:e,uvs2:i,normals:s}}extractInterleavedAttribute(t,e,i=0,s=0){const n=Math.floor(t.length/e),r=new Float32Array(n*s);for(let o=0;o<n;o++)for(let n=0;n<s;n++)r[o*s+n]=t[o*e+i+n];return r}int32ArrayToFloat32(t){const e=new ArrayBuffer(4*t.length),i=new Int32Array(e);for(let e=0;e<t.length;e++)i[e]=t[e];return new Float32Array(e)}async resolveResourceUrl(t,e,i){return _h.resolveWith(this.options.resolver,t,e,i)}async fetchEffectDocument(t,e){const i=this.options.baseUrl||t.substring(0,t.lastIndexOf("/")+1),s=await this.resolveResourceUrl(t,"effect",i);return{json:await _h.fetchJsonWith(this.options.resolver,s,void 0,e),baseUrl:i}}async loadDocuments(t,e){if(0===t.length)return[];Mh(this.scene,e.signal);const i=new AbortController,s=()=>i.abort(bh(e.signal));e.signal?.addEventListener("abort",s,{once:!0});try{return await this.loadResolvedDocuments(t,e,i)}finally{e.signal?.removeEventListener("abort",s)}}async loadResolvedDocuments(t,e,i){const s=t.length,n=i.signal,r=new Array(s).fill(null),o=new Array(s).fill(!1);let a=0;const h=(t,i)=>{o[t]||n.aborted||(o[t]=!0,r[t]=i,a++,e.onProgress?.(a,s))};await zh(Promise.all(t.map(async(i,n)=>{if(i)try{await this.resolveResources(i.json,i.baseUrl)}catch(i){if(!e.continueOnError)throw i;console.warn(`[QuarksLoader] Failed to resolve resources for effect ${n+1}/${s}:`,i),t[n]=null,h(n,null)}})),this.scene,n);const l=[],c=[];try{for(let i=0;i<s;i++){if(o[i])continue;const r=t[i];if(!r){h(i,null);continue}let a;try{a=this.parseDocument(r.json,"")}catch(t){if(!e.continueOnError)throw t;console.warn(`[QuarksLoader] Failed to parse effect ${i+1}/${s}:`,t),h(i,null);continue}l.push(a),c.push(this.finishLoad(a,n).then(()=>h(i,a.root)))}await Promise.all(c)}catch(t){throw n.aborted||i.abort(t),Promise.allSettled(c),this.scene.isDisposed||l.forEach(t=>ho(t.root)),t}return r}static async mapPool(t,e,i){if(0===t.length)return[];const s=void 0!==e&&e>0?e:t.length,n=new Array(t.length);let r=0;const o=Math.min(s,t.length);return await Promise.all(Array.from({length:o},()=>(async()=>{for(;r<t.length;){const e=r++;n[e]=await i(t[e],e)}})())),n}static async resolveWith(t,e,i,s){return t?.resolve?t.resolve(e,i,s):_h.joinUrl(s,e)}static fetchJsonWith(t,e,i,s){const n=async()=>{if(t?.fetchJson)return s?t.fetchJson(e,{signal:s}):t.fetchJson(e);const i=await(s?fetch(e,{signal:s}):fetch(e));if(!i.ok)throw new Error(`HTTP ${i.status}`);return i.json()};if(!i)return n();const r=yh(ph,i),o=`json|${e}`;let a=r.get(o);return void 0===a&&(a=n().catch(t=>{throw r.get(o)===a&&r.delete(o),t}),r.set(o,a)),a}static async inlineGeometryEntries(t,e,i=_h.warnResourceError){await Promise.all(ch(t,"geometries").map(async t=>{if(!hh(t)||"string"!=typeof t.url||t.positions)return;const s=t.url;try{const i=await e(s);for(const e of["positions","indices","uvs","uvs2","normals"]){const s=hh(i)?i[e]:void 0;void 0!==s&&(t[e]=Array.isArray(s)?s.slice():s)}delete t.url}catch(t){i("geometry",s,t)}}))}static warnResourceError(t,e,i){console.warn(`[QuarksLoader] Could not load ${t} "${e}":`,i)}reportResourceError(t,e,i){(this.options.onResourceError??_h.warnResourceError)(t,e,i)}parseImages(t,e,i){for(const[s,n]of t.entries()){const t=n.url;t&&Zt(`[${s}]`,()=>_h.warnIfNotAnImageUrl(t)),i.images[n.uuid]=t?_h.joinUrl(e,t):null;const r=vh.get(n)??t;r&&!/^(data|blob):/i.test(r)&&(i.imageSources[n.uuid]=r)}}static warnIfNotAnImageUrl(t){/^(data|blob):/i.test(t)||/\.(png|jpe?g|webp|gif|bmp|ktx2?|dds|env|basis)(\?|#|$)/i.test(t)||te(`Image "${t}" does not look like an image; its texture will fail to load. This usually means the effect was exported without embedding that texture.`)}parseTextures(t,e){for(const i of t){const t=void 0!==i.image?e.images[i.image]:void 0;if(t){const s=void 0===i.invertY||!!i.invertY,n=!!i.noMipmap,r=!1!==this.options.shareResources,o=r?[s,n,i.samplingMode,i.wrap,i.repeat,i.offset,i.rotation].join("|")+"|"+t:"",a=r?yh(fh,this.scene):void 0,h=a?.get(o);if(void 0!==h){e.textures[i.uuid]=h;continue}let l;const c=new Promise(t=>l=t);let u,d=!1;const f={noMipmap:n,invertY:s,samplingMode:"number"==typeof i.samplingMode?i.samplingMode:void 0,onLoad:()=>l(),onError:(e,i)=>{d=!0,void 0!==a&&a.get(o)===u&&a.delete(o),this.reportResourceError("image",t,i??e),l()}};try{u=new A(t,this.scene,f)}catch{e.textures[i.uuid]=null;continue}Sh.set(u,c);const m=void 0!==i.image?e.imageSources[i.image]:void 0;void 0!==m&&Xa(u,m,t),u.onDisposeObservable.addOnce(()=>l()),Array.isArray(i.wrap)&&(u.wrapU=this.mapWrapMode(i.wrap[0]),u.wrapV=this.mapWrapMode(i.wrap[1]??i.wrap[0])),Array.isArray(i.repeat)&&(u.uScale=i.repeat[0]??1,u.vScale=i.repeat[1]??1),Array.isArray(i.offset)&&(u.uOffset=i.offset[0]??0,u.vOffset=i.offset[1]??0),"number"==typeof i.rotation&&(u.wAng=i.rotation),void 0===a||d||(a.set(o,u),u.onDisposeObservable.addOnce(()=>{a.get(o)===u&&a.delete(o)})),e.textures[i.uuid]=u}else e.textures[i.uuid]=null}}mapWrapMode(t){switch(t){case 1001:return A.CLAMP_ADDRESSMODE;case 1002:return A.MIRROR_ADDRESSMODE;default:return A.WRAP_ADDRESSMODE}}parseMaterials(t,e){const i=t=>"string"==typeof t&&e.textures[t]||null;for(const s of t){const t={uuid:s.uuid,transparent:s.transparent??!0,blending:s.blending??1,side:s.side??2,depthTest:s.depthTest??!0,depthWrite:s.depthWrite??!1,alphaTest:s.alphaTest??0,texture:null},n=s.map??s.texture;n&&(t.texture=i(n));const o=s.reflectionAtlas;if(o&&(t.reflectionAtlas=i(o)),"number"==typeof s.reflectionLevel&&(t.reflectionLevel=s.reflectionLevel),"unlit"!==s.lighting&&"fixed"!==s.lighting&&"scene"!==s.lighting||(t.lighting=s.lighting),s.rim&&"object"==typeof s.rim&&(t.rim=s.rim),s.mapUV&&"object"==typeof s.mapUV&&(t.mapUV=s.mapUV),s.gradientMap&&"object"==typeof s.gradientMap&&(t.gradientMap={...s.gradientMap,ramp:i(s.gradientMap.ramp)}),s.erosion&&"object"==typeof s.erosion&&(t.erosion={...s.erosion,mask:i(s.erosion.mask)}),s.uvDistortion&&"object"==typeof s.uvDistortion&&(t.uvDistortion={...s.uvDistortion,map:i(s.uvDistortion.map)}),"number"==typeof s.alphaMode)t.alphaMode=s.alphaMode;else{const e={1:r.ALPHA_COMBINE,2:r.ALPHA_ADD,3:r.ALPHA_SUBTRACT,4:r.ALPHA_MULTIPLY};t.alphaMode=e[s.blending??1]||r.ALPHA_COMBINE}e.materials[s.uuid]=t}}getGeometry(t,e){if(e)return t.geometries[e]}getMaterial(t,e){if(!e)return;const i=Array.isArray(e)?e[0]:e;return t.materials[i]}createPlaceholderNode(t,e){const i=new n(e||t||"node",this.scene);return Object.assign(i,{quarksOriginalType:t}),i}createMeshNode(t,e){const i=new p(t.name||t.type||"mesh",this.scene),s=this.getGeometry(e,t.geometry);if(s&&s.positions.length>0&&s.indices.length>0){const t=new y;t.positions=s.positions,t.indices=s.indices,s.uvs&&s.uvs.length>0&&(t.uvs=s.uvs),s.uvs2&&s.uvs2.length>0&&(t.uvs2=s.uvs2),s.normals&&s.normals.length>0&&(t.normals=s.normals),t.applyToMesh(i,!0)}const n=this.getMaterial(e,t.material);if(n){const t=new P(`quarks_loader_material_${n.uuid}`,this.scene);e.ownedMaterials.push(t),t.alphaMode=n.alphaMode??r.ALPHA_COMBINE,t.backFaceCulling=2!==n.side,t.alphaCutOff=n.alphaTest??0,t.disableDepthWrite=!n.depthWrite;const s=n.texture;s&&"string"!=typeof s&&(t.diffuseTexture=s,t.opacityTexture=s),i.material=t}return i}parseObject(t,e){let i;switch(t.type){case"QuarksPrefab":i=Ha.fromJSON(t,this.scene);break;case"ParticleEmitter":if(t.ps){const s=t.ps,n=Zt("ps",()=>this.parseParticleSystem(s,e));i=n.emitter;break}i=this.createPlaceholderNode(t.type,t.name);break;case"Mesh":case"SkinnedMesh":case"InstancedMesh":case"BatchedMesh":i=this.createMeshNode(t,e);break;case"Scene":case"Group":case"Object3D":case"PerspectiveCamera":case"OrthographicCamera":case"AmbientLight":case"DirectionalLight":case"PointLight":case"RectAreaLight":case"SpotLight":case"HemisphereLight":case"LightProbe":case"LOD":case"Line":case"LineSegments":case"LineLoop":case"PointCloud":case"Points":case"Sprite":case"Bone":i=this.createPlaceholderNode(t.type,t.name);break;default:i=new n(t.name||t.type||"node",this.scene)}if(t.uuid&&function(t,e){Is.set(t,e)}(i,t.uuid),t.name&&(i.name=t.name),t.matrix){const e=h.FromArray(t.matrix),s=new a(1,1,1),n=u.Identity(),r=new a(0,0,0);e.decompose(s,n,r),i.position.copyFrom(r),i.scaling.copyFrom(s),i.rotationQuaternion=n}else t.position&&i.position.set(t.position[0],t.position[1],t.position[2]),t.scale&&i.scaling.set(t.scale[0],t.scale[1],t.scale[2]),t.quaternion?i.rotationQuaternion=new u(t.quaternion[0],t.quaternion[1],t.quaternion[2],t.quaternion[3]):t.rotation&&i.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]);if(void 0!==t.visible&&i.setEnabled(t.visible),!1===t.isVisible&&i instanceof p&&(i.isVisible=!1),t.children){const s=t.children;Array.isArray(s)?s.forEach((t,s)=>{const n=Zt(`children[${s}]`,()=>hh(t)?this.parseObject(t,e):te("A child is not an object; it is skipped."));n&&(n.parent=i)}):Zt("children",()=>te('"children" is not a list; the node loads without them.'))}return i}parseParticleSystem(t,e){e.format<2&&null!==t&&"object"==typeof t&&"hierarchy"!==t.scalingMode&&(t={...t,scalingMode:"hierarchy"});const i=Wa.fromJSON(t,e,{},this.scene);return"mesh_surface"===t?.shape?.type&&"string"==typeof t.shape.mesh&&uh.set(i,t.shape.mesh),dh.set(i,Kt()),i}linkReferences(t){const e={},i=t=>{const s=Fs(t);s&&(e[s]=t);for(const e of t.getChildren())e instanceof n&&i(e)};i(t);const s=i=>{if(i instanceof Ha&&i.resolveReferences(t),i instanceof yo){const t=i.system,s=dh.get(t),n=t=>s?Zt(s,()=>te(t)):te(t),r=uh.get(t),o=t.emitterShape;if(r&&o instanceof Bs){const t=e[r];t instanceof p?o.mesh=t:n(`Emitter "${i.name}" has a mesh surface shape on "${r}", `+(t?"which is not a mesh":"which is not in the effect")+"; it emits nothing until a mesh is set.")}for(let s=0;s<t.behaviors.length;s++)if(t.behaviors[s]instanceof ci){const r=t.behaviors[s],o=r.subParticleSystem;if("string"!=typeof o)continue;const a=e[o];a instanceof yo?(r.subParticleSystem=a,a.system.onlyUsedByOther=!0):(r.subParticleSystem=void 0,""!==o&&n(`Emitter "${i.name}" has a sub emitter targeting "${o}", `+(a?"which is not a particle emitter":"which is not in the effect")+"; that sub emitter is skipped."))}}for(const t of i.getChildren())t instanceof n&&s(t)};s(t)}}const Ah={};const Ph={name:""},Oh=[{name:"billboard",settings:{renderMode:Rs.BillBoard}},{name:"vertical billboard",settings:{renderMode:Rs.VerticalBillBoard}},{name:"horizontal billboard",settings:{renderMode:Rs.HorizontalBillBoard}},{name:"stretched",settings:{renderMode:Rs.StretchedBillBoard}},{name:"beam",settings:{renderMode:Rs.Beam}},{name:"mesh",settings:{renderMode:Rs.Mesh}},{name:"mesh scene lit",settings:{renderMode:Rs.Mesh,lighting:"scene"}},{name:"mesh unlit",settings:{renderMode:Rs.Mesh,lighting:"unlit"}},{name:"mesh rim",settings:{renderMode:Rs.Mesh,rim:Ds({mode:"add"})}},{name:"mesh unlit rim mix",settings:{renderMode:Rs.Mesh,lighting:"unlit",rim:Ds({mode:"mix"})}},{name:"mesh unlit rim fade",settings:{renderMode:Rs.Mesh,lighting:"unlit",rim:Ds({mode:"fade"})}},{name:"mesh reflecting",settings:{renderMode:Rs.Mesh,reflectionAtlas:Ah},context:{envAtlasReady:!0}},{name:"mesh unlit reflecting rim fade",settings:{renderMode:Rs.Mesh,lighting:"unlit",reflectionAtlas:Ah,rim:Ds({mode:"fade"})},context:{envAtlasReady:!0}},{name:"trail",settings:{renderMode:Rs.Trail}}],Th=[Ph,{name:"pivot",settings:{pivot:new ht(.5,0,0)}},{name:"size limits",settings:{minParticleSize:.01}},{name:"pivot size limits",settings:{pivot:new ht(0,.5,.5),maxParticleSize:.5}}],Vh=[Ph,{name:"sheet",settings:{uTileCount:4,vTileCount:2}},{name:"sheet blend",settings:{uTileCount:4,vTileCount:2,blendTiles:!0}}],Eh=[Ph,{name:"map",settings:{texture:Ah}}],$h=[Ph,{name:"soft",settings:{softParticles:!0},context:{depth:{packed:!1}}},{name:"soft packed",settings:{softParticles:!0},context:{depth:{packed:!0}}}],Ch=[Ph,{name:"alpha test",settings:{materialAlphaTest:.5}}],Ih=[Ph,{name:"fog",settings:{applyFog:!0}},{name:"fog additive",settings:{applyFog:!0,materialBlendMode:r.ALPHA_ADD}}],Nh=[{name:"premultiplied",settings:{materialBlendMode:r.ALPHA_PREMULTIPLIED}},{name:"premultiplied fog",settings:{materialBlendMode:r.ALPHA_PREMULTIPLIED,applyFog:!0}},{name:"one-one",settings:{materialBlendMode:r.ALPHA_ONEONE}},{name:"one-one fog",settings:{materialBlendMode:r.ALPHA_ONEONE,applyFog:!0}},{name:"multiply",settings:{materialBlendMode:r.ALPHA_MULTIPLY}},{name:"multiply fog",settings:{materialBlendMode:r.ALPHA_MULTIPLY,applyFog:!0}},{name:"multiply fog alpha test",settings:{materialBlendMode:r.ALPHA_MULTIPLY,applyFog:!0,materialAlphaTest:.5}},{name:"opaque",settings:{materialTransparent:!1}}],Fh=(()=>{const t=sn({tiling:[2,2]}),e=sn({channel:1,tiling:[2,2]}),i=tn({map:Ah}),s=tn({map:Ah,mapUV:{channel:1}}),n=js({ramp:Ah}),r=Ys({}),o=Ys({mask:Ah}),a=Ys({mask:Ah,maskUV:{channel:1}});return[{name:"map transform",settings:{mapUV:t}},{name:"map transform uv1",settings:{mapUV:e}},{name:"gradient map",settings:{gradientMap:n}},{name:"erosion",settings:{erosion:r}},{name:"erosion mask",settings:{erosion:o}},{name:"erosion mask uv1",settings:{erosion:a}},{name:"distortion",settings:{uvDistortion:i}},{name:"distortion uv1",settings:{uvDistortion:s}},{name:"map transform distortion gradient erosion mask",settings:{mapUV:t,uvDistortion:i,gradientMap:n,erosion:o}},{name:"map transform uv1 distortion gradient erosion",settings:{mapUV:e,uvDistortion:i,gradientMap:n,erosion:r}},{name:"every effect on uv1",settings:{mapUV:e,uvDistortion:s,gradientMap:n,erosion:a}}]})(),Bh=["billboard","stretched","beam","mesh","mesh unlit","mesh unlit rim mix","mesh reflecting","trail"];function Uh(t){return{IMAGEPROCESSING:!1,WHITEBALANCE:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,EXPOSURE:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,SKIPFINALCOLORCLAMP:!1,...t}}const Rh=[{name:"post-processed",context:{imageProcessing:Uh({IMAGEPROCESSINGPOSTPROCESS:!0})}},{name:"tone mapped",context:{imageProcessing:Uh({IMAGEPROCESSING:!0,TONEMAPPING:1})}},{name:"aces exposure contrast",context:{imageProcessing:Uh({IMAGEPROCESSING:!0,TONEMAPPING:2,EXPOSURE:!0,CONTRAST:!0})}},{name:"neutral vignette dither",context:{imageProcessing:Uh({IMAGEPROCESSING:!0,TONEMAPPING:3,VIGNETTE:!0,VIGNETTEBLENDMODEMULTIPLY:!0,DITHER:!0})}},{name:"opaque vignette curves white balance grading",context:{imageProcessing:Uh({IMAGEPROCESSING:!0,VIGNETTE:!0,VIGNETTEBLENDMODEOPAQUE:!0,COLORCURVES:!0,WHITEBALANCE:!0,COLORGRADING:!0,SKIPFINALCOLORCLAMP:!0})}},{name:"grading 3d green depth bgr",context:{imageProcessing:Uh({IMAGEPROCESSING:!0,COLORGRADING:!0,COLORGRADING3D:!0,SAMPLER3DGREENDEPTH:!0,SAMPLER3DBGRMAP:!0})}}],Lh=[Ph,{name:"premultiplied",settings:{materialBlendMode:r.ALPHA_PREMULTIPLIED}},{name:"additive fog",settings:{materialBlendMode:r.ALPHA_ADD,applyFog:!0}},{name:"multiply",settings:{materialBlendMode:r.ALPHA_MULTIPLY}}],Dh={name:"uv2",context:{meshUV2:!0}},kh={name:"soft packed alpha test fog one-one",settings:{softParticles:!0,materialAlphaTest:.5,applyFog:!0,materialBlendMode:r.ALPHA_ONEONE},context:{depth:{packed:!0}}};function qh(){const t=new Set,e=[],i=i=>{const s={renderMode:n=Rs.BillBoard,texture:null,reflectionAtlas:null,uTileCount:1,vTileCount:1,blendTiles:!1,softParticles:!1,materialAlphaTest:0,materialTransparent:!0,materialBlendMode:r.ALPHA_COMBINE,applyFog:!1,applyImageProcessing:!0,pivot:void 0,minParticleSize:0,maxParticleSize:1/0,lighting:n===Rs.Mesh?"fixed":void 0,rim:void 0,mapUV:void 0,uvDistortion:void 0,gradientMap:void 0,erosion:void 0};var n;const o={depth:null,envAtlasReady:!1,meshUV2:!1,imageProcessing:null};for(const t of i)Object.assign(s,t.settings),Object.assign(o,t.context);const a=Nr(s,o),h=a.name+" "+a.defines.join(",");if(t.has(h))return;t.add(h);const l=i.map(t=>t.name).filter(t=>""!==t);e.push({name:`${l.join(", ")} [${a.defines.join(",")||"none"}]`,program:a})};for(const t of Oh)for(const e of Th)for(const s of Vh)for(const n of Eh)for(const r of $h)for(const o of Ch)for(const a of Ih)i([t,e,s,n,r,o,a]);for(const t of Oh)for(const e of Nh)for(const s of $h.slice(0,2))for(const n of Eh)i([t,e,s,n]);for(const t of Oh.filter(t=>Bh.includes(t.name)))for(const e of t.settings?.renderMode===Rs.Mesh?[Ph,Dh]:[Ph])for(const s of Fh)for(const n of Eh)for(const r of[Ph,Vh[2]])for(const o of[Ph,kh])i([t,e,s,n,r,o]);for(const t of Oh)for(const e of Rh)for(const s of Lh)for(const n of Eh)i([t,e,s,n]);const s=Fh[Fh.length-3];for(const t of Oh.filter(t=>Bh.includes(t.name)))for(const e of Rh)i([t,e,s,Eh[Eh.length-1],kh]);return e}Es(Us);export{Lt as ApplyCollision,Ue as ApplyForce,De as ApplySequences,me as AxisAngleGenerator,so as BatchedRenderer,Qi as BehaviorFromJSON,Hi as BehaviorToJSON,ji as BehaviorTypes,ae as Bezier,us as BoxEmitFrom,fs as BoxEmitter,ke as ChangeEmitDirection,ps as CircleEmitter,Je as ColorBySpeed,Me as ColorGeneratorFromJSON,Ge as ColorOverLife,pe as ColorRange,gs as ConeEmitFrom,xs as ConeEmitter,we as ConstantColor,re as ConstantValue,ye as ContinuousLinearFunction,F as DEG2RAD,Ss as DonutEmitter,Hs as EROSION_DEFAULT_SOFTNESS,bs as EdgeEmitter,vo as EffectPool,ci as EmitSubParticleSystem,Be as EmitterFrame,Os as EmitterFromJSON,ds as EmitterMode,Ps as EmitterShapes,Ts as EmitterToJSON,Mt as Euler,ze as EulerGenerator,ui as ForceOverLife,di as FrameOverLife,Ws as GRADIENT_MAP_WEIGHTS,Te as GeneratorFromJSON,ve as Gradient,fi as GravityForce,ws as GridEmitter,vs as GridSampling,Ms as HemisphereEmitter,mi as InheritVelocity,oe as IntervalValue,pi as LimitSpeedOverLife,Wr as MAX_TRAIL_TESSELLATION,ot as MathUtils,zt as Matrix3,ft as Matrix4,Bs as MeshSurfaceEmitter,Us as MeshSurfaceEmitterPlugin,He as NodeParticle,Ei as Noise,$i as OrbitOverLife,yo as ParticleEmitter,We as ParticleStore,Wa as ParticleSystem,le as PiecewiseBezier,he as PiecewiseFunction,Vs as Plugins,zs as PointEmitter,Ka as QUARKS_FORMAT_VERSION,Qt as QuarksFormatError,_h as QuarksLoader,Ha as QuarksPrefab,go as QuarksUtil,at as Quaternion,Pt as QuaternionView,B as RAD2DEG,ce as RandomBetweenCurves,xe as RandomColor,be as RandomColorBetweenGradient,_e as RandomQuatGenerator,Ze as RecordState,As as RectangleEmitter,Rs as RenderMode,Ii as Rotation3DOverLife,Ni as RotationBySpeed,Ae as RotationGeneratorFromJSON,Fi as RotationOverLife,Le as SequencerFromJSON,cs as ShapeTransform,Bi as SizeBySpeed,Ui as SizeOverLife,Ri as SpeedOverLife,_s as SphereEmitter,Ye as SpriteParticle,hi as SubEmitterInheritMask,ai as SubParticleEmitMode,Re as TextureSequencer,Ke as TrailParticle,Di as TurbulenceField,Ks as UV_DISTORTION_DEFAULT_STRENGTH,Zs as UV_DISTORTION_DEFAULT_UV,qr as VFXBatch,de as ValueGeneratorFromJSON,Tt as Vector2,ht as Vector3,Pe as Vector3Function,Oe as Vector3GeneratorFromJSON,Et as Vector3View,Ct as Vector4,Nt as Vector4View,Gi as VelocityOverLife,ut as WebGLCoordinateSystem,dt as WebGPUCoordinateSystem,Wi as WidthOverLength,Ir as blendCategory,Oo as cacheEnvAtlas,et as ceilPowerOfTwo,R as clamp,Eo as createEnvAtlasFromFaceUrls,$ as createSeededRandom,_o as cubeFaceUrls,Kt as currentFormatPath,J as damp,Cn as decodeSoftDepth,Ls as defaultMeshLighting,Z as degToRad,nt as denormalize,To as disposeEnvAtlas,Co as ensureEnvAtlasFromCube,Xs as erosionEqual,L as euclideanModulo,it as floorPowerOfTwo,U as generateUUID,Po as getCachedEnvAtlas,Rt as getPhysicsResolver,V as getRandomSource,ms as getValueFromEmitterMode,Qs as gradientMapEqual,k as inverseLerp,tt as isPowerOfTwo,q as lerp,Es as loadPlugin,D as mapLinear,nn as mapUVEqual,ks as meshRimEqual,rt as normalize,Ys as normalizeErosion,js as normalizeGradientMap,sn as normalizeMapUV,Ds as normalizeMeshRim,qs as normalizeTextureUV,tn as normalizeUVDistortion,G as pingpong,ls as planBehaviorFusion,Ns as quarksNodeId,K as radToDeg,H as randFloat,Y as randFloatSpread,Q as randInt,T as random,Ne as readBehaviorSpace,Xt as readFormat,Zt as readFormatPart,rn as readsUV1,X as seededRandom,ah as serializeEffect,Ut as setPhysicsResolver,st as setQuaternionFromProperEuler,E as setRandomSource,Nr as shaderProgram,qh as shaderVariants,j as smootherstep,W as smoothstep,$n as softDepthParams,qe as speedFraction,li as subEmitterInheritMask,Za as textureSourceUrl,Js as textureUVEqual,Gs as textureUVToJSON,Qr as trailCurveTension,Kr as trailLifetime,Zr as trailMinVertexDistance,jr as trailTessellation,Yr as trailTextureMode,Xr as trailTextureScale,$s as unloadPlugin,en as uvDistortionEqual,te as warnFormat,C as withRandomSource};
2
2
  //# sourceMappingURL=babylon.quarks.esm.js.map