@votax572002/fluxfx 0.1.1 → 0.1.4

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.
package/dist/react.js CHANGED
@@ -1,14 +1,14 @@
1
1
  'use client';
2
- "use client";import w,{useEffect as he,useRef as O}from"react";var V=class{constructor(){this.listeners=new Set;this.rafId=null;this.startTime=0;this.lastTime=0;this.isDocumentHidden=!1;this.handleVisibilityChange=()=>{this.isDocumentHidden=document.hidden,this.isDocumentHidden?this.stopLoop():this.listeners.size>0&&(this.lastTime=0,this.startLoop())};this.tick=e=>{if(this.listeners.size===0||this.isDocumentHidden){this.stopLoop();return}this.startTime===0&&(this.startTime=e);let i=this.lastTime===0?16.67:Math.min(e-this.lastTime,100);this.lastTime=e;let t=(e-this.startTime)*.001,r=i*.001;this.listeners.forEach(s=>{s(t,r,e)}),this.rafId=window.requestAnimationFrame(this.tick)};typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}startLoop(){this.rafId!==null||typeof window>"u"||this.isDocumentHidden||(this.lastTime=0,this.rafId=window.requestAnimationFrame(this.tick))}stopLoop(){this.rafId!==null&&typeof window<"u"&&(window.cancelAnimationFrame(this.rafId),this.rafId=null)}add(e){return this.listeners.add(e),this.listeners.size===1&&this.startLoop(),()=>this.remove(e)}remove(e){this.listeners.delete(e),this.listeners.size===0&&this.stopLoop()}get activeCount(){return this.listeners.size}get isRunning(){return this.rafId!==null}},B=new V;var g=class{static acquireVec2(e=0,i=0){let t=this.vec2Pool.pop()??new Float32Array(2);return t[0]=e,t[1]=i,t}static releaseVec2(e){this.vec2Pool.length<128&&this.vec2Pool.push(e)}static acquireVec3(e=0,i=0,t=0){let r=this.vec3Pool.pop()??new Float32Array(3);return r[0]=e,r[1]=i,r[2]=t,r}static releaseVec3(e){this.vec3Pool.length<128&&this.vec3Pool.push(e)}static acquireVec4(e=0,i=0,t=0,r=1){let s=this.vec4Pool.pop()??new Float32Array(4);return s[0]=e,s[1]=i,s[2]=t,s[3]=r,s}static releaseVec4(e){this.vec4Pool.length<128&&this.vec4Pool.push(e)}static hexToVec3Into(e,i){let t=e.charCodeAt(0)===35?e.slice(1):e;if(t.length===3){let s=parseInt(t[0],16),a=parseInt(t[1],16),n=parseInt(t[2],16);return i[0]=(s<<4|s)/255,i[1]=(a<<4|a)/255,i[2]=(n<<4|n)/255,i}let r=parseInt(t,16);return Number.isNaN(r)?(i[0]=1,i[1]=1,i[2]=1,i):(i[0]=(r>>16&255)/255,i[1]=(r>>8&255)/255,i[2]=(r&255)/255,i)}};g.vec2Pool=[],g.vec3Pool=[],g.vec4Pool=[],g.scratchVec2=new Float32Array(2),g.scratchVec3=new Float32Array(3),g.scratchVec4=new Float32Array(4);var D=class{constructor(e){this.samples=new Float32Array(30);this.sampleIdx=0;this.sampleCount=0;this.stableUpWindows=0;this.lastAdjustAt=0;this.minScale=Math.max(.5,e.minScale),this.maxScale=Math.max(this.minScale,e.maxScale),this.currentScale=this.maxScale,this.downThresholdMs=e.downThresholdMs??20.5,this.upThresholdMs=e.upThresholdMs??17.2,this.cooldownMs=e.cooldownMs??750}get scale(){return this.currentScale}setBounds(e,i){let t=Math.max(.5,e),r=Math.max(t,i),s=this.currentScale;return this.minScale=t,this.maxScale=r,this.currentScale=Math.min(r,Math.max(t,this.currentScale)),r>s&&(this.currentScale=r),this.sampleCount=0,this.sampleIdx=0,this.stableUpWindows=0,Math.abs(this.currentScale-s)>.01}recordFrame(e,i){if(this.minScale>=this.maxScale||e<=0||e>60)return!1;if(this.samples[this.sampleIdx]=e,this.sampleIdx=(this.sampleIdx+1)%this.samples.length,this.sampleCount<this.samples.length)return this.sampleCount++,!1;if(i-this.lastAdjustAt<this.cooldownMs)return!1;let t=0;for(let s=0;s<this.samples.length;s++)t+=this.samples[s];let r=t/this.samples.length;if(r>this.downThresholdMs&&this.currentScale>this.minScale)return this.currentScale=Math.max(this.minScale,Number((this.currentScale-.15).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=i,!0;if(r<this.upThresholdMs&&this.currentScale<this.maxScale){if(this.stableUpWindows++,this.stableUpWindows>=2)return this.currentScale=Math.min(this.maxScale,Number((this.currentScale+.1).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=i,!0}else this.stableUpWindows=0;return!1}};var T=null;function c(o,e="#ffffff"){if(typeof o!="string")return e;let i=o.trim();if(!i)return e;if(typeof document<"u"){if(!T){let t=document.createElement("canvas");t.width=1,t.height=1,T=t.getContext("2d")}if(T){T.fillStyle="#010203",T.fillStyle=i;let t=T.fillStyle;if(/^#[0-9a-f]{6}$/i.test(t))return t;let r=t.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);if(r)return"#"+[Number(r[1]),Number(r[2]),Number(r[3])].map(s=>Math.max(0,Math.min(255,s)).toString(16).padStart(2,"0")).join("")}}return e}var P=`#version 300 es
2
+ "use client";import V,{useEffect as Ae,useRef as ee}from"react";var fe=["normal","reduced-res","low-fps","survival"];var q=class{constructor(e){this.idx=0;this.count=0;this.lastSampleAt=0;this.samples=new Float32Array(e)}push(e,t){this.samples[this.idx]=e,this.idx=(this.idx+1)%this.samples.length,this.count<this.samples.length&&this.count++,this.lastSampleAt=t}reset(){this.idx=0,this.count=0,this.lastSampleAt=0}isReady(e,t){return this.count>=this.samples.length&&e-this.lastSampleAt<=t}compute(){if(this.count===0)return{avgMs:0,slowRatio:0};let e=0,t=0;for(let i=0;i<this.count;i++){let r=this.samples[i];e+=r,r>26&&t++}return{avgMs:e/this.count,slowRatio:t/this.count}}},te=class{constructor(){this.mainChannel=new q(30);this.gpuChannel=new q(12);this.listeners=new Set;this.currentTier=0;this.lastEvalAt=0;this.lastTransitionAt=0;this.badChecks=0;this.goodChecks=0;this.lastAvgFrameMs=0;this.lastSlowRatio=0;this.survivalTimer=null}recordMainThread(e,t){e<=0||e>250||(this.mainChannel.push(e,t),this.maybeEvaluate(t))}recordGpuFrame(e,t,i){if(e<=0||e>250||t<=0)return;let r=e*(t/60);this.gpuChannel.push(r,i),this.maybeEvaluate(i)}resetMainThread(){this.mainChannel.reset()}resetAll(){this.mainChannel.reset(),this.gpuChannel.reset(),this.badChecks=0,this.goodChecks=0,this.lastAvgFrameMs=0,this.lastSlowRatio=0}onTierChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}get tier(){return this.currentTier}get label(){return fe[this.currentTier]}getSnapshot(){return{tier:this.currentTier,label:fe[this.currentTier],avgFrameMs:Math.round(this.lastAvgFrameMs*100)/100,slowFrameRatio:Math.round(this.lastSlowRatio*1e3)/1e3}}clearSurvivalProbe(){this.survivalTimer!==null&&(clearTimeout(this.survivalTimer),this.survivalTimer=null)}scheduleSurvivalProbe(){this.clearSurvivalProbe(),typeof setTimeout=="function"&&(this.survivalTimer=setTimeout(()=>{if(this.survivalTimer=null,this.currentTier===3){if(typeof document<"u"&&document.hidden){this.scheduleSurvivalProbe();return}this.mainChannel.reset(),this.gpuChannel.reset(),this.badChecks=0,this.goodChecks=0,this.setTier(2,performance.now())}},6e3))}maybeEvaluate(e){if(e-this.lastEvalAt<400)return;this.lastEvalAt=e;let t=this.mainChannel.isReady(e,1500),i=this.gpuChannel.isReady(e,2500);if(!t&&!i)return;let r=0,s=0;if(t){let a=this.mainChannel.compute();r=Math.max(r,a.avgMs),s=Math.max(s,a.slowRatio)}if(i){let a=this.gpuChannel.compute();r=Math.max(r,a.avgMs),s=Math.max(s,a.slowRatio)}if(this.lastAvgFrameMs=r,this.lastSlowRatio=s,r>22.5||s>=.35){this.badChecks++,this.goodChecks=0,this.badChecks>=2&&this.currentTier<3&&e-this.lastTransitionAt>=2e3&&(this.setTier(this.currentTier+1,e),this.badChecks=0);return}if(r<18.2&&s<.1){this.goodChecks++,this.badChecks=0,this.currentTier>0&&this.goodChecks>=3&&e-this.lastTransitionAt>=5e3&&(this.setTier(this.currentTier-1,e),this.goodChecks=0);return}this.badChecks=0,this.goodChecks=0}setTier(e,t){if(e===this.currentTier)return;let i=this.currentTier;this.currentTier=e,this.lastTransitionAt=t,e===3?this.scheduleSurvivalProbe():this.clearSurvivalProbe(),this.listeners.forEach(r=>r(e,i))}},D=new te;var ie=class{constructor(){this.listeners=new Set;this.visibilityListeners=new Set;this.rafId=null;this.startTime=0;this.lastTime=0;this.avgFrameTimeMs=0;this.isDocumentHidden=!1;this.handleVisibilityChange=()=>{this.isDocumentHidden=typeof document<"u"?document.hidden:!1,this.isDocumentHidden?(this.stopLoop(),D.resetAll()):this.listeners.size>0&&(this.lastTime=0,this.startLoop()),this.visibilityListeners.forEach(e=>{e(this.isDocumentHidden)})};this.tick=e=>{if(this.listeners.size===0||this.isDocumentHidden){this.stopLoop();return}this.startTime===0&&(this.startTime=e);let t=this.lastTime===0?16.67:e-this.lastTime,i=Math.min(t,100);this.lastTime=e,t>0&&t<500&&(this.avgFrameTimeMs=this.avgFrameTimeMs===0?t:this.avgFrameTimeMs*.9+t*.1),D.recordMainThread(t,e);let r=(e-this.startTime)*.001,s=i*.001;this.listeners.forEach(a=>{a(r,s,e)}),this.listeners.size>0&&!this.isDocumentHidden?this.rafId=window.requestAnimationFrame(this.tick):this.rafId=null};typeof document<"u"&&(this.isDocumentHidden=document.hidden,document.addEventListener("visibilitychange",this.handleVisibilityChange))}startLoop(){this.rafId!==null||typeof window>"u"||this.isDocumentHidden||(this.lastTime=0,this.rafId=window.requestAnimationFrame(this.tick))}stopLoop(){this.rafId!==null&&typeof window<"u"&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.lastTime=0,this.avgFrameTimeMs=0,D.resetMainThread()}onVisibilityChange(e){return this.visibilityListeners.add(e),()=>{this.visibilityListeners.delete(e)}}add(e){return this.listeners.add(e),this.listeners.size===1&&this.startLoop(),()=>this.remove(e)}remove(e){this.listeners.delete(e),this.listeners.size===0&&this.stopLoop()}get isHidden(){return this.isDocumentHidden}get activeCount(){return this.listeners.size}get isRunning(){return this.rafId!==null}get frameTimeMs(){return!this.isRunning||this.avgFrameTimeMs<=0?0:Math.round(this.avgFrameTimeMs*100)/100}get fps(){return!this.isRunning||this.avgFrameTimeMs<=0?0:Math.round(1e3/this.avgFrameTimeMs)}},B=new ie;var T=class{static acquireVec2(e=0,t=0){let i=this.vec2Pool.pop()??new Float32Array(2);return i[0]=e,i[1]=t,i}static releaseVec2(e){this.vec2Pool.length<128&&this.vec2Pool.push(e)}static acquireVec3(e=0,t=0,i=0){let r=this.vec3Pool.pop()??new Float32Array(3);return r[0]=e,r[1]=t,r[2]=i,r}static releaseVec3(e){this.vec3Pool.length<128&&this.vec3Pool.push(e)}static acquireVec4(e=0,t=0,i=0,r=1){let s=this.vec4Pool.pop()??new Float32Array(4);return s[0]=e,s[1]=t,s[2]=i,s[3]=r,s}static releaseVec4(e){this.vec4Pool.length<128&&this.vec4Pool.push(e)}static hexToVec3Into(e,t){let i=e.charCodeAt(0)===35?e.slice(1):e;if(i.length===3){let s=parseInt(i[0],16),a=parseInt(i[1],16),n=parseInt(i[2],16);return t[0]=(s<<4|s)/255,t[1]=(a<<4|a)/255,t[2]=(n<<4|n)/255,t}let r=parseInt(i,16);return Number.isNaN(r)?(t[0]=1,t[1]=1,t[2]=1,t):(t[0]=(r>>16&255)/255,t[1]=(r>>8&255)/255,t[2]=(r&255)/255,t)}};T.vec2Pool=[],T.vec3Pool=[],T.vec4Pool=[],T.scratchVec2=new Float32Array(2),T.scratchVec3=new Float32Array(3),T.scratchVec4=new Float32Array(4);var j=class{constructor(e){this.samples=new Float32Array(30);this.sampleIdx=0;this.sampleCount=0;this.stableUpWindows=0;this.lastAdjustAt=0;this.minScale=Math.max(.5,e.minScale),this.maxScale=Math.max(this.minScale,e.maxScale),this.currentScale=this.maxScale,this.downThresholdMs=e.downThresholdMs??20.5,this.upThresholdMs=e.upThresholdMs??17.2,this.cooldownMs=e.cooldownMs??750}get scale(){return this.currentScale}setBounds(e,t){let i=Math.max(.5,e),r=Math.max(i,t),s=this.currentScale;return this.minScale=i,this.maxScale=r,this.currentScale=Math.min(r,Math.max(i,this.currentScale)),r>s&&(this.currentScale=r),this.sampleCount=0,this.sampleIdx=0,this.stableUpWindows=0,Math.abs(this.currentScale-s)>.01}recordFrame(e,t){if(this.minScale>=this.maxScale||e<=0||e>60)return!1;if(this.samples[this.sampleIdx]=e,this.sampleIdx=(this.sampleIdx+1)%this.samples.length,this.sampleCount<this.samples.length)return this.sampleCount++,!1;if(t-this.lastAdjustAt<this.cooldownMs)return!1;let i=0;for(let s=0;s<this.samples.length;s++)i+=this.samples[s];let r=i/this.samples.length;if(r>this.downThresholdMs&&this.currentScale>this.minScale)return this.currentScale=Math.max(this.minScale,Number((this.currentScale-.15).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=t,!0;if(r<this.upThresholdMs&&this.currentScale<this.maxScale){if(this.stableUpWindows++,this.stableUpWindows>=2)return this.currentScale=Math.min(this.maxScale,Number((this.currentScale+.1).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=t,!0}else this.stableUpWindows=0;return!1}};var W=null;function M(o,e="#ffffff"){if(typeof o!="string")return e;let t=o.trim();if(!t)return e;if(typeof document<"u"){if(!W){let i=document.createElement("canvas");i.width=1,i.height=1,W=i.getContext("2d")}if(W){W.fillStyle="#010203",W.fillStyle=t;let i=W.fillStyle;if(/^#[0-9a-f]{6}$/i.test(i))return i;let r=i.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);if(r)return"#"+[Number(r[1]),Number(r[2]),Number(r[3])].map(s=>Math.max(0,Math.min(255,s)).toString(16).padStart(2,"0")).join("")}}return e}function me(o){let e=o.trim().toLowerCase();if(!e||e==="transparent"||e==="none")return null;let t=e.match(/^rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/);if(t){let r=Math.max(0,Math.min(255,parseFloat(t[1])))/255,s=Math.max(0,Math.min(255,parseFloat(t[2])))/255,a=Math.max(0,Math.min(255,parseFloat(t[3])))/255,n=1;return t[4]!==void 0&&(n=t[4].endsWith("%")?parseFloat(t[4])/100:parseFloat(t[4])),[r,s,a,Math.max(0,Math.min(1,n))]}let i=e.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);if(i){let r=i[1],s=r.length===3?r.split("").map(a=>a+a).join(""):r;return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1]}return null}function pe(o,e,t){let i=r=>r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4);return .2126*i(o)+.7152*i(e)+.0722*i(t)}function ve(o){if(typeof document>"u"||typeof window>"u")return!0;let e=o;for(;e;){let a=(e.getAttribute("data-theme")||e.getAttribute("data-mode")||e.getAttribute("data-bs-theme")||"").trim().toLowerCase();if(a==="dark")return!0;if(a==="light")return!1;if(e.classList.contains("dark")||e.classList.contains("dark-mode"))return!0;if(e.classList.contains("light")||e.classList.contains("light-mode"))return!1;e=e.parentElement}let t=document.documentElement,i=document.body,r=(t?.getAttribute("data-theme")||t?.getAttribute("data-mode")||t?.getAttribute("data-bs-theme")||"").trim().toLowerCase();if(r==="dark")return!0;if(r==="light")return!1;if(t?.classList.contains("dark")||i?.classList.contains("dark"))return!0;if(t?.classList.contains("light")||i?.classList.contains("light"))return!1;let s=o;for(;s;){let a=window.getComputedStyle(s).backgroundColor,n=me(a);if(n&&n[3]>.12)return pe(n[0],n[1],n[2])<.42;s=s.parentElement}return typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)").matches:!0}function re(o,e,t){let i=Math.max(o,e,t),r=Math.min(o,e,t),s=(i+r)*.5;if(i===r)return[0,0,s];let a=i-r,n=s>.5?a/(2-i-r):a/(i+r),l=0;return i===o?l=((e-t)/a+(e<t?6:0))/6:i===e?l=((t-o)/a+2)/6:l=((o-e)/a+4)/6,[l,n,s]}function ge(o,e,t){if(e===0)return[t,t,t];let i=(a,n,l)=>{let c=l;return c<0&&(c+=1),c>1&&(c-=1),c<1/6?a+(n-a)*6*c:c<1/2?n:c<2/3?a+(n-a)*(2/3-c)*6:a},r=t<.5?t*(1+e):t+e-t*e,s=2*t-r;return[i(s,r,o+1/3),i(s,r,o),i(s,r,o-1/3)]}function K(o,e){return o.map(([t,i,r])=>{let[s,a,n]=re(t,i,r);if(e)return[t,i,r];let l=Math.min(a,.72)*.92,c=Math.max(.36,Math.min(.6,n*.78+.14));return ge(s,l,c)})}function be(o,e){if(typeof window>"u"||!o)return null;let t=o;for(;t;){if(t.getAttribute("data-fluxfx-canvas")!=="true"){let i=window.getComputedStyle(t).backgroundColor,r=me(i);if(r&&r[3]>.14)return r}if(t===e)break;t=t.parentElement}return null}function ye(o,e){let[t,i,r]=re(e[0],e[1],e[2]),s=pe(e[0],e[1],e[2]);if(i<.2)return K(o,s<.42);let a=s<.38;return o.map(([n,l,c],u)=>{let[h,f,d]=re(n,l,c),m=Math.abs(h-t),p=Math.min(m,1-m),v=h;if(p<.22){let L=[.46,.56,.34];v=(t+L[u%L.length])%1}let g=Math.max(.55,Math.min(.92,f<.35?.72:f)),b=a?Math.max(.68,Math.min(.86,d*.45+.48)):Math.max(.24,Math.min(.44,d*.5+.12)),y=Math.abs(b-r)<.22?a?Math.min(.88,r+.34):Math.max(.2,r-.34):b;return ge(v,g,y)})}var N=`#version 300 es
3
3
  precision highp float;
4
4
  layout(location = 0) in vec2 aPosition;
5
5
  out vec2 vUv;
6
6
  void main() {
7
7
  vUv = aPosition * 0.5 + 0.5;
8
8
  gl_Position = vec4(aPosition, 0.0, 1.0);
9
- }`,v=class{static hashSource(e,i){let t=e+"|"+i,r=2166136261;for(let s=0;s<t.length;s++)r^=t.charCodeAt(s),r=Math.imul(r,16777619);return(r>>>0).toString(36)}static compileShader(e,i,t){let r=e.createShader(i);if(!r)throw new Error("[FluxFX] Failed to create WebGLShader");if(e.shaderSource(r,t),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(r);throw e.deleteShader(r),new Error(`[FluxFX] Shader compile error:
10
- ${s}`)}return r}static getOrCreateProgram(e,i,t=P){let r=this.contextCache.get(e);r||(r=new Map,this.contextCache.set(e,r));let s=this.hashSource(t,i),a=r.get(s);if(a)return a;e.getExtension("KHR_parallel_shader_compile");let n=this.compileShader(e,e.VERTEX_SHADER,t),l=this.compileShader(e,e.FRAGMENT_SHADER,i),u=e.createProgram();if(!u)throw e.deleteShader(n),e.deleteShader(l),new Error("[FluxFX] Failed to create WebGLProgram");if(e.attachShader(u,n),e.attachShader(u,l),e.linkProgram(u),e.deleteShader(n),e.deleteShader(l),!e.getProgramParameter(u,e.LINK_STATUS)){let f=e.getProgramInfoLog(u);throw e.deleteProgram(u),new Error(`[FluxFX] Program link error:
11
- ${f}`)}let d={program:u,uniforms:new Map};return r.set(s,d),d}static getUniformLocation(e,i,t){if(i.uniforms.has(t))return i.uniforms.get(t)??null;let r=e.getUniformLocation(i.program,t);return i.uniforms.set(t,r),r}static precompile(e,i){for(let t=0;t<i.length;t++)this.getOrCreateProgram(e,i[t])}static disposeContext(e){let i=this.contextCache.get(e);i&&(i.forEach(t=>e.deleteProgram(t.program)),i.clear(),this.contextCache.delete(e))}};v.contextCache=new WeakMap;var pe=`
9
+ }`,x=class{static hashSource(e,t){let i=e+"|"+t,r=2166136261;for(let s=0;s<i.length;s++)r^=i.charCodeAt(s),r=Math.imul(r,16777619);return(r>>>0).toString(36)}static compileShader(e,t,i){let r=e.createShader(t);if(!r)throw new Error("[FluxFX] Failed to create WebGLShader");if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(r);throw e.deleteShader(r),new Error(`[FluxFX] Shader compile error:
10
+ ${s}`)}return r}static getOrCreateProgram(e,t,i=N){let r=this.contextCache.get(e);r||(r=new Map,this.contextCache.set(e,r));let s=this.hashSource(i,t),a=r.get(s);if(a)return a;e.getExtension("KHR_parallel_shader_compile");let n=this.compileShader(e,e.VERTEX_SHADER,i),l=this.compileShader(e,e.FRAGMENT_SHADER,t),c=e.createProgram();if(!c)throw e.deleteShader(n),e.deleteShader(l),new Error("[FluxFX] Failed to create WebGLProgram");if(e.attachShader(c,n),e.attachShader(c,l),e.linkProgram(c),e.deleteShader(n),e.deleteShader(l),!e.getProgramParameter(c,e.LINK_STATUS)){let h=e.getProgramInfoLog(c);throw e.deleteProgram(c),new Error(`[FluxFX] Program link error:
11
+ ${h}`)}let u={program:c,uniforms:new Map};return r.set(s,u),u}static getUniformLocation(e,t,i){if(t.uniforms.has(i))return t.uniforms.get(i)??null;let r=e.getUniformLocation(t.program,i);return t.uniforms.set(i,r),r}static precompile(e,t){for(let i=0;i<t.length;i++)this.getOrCreateProgram(e,t[i])}static disposeContext(e){let t=this.contextCache.get(e);t&&(t.forEach(i=>e.deleteProgram(i.program)),t.clear(),this.contextCache.delete(e))}};x.contextCache=new WeakMap;var Ue=`
12
12
  let gl = null;
13
13
  let canvas = null;
14
14
  let displayProgram = null;
@@ -19,12 +19,27 @@ let rafId = 0;
19
19
 
20
20
  let running = false;
21
21
  let pausedByHost = false;
22
+ let survivalPaused = false;
22
23
  let reducedMotion = false;
23
24
  let contextLost = false;
24
25
  let needsResize = false;
25
26
 
27
+ const AMBIENT_FPS = 30;
28
+ const ACTIVE_FPS = 60;
29
+ const INTERACTION_BOOST_MS = 1800;
30
+ let ambientFps = AMBIENT_FPS;
31
+ let activeFps = ACTIVE_FPS;
32
+ const STATS_REPORT_INTERVAL_MS = 350;
33
+
34
+ let boostUntil = 0;
35
+ let lastRafTime = 0;
36
+ let lastDrawTime = 0;
37
+ let lastTargetFps = 0;
38
+ let prevFrameDrew = false;
39
+ let avgDrawDeltaMs = 0;
40
+ let lastStatsReport = 0;
41
+
26
42
  let elapsedSec = 0;
27
- let lastFrameTime = 0;
28
43
  let lastDeltaSec = 0.01667;
29
44
  let currentSpeed = 1.0;
30
45
  let targetSpeed = 1.0;
@@ -82,7 +97,12 @@ function cancelFrame(id) {
82
97
  else clearTimeout(id);
83
98
  }
84
99
 
85
- // Frame-rate independent exponential smoothing (identical feel at 60Hz, 90Hz, 120Hz ProMotion)
100
+ function boostInteraction(durationMs) {
101
+ const until = performance.now() + (durationMs || INTERACTION_BOOST_MS);
102
+ if (until > boostUntil) boostUntil = until;
103
+ }
104
+
105
+ // Frame-rate independent exponential smoothing (identical feel at 30Hz, 60Hz, 120Hz ProMotion)
86
106
  function damp(lambda, dt) {
87
107
  return 1 - Math.exp(-lambda * dt);
88
108
  }
@@ -138,7 +158,7 @@ function applyUniform(prog, cache, name, val) {
138
158
  function computeFboDims(canvasW, canvasH) {
139
159
  let w = Math.max(1, Math.floor(canvasW * feedbackScale));
140
160
  let h = Math.max(1, Math.floor(canvasH * feedbackScale));
141
- // Cap longest edge so 4K/5K Retina screens stay locked at 60/120 FPS
161
+ // Cap longest edge so 4K/5K Retina screens stay locked at target FPS
142
162
  const longest = Math.max(w, h);
143
163
  if (longest > feedbackMaxDim) {
144
164
  const ratio = feedbackMaxDim / longest;
@@ -258,9 +278,9 @@ function applySize() {
258
278
  canvas.width = w;
259
279
  canvas.height = h;
260
280
  gl.viewport(0, 0, w, h);
261
- if (pingPong) {
262
- resizePingPong(w, h);
263
- }
281
+ }
282
+ if (pingPong) {
283
+ resizePingPong(canvas.width, canvas.height);
264
284
  }
265
285
  }
266
286
 
@@ -410,29 +430,69 @@ function stopLoop() {
410
430
  running = false;
411
431
  cancelFrame(rafId);
412
432
  rafId = 0;
413
- lastFrameTime = 0;
433
+ lastRafTime = 0;
434
+ lastDrawTime = 0;
435
+ lastTargetFps = 0;
436
+ prevFrameDrew = false;
437
+ avgDrawDeltaMs = 0;
438
+ lastStatsReport = 0;
439
+ self.postMessage({ type: 'stats', fps: 0, frameTimeMs: 0, targetFps: 0 });
414
440
  }
415
441
 
416
442
  function startLoopIfAllowed() {
417
- if (running || pausedByHost || reducedMotion || contextLost || !gl) return;
443
+ if (running || pausedByHost || survivalPaused || reducedMotion || contextLost || !gl) return;
418
444
  running = true;
419
- lastFrameTime = 0;
445
+ lastRafTime = 0;
446
+ lastDrawTime = 0;
447
+ prevFrameDrew = false;
420
448
  rafId = scheduleFrame(render);
421
449
  }
422
450
 
423
451
  function render(now) {
424
452
  if (!running || !gl || contextLost) return;
425
- const delta = lastFrameTime ? Math.min(now - lastFrameTime, 100) : 16.67;
426
- lastFrameTime = now;
427
- const dt = Math.max(0.001, Math.min(delta * 0.001, 0.05));
453
+
454
+ const rafDelta = lastRafTime ? Math.min(now - lastRafTime, 100) : 16.67;
455
+ lastRafTime = now;
456
+
457
+ // Measure dynamic resolution only on frames immediately following a GPU draw
458
+ if (prevFrameDrew) {
459
+ if (updateDynamicRes(rafDelta, now)) {
460
+ needsResize = true;
461
+ }
462
+ prevFrameDrew = false;
463
+ }
464
+
465
+ const isBoosted = now < boostUntil || mouseDown > 0.5;
466
+ const targetFps = isBoosted ? activeFps : ambientFps;
467
+ const minIntervalMs = (1000 / targetFps) - 2.0;
468
+
469
+ if (lastDrawTime > 0 && (now - lastDrawTime) < minIntervalMs) {
470
+ rafId = scheduleFrame(render);
471
+ return;
472
+ }
473
+
474
+ const rawDrawDelta = lastDrawTime ? (now - lastDrawTime) : (1000 / targetFps);
475
+ const drawDelta = Math.min(rawDrawDelta, 100);
476
+ lastDrawTime = now;
477
+
478
+ if (targetFps !== lastTargetFps) {
479
+ lastTargetFps = targetFps;
480
+ avgDrawDeltaMs = 0;
481
+ } else if (rawDrawDelta > 0 && rawDrawDelta < 500) {
482
+ avgDrawDeltaMs =
483
+ avgDrawDeltaMs === 0
484
+ ? rawDrawDelta
485
+ : avgDrawDeltaMs * 0.85 + rawDrawDelta * 0.15;
486
+ }
487
+
488
+ const dt = Math.max(0.001, Math.min(drawDelta * 0.001, 0.05));
428
489
  lastDeltaSec = dt;
429
490
 
430
491
  // Smoothly ramp speed and integrate phase time (zero jump when speed changes)
431
492
  currentSpeed += (targetSpeed - currentSpeed) * damp(7.5, dt);
432
493
  elapsedSec += dt * currentSpeed;
433
494
 
434
- const dprChanged = updateDynamicRes(delta, now);
435
- if (needsResize || dprChanged) {
495
+ if (needsResize) {
436
496
  needsResize = false;
437
497
  applySize();
438
498
  }
@@ -459,6 +519,17 @@ function render(now) {
459
519
  scrollVel = Math.max(-6, Math.min(6, (scrollProgress - prevS) / dt));
460
520
 
461
521
  drawFrame();
522
+ prevFrameDrew = true;
523
+
524
+ if (avgDrawDeltaMs > 0 && now - lastStatsReport >= STATS_REPORT_INTERVAL_MS) {
525
+ lastStatsReport = now;
526
+ self.postMessage({
527
+ type: 'stats',
528
+ fps: Math.round(1000 / avgDrawDeltaMs),
529
+ frameTimeMs: Math.round(avgDrawDeltaMs * 100) / 100,
530
+ targetFps: targetFps,
531
+ });
532
+ }
462
533
 
463
534
  rafId = scheduleFrame(render);
464
535
  }
@@ -499,6 +570,9 @@ self.onmessage = function(e) {
499
570
  minScale = msg.minDpr;
500
571
  dynamicRes = msg.dynamicRes;
501
572
  reducedMotion = !!msg.reducedMotion;
573
+ ambientFps = msg.ambientFps || AMBIENT_FPS;
574
+ activeFps = msg.activeFps || ACTIVE_FPS;
575
+ survivalPaused = !!msg.survivalPaused;
502
576
  savedVertexSrc = msg.vertexShader;
503
577
  savedFragmentSrc = msg.fragmentShader;
504
578
  savedFeedbackSrc = msg.feedbackShader || null;
@@ -549,6 +623,7 @@ self.onmessage = function(e) {
549
623
  case 'resize':
550
624
  width = msg.width;
551
625
  height = msg.height;
626
+ boostInteraction(600);
552
627
  if (reducedMotion && !pausedByHost && !contextLost) {
553
628
  needsResize = false;
554
629
  applySize();
@@ -557,6 +632,34 @@ self.onmessage = function(e) {
557
632
  needsResize = true;
558
633
  }
559
634
  break;
635
+ case 'protection':
636
+ ambientFps = msg.ambientFps || AMBIENT_FPS;
637
+ activeFps = msg.activeFps || ACTIVE_FPS;
638
+ minScale = msg.minDpr;
639
+ baseDpr = msg.maxDpr;
640
+ dprScale = baseDpr;
641
+ if (typeof msg.feedbackMaxDim === 'number') {
642
+ feedbackMaxDim = msg.feedbackMaxDim;
643
+ }
644
+ sampleCount = 0;
645
+ sampleIdx = 0;
646
+ stableWindows = 0;
647
+ if (msg.suspended) {
648
+ survivalPaused = true;
649
+ stopLoop();
650
+ } else {
651
+ const wasSuspended = survivalPaused;
652
+ survivalPaused = false;
653
+ if (reducedMotion && !pausedByHost && !contextLost) {
654
+ needsResize = false;
655
+ applySize();
656
+ drawFrame();
657
+ } else {
658
+ needsResize = true;
659
+ if (wasSuspended) startLoopIfAllowed();
660
+ }
661
+ }
662
+ break;
560
663
  case 'dprBounds':
561
664
  minScale = msg.minDpr;
562
665
  baseDpr = msg.maxDpr;
@@ -580,11 +683,13 @@ self.onmessage = function(e) {
580
683
  mouseVel[0] = 0;
581
684
  mouseVel[1] = 0;
582
685
  targetMouseActive = 1;
686
+ boostInteraction(INTERACTION_BOOST_MS);
583
687
  break;
584
688
  case 'mouse':
585
689
  targetMouse[0] = msg.x;
586
690
  targetMouse[1] = msg.y;
587
691
  targetMouseActive = 1;
692
+ boostInteraction(INTERACTION_BOOST_MS);
588
693
  break;
589
694
  case 'mouseLeave':
590
695
  targetMouseActive = 0;
@@ -594,9 +699,11 @@ self.onmessage = function(e) {
594
699
  break;
595
700
  case 'mouseDown':
596
701
  mouseDown = msg.down ? 1 : 0;
702
+ boostInteraction(INTERACTION_BOOST_MS);
597
703
  break;
598
704
  case 'scroll':
599
705
  targetScroll = msg.progress;
706
+ boostInteraction(1200);
600
707
  if (reducedMotion && !pausedByHost && !contextLost) {
601
708
  scrollProgress = targetScroll;
602
709
  scrollVel = 0;
@@ -608,6 +715,7 @@ self.onmessage = function(e) {
608
715
  if (msg.name === 'uSpeed' && typeof msg.value === 'number') {
609
716
  targetSpeed = msg.value;
610
717
  }
718
+ boostInteraction(1200);
611
719
  if (reducedMotion && !contextLost) drawFrame();
612
720
  break;
613
721
  case 'uniformsBatch':
@@ -619,6 +727,7 @@ self.onmessage = function(e) {
619
727
  }
620
728
  }
621
729
  }
730
+ boostInteraction(1200);
622
731
  if (reducedMotion && !contextLost) drawFrame();
623
732
  break;
624
733
  case 'reducedMotion':
@@ -669,7 +778,9 @@ self.onmessage = function(e) {
669
778
  if (feedbackProgram) gl.deleteProgram(feedbackProgram);
670
779
  if (vbo) gl.deleteBuffer(vbo);
671
780
  if (vao) gl.deleteVertexArray(vao);
672
- gl.getExtension('WEBGL_lose_context')?.loseContext();
781
+ if (!gl.isContextLost()) {
782
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
783
+ }
673
784
  }
674
785
  gl = null;
675
786
  canvas = null;
@@ -677,7 +788,7 @@ self.onmessage = function(e) {
677
788
  break;
678
789
  }
679
790
  };
680
- `,H=null;function q(){if(typeof window>"u"||typeof Worker>"u"||typeof OffscreenCanvas>"u"||typeof HTMLCanvasElement>"u"||!("transferControlToOffscreen"in HTMLCanvasElement.prototype))return!1;let o=typeof navigator<"u"?navigator.userAgent:"";return!(/iP(ad|hone|od)/i.test(o)||/^((?!chrome|android).)*safari/i.test(o))}function N(){if(!H){let o=new Blob([pe],{type:"application/javascript"});H=URL.createObjectURL(o)}return new Worker(H)}var Q=P;var C={low:{max:1,min:.65,retinaMin:.85,fboMaxDim:512},medium:{max:2,min:.75,retinaMin:1,fboMaxDim:896},high:{max:2,min:1,retinaMin:1.25,fboMaxDim:1152}},ve=new Float32Array([-1,-1,3,-1,-1,3]),ge=12;function k(o,e){return 1-Math.exp(-o*e)}var R=class R{constructor(e,i){this.resizeObserver=null;this.visibilityObserver=null;this.reducedMotionQuery=null;this.dprMediaQuery=null;this.worker=null;this.isOffscreen=!1;this.gl=null;this.programEntry=null;this.feedbackProgramEntry=null;this.vao=null;this.vbo=null;this.dynamicRes=null;this.lastRenderNow=0;this.elapsedSec=0;this.lastDeltaSec=.01667;this.currentSpeed=1;this.targetSpeed=1;this.needsResize=!1;this.pingPong=null;this.fboW=1;this.fboH=1;this.fboFormat=0;this.fboType=0;this.readIdx=0;this.writeIdx=1;this.customUniforms=new Map;this.mouse=g.acquireVec2(.5,.5);this.targetMouse=g.acquireVec2(.5,.5);this.mouseVel=g.acquireVec2(0,0);this.mouseDown=0;this.mouseActive=0;this.targetMouseActive=0;this.isPointerInside=!1;this.scroll=0;this.targetScroll=0;this.scrollVel=0;this.hasScrollListener=!1;this.width=1;this.height=1;this.isPaused=!1;this.isHiddenByViewport=!1;this.isContextLost=!1;this.isReducedMotion=!1;this.isDestroyed=!1;this.hasPointerListener=!1;this.countedContext=!1;this.handleContextLost=e=>{e.preventDefault(),this.isContextLost=!0,this.lastRenderNow=0,this.gl&&v.disposeContext(this.gl),this.programEntry=null,this.feedbackProgramEntry=null,this.pingPong=null,this.vao=null,this.vbo=null};this.handleContextRestored=()=>{if(!(this.isDestroyed||!this.gl))try{this.isContextLost=!1,this.initMainThreadPipeline(this.gl),this.drawMainThreadFrame()}catch(e){console.error("[FluxFX] Failed to restore WebGL2 context:",e)}};this.handleDprChange=()=>{this.isDestroyed||(this.syncDprBounds(),this.watchDevicePixelRatio())};this.handleReducedMotionChange=e=>{this.applyReducedMotionState(this.respectReducedMotion&&e.matches)};this.handlePointerEnter=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let i=this.getLocalPointerCoords(e);if(!i)return;let[t,r]=i;this.isPointerInside=!0,this.targetMouseActive=1,this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouseEnter",x:t,y:r}):(this.mouse[0]=t,this.mouse[1]=r,this.targetMouse[0]=t,this.targetMouse[1]=r,this.mouseVel[0]=0,this.mouseVel[1]=0)};this.handlePointerMove=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let i=this.getLocalPointerCoords(e);if(!i){this.isPointerInside&&this.handlePointerLeave();return}let[t,r]=i;if(!this.isPointerInside){this.handlePointerEnter(e);return}this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouse",x:t,y:r}):(this.targetMouse[0]=t,this.targetMouse[1]=r)};this.handlePointerLeave=()=>{!this.isPointerInside&&this.targetMouseActive===0||(this.isPointerInside=!1,this.targetMouseActive=0,this.mouseDown=0,this.mouseVel[0]=0,this.mouseVel[1]=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseLeave"}))};this.handlePointerDown=e=>{this.isPaused||this.isHiddenByViewport||this.isReducedMotion||(this.isPointerInside||this.handlePointerEnter(e),this.mouseDown=1,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!0}))};this.handlePointerUp=()=>{this.mouseDown!==0&&(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}))};this.handleScroll=()=>{if(!this.trackScroll||this.isDestroyed)return;let e=this.computeScrollProgress();this.isOffscreen&&this.worker?this.worker.postMessage({type:"scroll",progress:e}):(this.targetScroll=e,this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport&&(this.scroll=e,this.scrollVel=0,this.drawMainThreadFrame()))};this.handleDocVisibility=()=>{!this.isOffscreen||!this.worker||(document.hidden?this.worker.postMessage({type:"pause"}):!this.isPaused&&!this.isHiddenByViewport&&this.worker.postMessage({type:"resume"}))};this.container=e,this.options={...i},this.interactive=i.interactive??!0,this.respectReducedMotion=i.respectReducedMotion??!0,this.trackScroll=i.trackScroll??!1,this.feedbackScale=i.feedbackScale??.5,this.feedbackFloat=i.feedbackFloat??!0;let t=i.quality??"medium",r=C[t]??C.medium;this.feedbackMaxDim=i.feedbackMaxDim??r.fboMaxDim,typeof window<"u"&&typeof window.matchMedia=="function"&&(this.reducedMotionQuery=window.matchMedia("(prefers-reduced-motion: reduce)"),this.isReducedMotion=this.respectReducedMotion&&this.reducedMotionQuery.matches),window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.container.style.isolation="isolate",this.canvas=document.createElement("canvas"),this.canvas.setAttribute("data-fluxfx-canvas","true"),this.canvas.style.position="absolute",this.canvas.style.inset="0",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.zIndex="-1",this.canvas.style.pointerEvents="none",this.canvas.style.display="block",this.container.prepend(this.canvas);let a=this.container.getBoundingClientRect();if(this.width=Math.max(1,Math.floor(a.width)),this.height=Math.max(1,Math.floor(a.height)),this.trackScroll){let f=this.computeScrollProgress();this.scroll=f,this.targetScroll=f}let{minDpr:n,maxDpr:l}=this.resolveDprBounds(),u=i.dynamicResolution??!0,d=i.offscreen??!0;this.seedUniformsFromOptions(i,!0),d&&q()?this.initOffscreenMode(i,n,l,u):this.initMainThreadMode(i,n,l,u),this.bindObservers(i.pauseWhenHidden??!0)}static get activeContexts(){return this._activeContexts}resolveDprBounds(){let e=this.options.quality??"medium",i=C[e]??C.medium,t=typeof window<"u"&&window.devicePixelRatio||1,r=t>=1.5,s=this.options.maxDpr??Math.min(t,i.max),a=r?i.retinaMin:i.min;return{minDpr:this.options.minDpr??Math.min(a,s),maxDpr:s}}computeScrollProgress(){if(typeof window>"u")return 0;let e=this.container.getBoundingClientRect(),i=window.innerHeight||1,t=i+e.height;return t<=0?0:Math.min(1,Math.max(0,(i-e.top)/t))}markContextActive(){this.countedContext||(this.countedContext=!0,R._activeContexts++,R._activeContexts>ge&&console.warn(`[FluxFX] ${R._activeContexts} active WebGL contexts detected. Browsers typically cap contexts around 8\u201316; consider limiting simultaneous WebGL backgrounds.`))}markContextReleased(){this.countedContext&&(this.countedContext=!1,R._activeContexts=Math.max(0,R._activeContexts-1))}seedUniformsFromOptions(e,i=!1){let t={};if(typeof e.speed=="number"?(this.targetSpeed=e.speed,i&&(this.currentSpeed=e.speed),this.customUniforms.set("uSpeed",e.speed),t.uSpeed=e.speed):this.customUniforms.has("uSpeed")||(this.targetSpeed=1,this.currentSpeed=1,this.customUniforms.set("uSpeed",1),t.uSpeed=1),e.colors&&e.colors.length>0){let r=Array.isArray(e.colors)?e.colors:String(e.colors).split(",").map(n=>n.trim()).filter(Boolean),s=c(r[0],"#ffffff"),a=Math.min(r.length,3);for(let n=0;n<a;n++){let l=c(r[n],s),u=g.hexToVec3Into(l,g.scratchVec3),d=[u[0],u[1],u[2]];this.customUniforms.set(`uColor${n+1}`,d),t[`uColor${n+1}`]=d}if(a===1){let n=this.customUniforms.get("uColor1");this.customUniforms.set("uColor2",[n[0],n[1],n[2]]),t.uColor2=[n[0],n[1],n[2]]}}if(e.uniforms)for(let[r,s]of Object.entries(e.uniforms))this.customUniforms.set(r,s),t[r]=typeof s=="number"?s:Array.from(s);return t}fallbackToMainThread(e,i,t,r){if(this.isDestroyed)return;this.worker&&(this.worker.terminate(),this.worker=null),this.isOffscreen=!1,this.markContextReleased();let s=this.canvas.cloneNode(!1);this.canvas.replaceWith(s),this.canvas=s,this.initMainThreadMode(e,i,t,r)}initOffscreenMode(e,i,t,r){try{let s=N(),a=this.canvas.transferControlToOffscreen();this.worker=s,this.isOffscreen=!0,this.markContextActive(),s.onmessage=l=>{l.data?.type==="error"&&this.fallbackToMainThread(e,i,t,r)},s.onerror=()=>{this.fallbackToMainThread(e,i,t,r)};let n={};this.customUniforms.forEach((l,u)=>{n[u]=typeof l=="number"?l:Array.from(l)}),s.postMessage({type:"init",canvas:a,width:this.width,height:this.height,minDpr:i,maxDpr:t,dynamicRes:r,reducedMotion:this.isReducedMotion,vertexShader:e.vertexShader??Q,fragmentShader:e.fragmentShader,feedbackShader:e.feedbackShader??null,feedbackScale:this.feedbackScale,feedbackMaxDim:this.feedbackMaxDim,feedbackFloat:this.feedbackFloat,initialScroll:this.scroll,uniforms:n},[a])}catch{this.isOffscreen=!1,this.markContextReleased(),this.initMainThreadMode(e,i,t,r)}}computeFboDimsMain(e,i){let t=Math.max(1,Math.floor(e*this.feedbackScale)),r=Math.max(1,Math.floor(i*this.feedbackScale)),s=Math.max(t,r);if(s>this.feedbackMaxDim){let a=this.feedbackMaxDim/s;t=Math.max(1,Math.floor(t*a)),r=Math.max(1,Math.floor(r*a))}return[t,r]}destroyPingPongMain(){if(!this.pingPong||!this.gl){this.pingPong=null;return}for(let e=0;e<2;e++)this.gl.deleteFramebuffer(this.pingPong[e].fbo),this.gl.deleteTexture(this.pingPong[e].tex);this.pingPong=null}createPingPongMain(e){if(this.destroyPingPongMain(),!this.options.feedbackShader||this.isContextLost)return;let[i,t]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);this.fboW=i,this.fboH=t;let r=e.RGBA8,s=e.UNSIGNED_BYTE;this.feedbackFloat&&(e.getExtension("EXT_color_buffer_float")||e.getExtension("EXT_color_buffer_half_float"))&&(r=e.RGBA16F,s=e.HALF_FLOAT);let n=(u,d)=>{let f=[];for(let h=0;h<2;h++){let m=e.createTexture(),p=e.createFramebuffer();if(!m||!p)return m&&e.deleteTexture(m),p&&e.deleteFramebuffer(p),f.forEach(b=>{e.deleteFramebuffer(b.fbo),e.deleteTexture(b.tex)}),null;if(e.bindTexture(e.TEXTURE_2D,m),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,u,this.fboW,this.fboH,0,e.RGBA,d,null),e.bindFramebuffer(e.FRAMEBUFFER,p),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,m,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)return e.deleteFramebuffer(p),e.deleteTexture(m),f.forEach(b=>{e.deleteFramebuffer(b.fbo),e.deleteTexture(b.tex)}),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),null;e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),f.push({fbo:p,tex:m})}return e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),[f[0],f[1]]},l=n(r,s);!l&&r!==e.RGBA8&&(r=e.RGBA8,s=e.UNSIGNED_BYTE,l=n(r,s)),this.fboFormat=r,this.fboType=s,this.pingPong=l,this.readIdx=0,this.writeIdx=1}resizePingPongMain(){if(!this.pingPong||!this.gl||this.isContextLost)return;let[e,i]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);if(e===this.fboW&&i===this.fboH)return;let t=this.gl,r=this.fboW,s=this.fboH,a=this.pingPong[this.readIdx],n=[];for(let l=0;l<2;l++){let u=t.createTexture(),d=t.createFramebuffer();t.bindTexture(t.TEXTURE_2D,u),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,this.fboFormat,e,i,0,t.RGBA,this.fboType,null),t.bindFramebuffer(t.FRAMEBUFFER,d),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,u,0),n.push({fbo:d,tex:u})}t.bindFramebuffer(t.READ_FRAMEBUFFER,a.fbo),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,n[0].fbo),t.blitFramebuffer(0,0,r,s,0,0,e,i,t.COLOR_BUFFER_BIT,t.LINEAR),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindTexture(t.TEXTURE_2D,null);for(let l=0;l<2;l++)t.deleteFramebuffer(this.pingPong[l].fbo),t.deleteTexture(this.pingPong[l].tex);this.pingPong=[n[0],n[1]],this.fboW=e,this.fboH=i,this.readIdx=0,this.writeIdx=1}initMainThreadPipeline(e){let i=this.options.vertexShader??P;this.programEntry=v.getOrCreateProgram(e,this.options.fragmentShader,i),this.options.feedbackShader?this.feedbackProgramEntry=v.getOrCreateProgram(e,this.options.feedbackShader,i):this.feedbackProgramEntry=null,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vbo=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vbo),e.bufferData(e.ARRAY_BUFFER,ve,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),this.needsResize=!1,this.applyCanvasSize(),this.options.feedbackShader&&this.createPingPongMain(e)}initMainThreadMode(e,i,t,r){let s=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance",preserveDrawingBuffer:!1});if(!s){console.warn("[FluxFX] WebGL2 is not supported on this device.");return}this.gl=s,this.markContextActive(),this.canvas.addEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestored,!1),this.dynamicRes=new D({minScale:r?i:t,maxScale:t}),this.initMainThreadPipeline(s),this.drawMainThreadFrame()}applyCanvasSize(){if(!this.gl||!this.dynamicRes||this.isContextLost)return;let e=this.dynamicRes.scale,i=Math.max(1,Math.round(this.width*e)),t=Math.max(1,Math.round(this.height*e));(this.canvas.width!==i||this.canvas.height!==t)&&(this.canvas.width=i,this.canvas.height=t,this.gl.viewport(0,0,i,t),this.pingPong&&this.resizePingPongMain())}bindCommonUniformsMain(e,i,t,r){let s=v.getUniformLocation(e,i,"uTime");s&&e.uniform1f(s,this.elapsedSec);let a=v.getUniformLocation(e,i,"uDelta");a&&e.uniform1f(a,this.lastDeltaSec);let n=v.getUniformLocation(e,i,"uResolution");n&&e.uniform2f(n,t,r);let l=v.getUniformLocation(e,i,"uCanvasResolution");l&&e.uniform2f(l,this.canvas.width,this.canvas.height);let u=v.getUniformLocation(e,i,"uDpr");u&&this.dynamicRes&&e.uniform1f(u,this.dynamicRes.scale);let d=v.getUniformLocation(e,i,"uMouse");d&&e.uniform2f(d,this.mouse[0],this.mouse[1]);let f=v.getUniformLocation(e,i,"uMouseVel");f&&e.uniform2f(f,this.mouseVel[0],this.mouseVel[1]);let h=v.getUniformLocation(e,i,"uMouseDown");h&&e.uniform1f(h,this.mouseDown);let m=v.getUniformLocation(e,i,"uMouseActive");m&&e.uniform1f(m,this.mouseActive);let p=v.getUniformLocation(e,i,"uScroll");p&&e.uniform1f(p,this.scroll);let b=v.getUniformLocation(e,i,"uScrollVel");b&&e.uniform1f(b,this.scrollVel),this.customUniforms.forEach((y,S)=>{let M=v.getUniformLocation(e,i,S);M&&(S==="uSpeed"?e.uniform1f(M,this.currentSpeed):typeof y=="number"?e.uniform1f(M,y):y.length===2?e.uniform2f(M,y[0],y[1]):y.length===3?e.uniform3f(M,y[0],y[1],y[2]):y.length===4&&e.uniform4f(M,y[0],y[1],y[2],y[3]))})}drawMainThreadFrame(){if(!this.gl||!this.programEntry||this.isContextLost)return;let e=this.gl;if(e.bindVertexArray(this.vao),this.feedbackProgramEntry&&this.pingPong){e.bindFramebuffer(e.FRAMEBUFFER,this.pingPong[this.writeIdx].fbo),e.viewport(0,0,this.fboW,this.fboH),e.useProgram(this.feedbackProgramEntry.program),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let i=v.getUniformLocation(e,this.feedbackProgramEntry,"uPrevFrame");i&&e.uniform1i(i,0),this.bindCommonUniformsMain(e,this.feedbackProgramEntry,this.fboW,this.fboH),e.drawArrays(e.TRIANGLES,0,3);let t=this.readIdx;this.readIdx=this.writeIdx,this.writeIdx=t,e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,this.canvas.width,this.canvas.height)}if(e.useProgram(this.programEntry.program),this.pingPong){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let i=v.getUniformLocation(e,this.programEntry,"uFeedback");i&&e.uniform1i(i,0);let t=v.getUniformLocation(e,this.programEntry,"uPrevFrame");t&&e.uniform1i(t,0)}this.bindCommonUniformsMain(e,this.programEntry,this.canvas.width,this.canvas.height),e.drawArrays(e.TRIANGLES,0,3)}render(e,i){if(this.isOffscreen||this.isPaused||this.isHiddenByViewport||this.isReducedMotion||this.isContextLost||this.isDestroyed||!this.gl||!this.programEntry)return;let t=performance.now(),r=this.lastRenderNow?t-this.lastRenderNow:16.67;this.lastRenderNow=t;let s=Math.max(.001,Math.min(r*.001,.05));this.lastDeltaSec=s,this.currentSpeed+=(this.targetSpeed-this.currentSpeed)*k(7.5,s),this.elapsedSec+=s*this.currentSpeed;let a=!1;if(this.needsResize&&(this.needsResize=!1,a=!0),this.dynamicRes&&this.dynamicRes.recordFrame(r,t)&&(a=!0),a&&this.applyCanvasSize(),this.mouseActive+=(this.targetMouseActive-this.mouseActive)*k(7,s),this.mouseActive<.001&&this.targetMouseActive===0&&(this.mouseActive=0),this.targetMouseActive>.5){let n=this.mouse[0],l=this.mouse[1],u=k(13,s);this.mouse[0]+=(this.targetMouse[0]-this.mouse[0])*u,this.mouse[1]+=(this.targetMouse[1]-this.mouse[1])*u,this.mouseVel[0]=Math.max(-8,Math.min(8,(this.mouse[0]-n)/s)),this.mouseVel[1]=Math.max(-8,Math.min(8,(this.mouse[1]-l)/s))}else this.mouseVel[0]=0,this.mouseVel[1]=0;if(this.trackScroll){let n=this.scroll;this.scroll+=(this.targetScroll-this.scroll)*k(9.5,s),this.scrollVel=Math.max(-6,Math.min(6,(this.scroll-n)/s))}this.drawMainThreadFrame()}syncDprBounds(){let{minDpr:e,maxDpr:i}=this.resolveDprBounds(),r=this.options.dynamicResolution??!0?e:i;this.isOffscreen&&this.worker?this.worker.postMessage({type:"dprBounds",minDpr:r,maxDpr:i}):this.dynamicRes&&this.dynamicRes.setBounds(r,i)&&(this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0)}watchDevicePixelRatio(){if(this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof window>"u"||typeof window.matchMedia!="function")return;let e=window.devicePixelRatio||1;this.dprMediaQuery=window.matchMedia(`(resolution: ${e}dppx)`),this.dprMediaQuery.addEventListener("change",this.handleDprChange)}updateOptions(e){if(this.isDestroyed)return;let i=this.options.quality;this.options={...this.options,...e};let t=this.seedUniformsFromOptions(e,!1);if((e.quality!==void 0&&e.quality!==i||e.minDpr!==void 0||e.maxDpr!==void 0||e.dynamicResolution!==void 0)&&this.syncDprBounds(),typeof e.interactive=="boolean"&&e.interactive!==this.interactive&&(this.interactive=e.interactive,this.syncPointerListener()),typeof e.trackScroll=="boolean"&&e.trackScroll!==this.trackScroll&&(this.trackScroll=e.trackScroll,this.syncScrollListener()),typeof e.respectReducedMotion=="boolean"){this.respectReducedMotion=e.respectReducedMotion;let r=this.reducedMotionQuery?.matches??!1;this.applyReducedMotionState(this.respectReducedMotion&&r)}this.isOffscreen&&this.worker?Object.keys(t).length>0&&this.worker.postMessage({type:"uniformsBatch",uniforms:t}):this.isReducedMotion&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame())}applyReducedMotionState(e){this.isReducedMotion!==e&&(this.isReducedMotion=e,this.lastRenderNow=0,this.isOffscreen&&this.worker?this.worker.postMessage({type:"reducedMotion",value:e}):e&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame()))}getLocalPointerCoords(e){let i=this.container.getBoundingClientRect();if(i.width<=0||i.height<=0||e.clientX<i.left||e.clientX>i.right||e.clientY<i.top||e.clientY>i.bottom)return null;let t=(e.clientX-i.left)/i.width,r=1-(e.clientY-i.top)/i.height;return[t,r]}syncPointerListener(){this.interactive&&!this.hasPointerListener?(this.container.addEventListener("pointerenter",this.handlePointerEnter,{passive:!0}),this.container.addEventListener("pointermove",this.handlePointerMove,{passive:!0}),this.container.addEventListener("pointerleave",this.handlePointerLeave,{passive:!0}),this.container.addEventListener("pointerdown",this.handlePointerDown,{passive:!0}),window.addEventListener("pointerup",this.handlePointerUp,{passive:!0}),window.addEventListener("pointercancel",this.handlePointerUp,{passive:!0}),this.hasPointerListener=!0):!this.interactive&&this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.handlePointerLeave(),this.hasPointerListener=!1)}syncScrollListener(){this.trackScroll&&!this.hasScrollListener?(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.hasScrollListener=!0,this.handleScroll()):!this.trackScroll&&this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1)}bindObservers(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(i=>{let t=i[0];if(!t)return;let r=Math.max(1,Math.floor(t.contentRect.width)),s=Math.max(1,Math.floor(t.contentRect.height));r===this.width&&s===this.height||(this.width=r,this.height=s,this.trackScroll&&this.handleScroll(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"resize",width:this.width,height:this.height}):this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0)}),this.resizeObserver.observe(this.container)),e&&typeof IntersectionObserver<"u"&&(this.visibilityObserver=new IntersectionObserver(i=>{let t=i[0]?.isIntersecting??!0;this.isHiddenByViewport=!t,t||this.handlePointerLeave(),this.isOffscreen&&this.worker?this.worker.postMessage({type:t&&!this.isPaused?"resume":"pause"}):t||(this.lastRenderNow=0)},{rootMargin:"50px"}),this.visibilityObserver.observe(this.container)),this.reducedMotionQuery&&this.reducedMotionQuery.addEventListener("change",this.handleReducedMotionChange),this.isOffscreen&&typeof document<"u"&&document.addEventListener("visibilitychange",this.handleDocVisibility),this.watchDevicePixelRatio(),this.syncPointerListener(),this.syncScrollListener()}setUniform(e,i){this.isDestroyed||(this.customUniforms.set(e,i),e==="uSpeed"&&typeof i=="number"&&(this.targetSpeed=i),this.isOffscreen&&this.worker?this.worker.postMessage({type:"uniform",name:e,value:typeof i=="number"?i:Array.from(i)}):this.isReducedMotion&&this.drawMainThreadFrame())}setColor(e,i){let t=c(i,"#ffffff"),r=g.hexToVec3Into(t,g.scratchVec3);this.setUniform(e,[r[0],r[1],r[2]])}pause(){this.isPaused||this.isDestroyed||(this.isPaused=!0,this.lastRenderNow=0,this.handlePointerLeave(),this.isOffscreen&&this.worker&&this.worker.postMessage({type:"pause"}))}resume(){!this.isPaused||this.isDestroyed||(this.isPaused=!1,this.lastRenderNow=0,this.isOffscreen&&this.worker&&!this.isHiddenByViewport?this.worker.postMessage({type:"resume"}):this.isReducedMotion&&!this.isHiddenByViewport&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame()))}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.visibilityObserver?.disconnect(),this.visibilityObserver=null,this.reducedMotionQuery&&(this.reducedMotionQuery.removeEventListener("change",this.handleReducedMotionChange),this.reducedMotionQuery=null),this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleDocVisibility),this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.hasPointerListener=!1),this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1),this.canvas.removeEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored,!1),this.isOffscreen&&this.worker&&(this.worker.postMessage({type:"destroy"}),this.worker=null),this.gl&&(this.destroyPingPongMain(),this.vbo&&this.gl.deleteBuffer(this.vbo),this.vao&&this.gl.deleteVertexArray(this.vao),v.disposeContext(this.gl),this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null),this.markContextReleased(),g.releaseVec2(this.mouse),g.releaseVec2(this.targetMouse),g.releaseVec2(this.mouseVel),this.customUniforms.clear(),this.canvas.remove())}};R._activeContexts=0;var x=R;var U=class{constructor(){this.plugins=new Map;this.activeByElement=new WeakMap;this.activeSet=new Set;this.visibilityObserver=null;this.visibilityCallbacks=new WeakMap;this.removeTicker=null}ensureObserver(){return typeof window>"u"||typeof IntersectionObserver>"u"?null:(this.visibilityObserver||(this.visibilityObserver=new IntersectionObserver(e=>{for(let i=0;i<e.length;i++){let t=e[i],r=this.visibilityCallbacks.get(t.target);r&&r.forEach(s=>s(t.isIntersecting))}},{rootMargin:"50px"})),this.visibilityObserver)}ensureTicker(){this.removeTicker||(this.removeTicker=B.add((e,i)=>{this.activeSet.forEach(t=>{if(!(!t.visible||t.faulted||!t.instance.update))try{t.instance.update(e,i)}catch(r){t.faulted=!0,console.error(`[FluxFX] Runtime error in "${t.name}" (auto-paused):`,r)}})}))}stopTickerIfEmpty(){this.activeSet.size===0&&this.removeTicker&&(this.removeTicker(),this.removeTicker=null)}register(e){return this.plugins.set(e.name,e),this}has(e){return this.plugins.has(e)}getStats(){let e=0;this.activeSet.forEach(t=>{t.visible&&e++});let i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;return{mounted:this.activeSet.size,visible:e,activeLoops:B.isRunning?1:0,registered:this.plugins.size,webglContexts:x.activeContexts,reducedMotion:i}}apply(e,i,t={}){let r=this.plugins.get(i);if(!r)return console.warn(`[FluxFX] Effect "${i}" is not registered.`),()=>{};let s=this.activeByElement.get(e);s||(s=new Map,this.activeByElement.set(e,s));let a=s.get(i);a&&a.destroy();let n;try{n=r.mount(e,t)}catch(h){return console.error(`[FluxFX] Failed to mount "${i}":`,h),()=>{}}let l=t.pauseWhenHidden??!0,u=null,d=!1,f={el:e,name:i,plugin:r,instance:n,visible:!0,faulted:!1,destroy:()=>{if(!d){d=!0,u?.(),this.activeSet.delete(f),s?.delete(i);try{f.instance.destroy()}catch(h){console.error(`[FluxFX] Cleanup error in "${i}":`,h)}this.stopTickerIfEmpty()}}};if(l){let h=this.ensureObserver();if(h){let m=this.visibilityCallbacks.get(e);m||(m=new Set,this.visibilityCallbacks.set(e,m),h.observe(e));let p=b=>{f.visible=b,b?f.instance.resume?.():f.instance.pause?.()};m.add(p),u=()=>{m?.delete(p),m&&m.size===0&&(h.unobserve(e),this.visibilityCallbacks.delete(e))}}}return s.set(i,f),this.activeSet.add(f),f.instance.update&&this.ensureTicker(),f.destroy}update(e,i,t={}){let s=this.activeByElement.get(e)?.get(i);if(!s)return!1;if(s.instance.setOptions)try{return s.instance.setOptions(t),!0}catch(a){return console.error(`[FluxFX] Hot-update error in "${i}":`,a),!1}try{return s.instance.destroy(),s.instance=s.plugin.mount(e,t),s.faulted=!1,s.visible||s.instance.pause?.(),s.instance.update&&this.ensureTicker(),!0}catch(a){return s.faulted=!0,console.error(`[FluxFX] Fallback remount error in "${i}":`,a),!1}}scan(e=document){if(typeof document>"u")return;e.querySelectorAll("[data-fx]").forEach(t=>{let r=t.getAttribute("data-fx");if(!r)return;let s=r.trim().split(/\s+/).filter(Boolean),a=this.parseDatasetOptions(t),n=this.activeByElement.get(t);s.forEach(l=>{n?.has(l)||this.apply(t,l,a)})})}init(e){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.scan(e??document),{once:!0}):this.scan(e??document))}destroyAll(){let e=Array.from(this.activeSet);for(let i=0;i<e.length;i++)e[i].destroy()}parseDatasetOptions(e){let i={};for(let[t,r]of Object.entries(e.dataset)){if(!t.startsWith("fx")||t==="fx"||r===void 0)continue;let s=t.slice(2),a=s.charAt(0).toLowerCase()+s.slice(1);r==="true"?i[a]=!0:r==="false"?i[a]=!1:r!==""&&!Number.isNaN(Number(r))?i[a]=Number(r):i[a]=r}return i}},_=new U;var be=`#version 300 es
791
+ `,se=null;function oe(){if(typeof window>"u"||typeof Worker>"u"||typeof OffscreenCanvas>"u"||typeof HTMLCanvasElement>"u"||!("transferControlToOffscreen"in HTMLCanvasElement.prototype))return!1;let o=typeof navigator<"u"?navigator.userAgent:"";return!(/iP(ad|hone|od)/i.test(o)||/^((?!chrome|android).)*safari/i.test(o))}function Te(){if(!se){let o=new Blob([Ue],{type:"application/javascript"});se=URL.createObjectURL(o)}return new Worker(se)}var xe=N;var G={low:{max:1,min:.65,retinaMin:.85,fboMaxDim:512},medium:{max:2,min:.75,retinaMin:1,fboMaxDim:896},high:{max:2,min:1,retinaMin:1.25,fboMaxDim:1152}},_e=new Float32Array([-1,-1,3,-1,-1,3]),Ie=12;function Ce(){if(typeof navigator>"u")return!1;let o=navigator.userAgent||"";return/Safari/i.test(o)&&!/Chrome|Chromium|Edg|CriOS|FxiOS|OPR/i.test(o)}function Me(){if(typeof navigator>"u")return 8;let o=navigator.userAgent||"",e=/Mobi|Android|iPhone|iPad|iPod/i.test(o);return Ce()||e?6:8}function Q(){return typeof performance<"u"?performance.now():Date.now()}var ae=30,ne=60,X=1800;function Y(o,e){return 1-Math.exp(-o*e)}var w=class w{constructor(e,t){this.resizeObserver=null;this.visibilityObserver=null;this.reducedMotionQuery=null;this.dprMediaQuery=null;this.worker=null;this.isOffscreen=!1;this.gl=null;this.programEntry=null;this.feedbackProgramEntry=null;this.vao=null;this.vbo=null;this.dynamicRes=null;this.lastRenderNow=0;this.lastDrawNow=0;this.lastTargetFps=0;this.prevFrameDrew=!1;this.avgDrawDeltaMs=0;this.boostUntil=0;this.reportedFps=0;this.reportedFrameTimeMs=0;this.elapsedSec=0;this.lastDeltaSec=.01667;this.currentSpeed=1;this.targetSpeed=1;this.needsResize=!1;this.pingPong=null;this.fboW=1;this.fboH=1;this.fboFormat=0;this.fboType=0;this.readIdx=0;this.writeIdx=1;this.customUniforms=new Map;this.mouse=T.acquireVec2(.5,.5);this.targetMouse=T.acquireVec2(.5,.5);this.mouseVel=T.acquireVec2(0,0);this.mouseDown=0;this.mouseActive=0;this.targetMouseActive=0;this.isPointerInside=!1;this.scroll=0;this.targetScroll=0;this.scrollVel=0;this.hasScrollListener=!1;this.width=1;this.height=1;this.isPaused=!1;this.isHiddenByViewport=!1;this.isContextLost=!1;this.isReducedMotion=!1;this.isDestroyed=!1;this.wakeCallback=null;this.ambientFps=ae;this.activeFps=ne;this.protectionTier=D.tier;this.isSurvivalSuspended=!1;this.unsubscribeGuard=null;this.isBudgetSuspended=!1;this.lastActiveAt=Q();this.hasDocVisibilityListener=!1;this.hasPointerListener=!1;this.countedContext=!1;this.isBodyMount=!1;this.origBodyMinHeight="";this.themeMode="auto";this.resolvedDarkTheme=!0;this.currentTheme=1;this.themeTweenRaf=0;this.colorSchemeQuery=null;this.themeMutationObserver=null;this.basePaletteRgb=[];this.activePaletteRgb=[];this.scrollStopsRgb=[];this.lastScrollColorT=-1;this.hasScrollColorListener=!1;this.scrollColorRaf=0;this.hasTouchListener=!1;this.touchBurstTimer=0;this.touchLeaveTimer=0;this.layerMode="background";this.adaptToSurface=!1;this.rawBasePaletteRgb=[];this.lastSurfaceEl=null;this.lastSurfaceKey="";this.lastSurfaceCheckAt=0;this.isSurfaceAdapted=!1;this.handleThemeChange=()=>{if(this.isDestroyed)return;let e=this.detectDarkTheme(this.themeMode);e!==this.resolvedDarkTheme&&(this.resolvedDarkTheme=e,this.startThemeTransition(e))};this.handleScrollColorEvent=()=>{this.isDestroyed||this.scrollStopsRgb.length<2||this.scrollColorRaf||(this.scrollColorRaf=requestAnimationFrame(()=>{if(this.scrollColorRaf=0,this.isDestroyed||this.scrollStopsRgb.length<2)return;let e=this.computeScrollProgress();this.updateScrollColorShift(e)}))};this.handleTouchStart=e=>{if(!this.interactive||this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let t=e.touches[0];if(!t)return;if(this.isShadowedByChildInteractive(t.target)){this.isPointerInside&&this.handlePointerLeave();return}let i=this.getLocalTouchCoords(t);if(!i)return;this.touchLeaveTimer&&(window.clearTimeout(this.touchLeaveTimer),this.touchLeaveTimer=0),this.touchBurstTimer&&(window.clearTimeout(this.touchBurstTimer),this.touchBurstTimer=0);let[r,s]=i;this.inspectSurfaceFromTarget(t.target,!0),this.isPointerInside=!0,this.targetMouseActive=1,this.mouseDown=1,this.boostInteraction(X),this.isOffscreen&&this.worker?(this.worker.postMessage({type:"mouseEnter",x:r,y:s}),this.worker.postMessage({type:"mouseDown",down:!0})):(this.mouse[0]=r,this.mouse[1]=s,this.targetMouse[0]=r,this.targetMouse[1]=s,this.mouseVel[0]=0,this.mouseVel[1]=0),this.touchBurstTimer=window.setTimeout(()=>{this.touchBurstTimer=0,!this.isDestroyed&&(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}))},160)};this.handleTouchMove=e=>{if(!this.interactive||this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let t=e.touches[0];if(!t)return;if(this.isShadowedByChildInteractive(t.target)){this.isPointerInside&&this.handlePointerLeave();return}let i=this.getLocalTouchCoords(t);if(!i)return;let[r,s]=i;this.inspectSurfaceFromTarget(t.target),this.boostInteraction(X),this.targetMouseActive=1,this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouse",x:r,y:s}):(this.targetMouse[0]=r,this.targetMouse[1]=s)};this.handleTouchEnd=()=>{this.isDestroyed||(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}),this.touchLeaveTimer&&window.clearTimeout(this.touchLeaveTimer),this.touchLeaveTimer=window.setTimeout(()=>{this.touchLeaveTimer=0,this.isDestroyed||this.handlePointerLeave()},550))};this.handleContextLost=e=>{e.preventDefault(),this.isContextLost=!0,this.resetFrameTracking(),this.gl&&x.disposeContext(this.gl),this.programEntry=null,this.feedbackProgramEntry=null,this.pingPong=null,this.vao=null,this.vbo=null,this.wakeCallback?.()};this.handleContextRestored=()=>{if(!(this.isDestroyed||!this.gl))try{this.isContextLost=!1,this.initMainThreadPipeline(this.gl),this.drawMainThreadFrame(),this.wakeCallback?.()}catch(e){console.error("[FluxFX] Failed to restore WebGL2 context:",e)}};this.handleProtectionTierChange=e=>{this.isDestroyed||this.protectionTier===e||(this.protectionTier=e,this.applyProtectionState(),this.isDestroyed||this.pushUniformBatch({uQuality:this.computeEffectiveQuality()}))};this.handleDprChange=()=>{this.isDestroyed||(this.syncDprBounds(),this.watchDevicePixelRatio())};this.handleReducedMotionChange=e=>{this.applyReducedMotionState(this.respectReducedMotion&&e.matches)};this.handlePointerEnter=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;if(this.isShadowedByChildInteractive(e.target)){this.isPointerInside&&this.handlePointerLeave();return}let t=this.getLocalPointerCoords(e);if(!t)return;let[i,r]=t;this.isPointerInside=!0,this.targetMouseActive=1,this.boostInteraction(X),this.protectionTier>=3&&this.applyProtectionState(),this.lastActiveAt=Q(),this.isBudgetSuspended&&!this.isPaused&&this.restoreContextFromBudget(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouseEnter",x:i,y:r}):(this.mouse[0]=i,this.mouse[1]=r,this.targetMouse[0]=i,this.targetMouse[1]=r,this.mouseVel[0]=0,this.mouseVel[1]=0)};this.handlePointerMove=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;if(this.isShadowedByChildInteractive(e.target)){this.isPointerInside&&this.handlePointerLeave();return}let t=this.getLocalPointerCoords(e);if(!t){this.isPointerInside&&this.handlePointerLeave();return}let[i,r]=t;if(!this.isPointerInside){this.handlePointerEnter(e),this.inspectSurfaceFromTarget(e.target,!0);return}this.inspectSurfaceFromTarget(e.target),this.boostInteraction(X),this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouse",x:i,y:r}):(this.targetMouse[0]=i,this.targetMouse[1]=r)};this.handlePointerLeave=()=>{!this.isPointerInside&&this.targetMouseActive===0||(this.isPointerInside=!1,this.targetMouseActive=0,this.lastSurfaceEl=null,this.lastSurfaceKey="",this.isSurfaceAdapted&&(this.isSurfaceAdapted=!1,this.startPaletteTween(this.basePaletteRgb,240)),this.mouseDown=0,this.mouseVel[0]=0,this.mouseVel[1]=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseLeave"}),this.protectionTier>=3&&this.applyProtectionState())};this.handlePointerDown=e=>{if(!(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)){if(this.isShadowedByChildInteractive(e.target)){this.isPointerInside&&this.handlePointerLeave();return}this.isPointerInside||this.handlePointerEnter(e),this.mouseDown=1,this.boostInteraction(X),this.protectionTier>=3&&this.applyProtectionState(),this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!0})}};this.handlePointerUp=()=>{this.mouseDown!==0&&(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}),this.protectionTier>=3&&this.applyProtectionState())};this.handleScroll=()=>{if(!this.trackScroll||this.isDestroyed)return;let e=this.computeScrollProgress();this.boostInteraction(1200),this.isOffscreen&&this.worker?this.worker.postMessage({type:"scroll",progress:e}):(this.targetScroll=e,this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport&&(this.scroll=e,this.scrollVel=0,this.drawMainThreadFrame()))};this.handleDocVisibility=()=>{!this.isOffscreen||!this.worker||(document.hidden?(this.resetFrameTracking(),this.worker.postMessage({type:"pause"})):!this.isPaused&&!this.isHiddenByViewport&&this.worker.postMessage({type:"resume"}))};this.container=e,this.options={...t},this.interactive=t.interactive??!0,this.respectReducedMotion=t.respectReducedMotion??!0,this.trackScroll=t.trackScroll??!1,this.feedbackScale=t.feedbackScale??.5,this.feedbackFloat=t.feedbackFloat??!0,w.instances.add(this);let i=t.quality??"medium",r=G[i]??G.medium;this.baseFeedbackMaxDim=t.feedbackMaxDim??r.fboMaxDim;let s=this.resolveTierConfig();this.ambientFps=s.ambientFps,this.activeFps=s.activeFps,this.feedbackMaxDim=s.feedbackMaxDim,this.isSurvivalSuspended=s.suspended,typeof window<"u"&&typeof window.matchMedia=="function"&&(this.reducedMotionQuery=window.matchMedia("(prefers-reduced-motion: reduce)"),this.isReducedMotion=this.respectReducedMotion&&this.reducedMotionQuery.matches),this.isBodyMount=typeof document<"u"&&this.container===document.body,window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.container.style.isolation="isolate",this.isBodyMount&&(this.origBodyMinHeight=this.container.style.minHeight,this.container.style.minHeight||(this.container.style.minHeight="100dvh")),this.canvas=document.createElement("canvas"),this.canvas.setAttribute("data-fluxfx-canvas","true"),this.canvas.style.position=this.isBodyMount?"fixed":"absolute",this.canvas.style.inset="0",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.zIndex="-1",this.canvas.style.pointerEvents="none",this.canvas.style.display="block",this.container.prepend(this.canvas),this.layerMode=t.layer??"background",this.adaptToSurface=t.adaptToSurface??!1,this.applyCanvasLayerStyle(),this.themeMode=t.theme??"auto",this.resolvedDarkTheme=this.detectDarkTheme(this.themeMode),this.currentTheme=this.resolvedDarkTheme?1:0;let n=this.container.getBoundingClientRect();if(this.width=Math.max(1,Math.floor(n.width)),this.height=Math.max(1,Math.floor(n.height)),this.trackScroll){let p=this.computeScrollProgress();this.scroll=p,this.targetScroll=p}let{minDpr:l,maxDpr:c}=this.resolveDprBounds(),u=t.dynamicResolution??!0,h=t.offscreen??!0;this.seedUniformsFromOptions(t,!0);let f=typeof window<"u"&&window.innerHeight||0,d=typeof window<"u"&&window.innerWidth||0,m=(t.pauseWhenHidden??!0)&&f>0&&(n.bottom<-50||n.top>f+50||n.right<-50||n.left>d+50);m&&(this.isHiddenByViewport=!0),w.ensureContextBudget(this,m)?h&&oe()?this.initOffscreenMode(t,l,c,u):this.initMainThreadMode(t,l,c,u):(this.isBudgetSuspended=!0,this.applyBudgetFallbackStyle()),this.bindObservers(t.pauseWhenHidden??!0),this.unsubscribeGuard=D.onTierChange(this.handleProtectionTierChange)}static acquireRecycledMainContext(){for(;this.recycledMainContexts.length>0;){let e=this.recycledMainContexts.pop();if(!e.gl.isContextLost())return e}return null}static recycleMainContext(e,t){let i=Math.max(this._maxContexts,Me());return this.recycledMainContexts.length>=i?!1:(this.recycledMainContexts.push({canvas:e,gl:t}),!0)}static get activeContexts(){return this._activeContexts}static get maxActiveContexts(){return this._maxContexts}static get suspendedContexts(){let e=0;return this.instances.forEach(t=>{!t.isDestroyed&&t.isBudgetSuspended&&e++}),e}static setMaxActiveContexts(e){let t=Math.max(1,Math.floor(e));t!==this._maxContexts&&(this._maxContexts=t,this.enforceContextBudget(),this.reclaimBudgetForWaiting())}static pickEvictionVictim(e,t){let i=null,r=null;return this.instances.forEach(s=>{s===e||s.isDestroyed||s.isBudgetSuspended||!s.countedContext||(s.isHiddenByViewport||s.isPaused?(!i||s.lastActiveAt<i.lastActiveAt)&&(i=s):t&&!s.isPointerInside&&s.mouseDown===0&&(!r||s.lastActiveAt<r.lastActiveAt)&&(r=s))}),i??r}static ensureContextBudget(e,t){if(this._activeContexts<this._maxContexts)return!0;if(t)return!1;let i=this.pickEvictionVictim(e,!0);return i?(i.suspendContextForBudget(),this._activeContexts<this._maxContexts):!1}static enforceContextBudget(){for(;this._activeContexts>this._maxContexts;){let e=this.pickEvictionVictim(null,!0);if(!e)break;e.suspendContextForBudget()}}static reclaimBudgetForWaiting(){for(;this._activeContexts<this._maxContexts;){let e=null;if(this.instances.forEach(t=>{t.isDestroyed||!t.isBudgetSuspended||t.isPaused||t.isHiddenByViewport||(!e||t.lastActiveAt>e.lastActiveAt)&&(e=t)}),!e||!e.restoreContextFromBudget())break}}static getRenderStats(){let e=0,t=0,i=0;return this.instances.forEach(r=>{r.isDestroyed||r.isPaused||r.isHiddenByViewport||r.isReducedMotion||r.isContextLost||r.isSurvivalSuspended||r.reportedFps>0&&(e++,r.reportedFps>t&&(t=r.reportedFps,i=r.reportedFrameTimeMs))}),{activeRendering:e,fps:t,frameTimeMs:i}}boostInteraction(e=X){let t=performance.now()+e;t>this.boostUntil&&(this.boostUntil=t)}resetFrameTracking(){this.lastRenderNow=0,this.lastDrawNow=0,this.lastTargetFps=0,this.prevFrameDrew=!1,this.avgDrawDeltaMs=0,this.reportedFps=0,this.reportedFrameTimeMs=0}resolveTierConfig(){let e=this.baseFeedbackMaxDim;return this.protectionTier===1?{ambientFps:ae,activeFps:ne,feedbackMaxDim:Math.max(256,Math.round(e*.75)),suspended:!1}:this.protectionTier===2?{ambientFps:20,activeFps:30,feedbackMaxDim:Math.max(256,Math.round(e*.55)),suspended:!1}:this.protectionTier>=3?{ambientFps:15,activeFps:30,feedbackMaxDim:Math.max(256,Math.round(e*.5)),suspended:!this.isPointerInside&&this.mouseDown===0}:{ambientFps:ae,activeFps:ne,feedbackMaxDim:e,suspended:!1}}resolveDprBounds(){let e=this.options.quality??"medium",t=G[e]??G.medium,i=typeof window<"u"&&window.devicePixelRatio||1,r=i>=1.5,s=this.options.maxDpr??Math.min(i,t.max),a=r?t.retinaMin:t.min,n=this.options.minDpr??Math.min(a,s);if(this.protectionTier===1){let l=Math.max(.65,Number((s*.75).toFixed(2)));return{minDpr:Math.min(n,l),maxDpr:l}}if(this.protectionTier>=2){let l=Math.max(.55,Math.min(n,Number((s*.6).toFixed(2))));return{minDpr:l,maxDpr:l}}return{minDpr:n,maxDpr:s}}computeScrollProgress(){if(typeof window>"u")return 0;let e=this.container.getBoundingClientRect(),t=window.innerHeight||1,i=t+e.height;return i<=0?0:Math.min(1,Math.max(0,(t-e.top)/i))}markContextActive(){this.countedContext||(this.countedContext=!0,w._activeContexts++,w._activeContexts>Ie&&console.warn(`[FluxFX] ${w._activeContexts} active WebGL contexts detected. Browsers typically cap contexts around 8\u201316; consider limiting simultaneous WebGL backgrounds.`))}markContextReleased(){this.countedContext&&(this.countedContext=!1,w._activeContexts=Math.max(0,w._activeContexts-1))}uniformVec3Css(e,t,i=1){let r=this.customUniforms.get(e),s=t[0],a=t[1],n=t[2];return r&&typeof r!="number"&&r.length>=3&&(s=Math.round(Math.min(1,Math.max(0,r[0]))*255),a=Math.round(Math.min(1,Math.max(0,r[1]))*255),n=Math.round(Math.min(1,Math.max(0,r[2]??0))*255)),i<1?`rgba(${s}, ${a}, ${n}, ${i})`:`rgb(${s}, ${a}, ${n})`}applyBudgetFallbackStyle(){if(this.isDestroyed)return;let e=this.customUniforms.get("uTransparentBg"),t=typeof e=="number"&&e>.5,i=this.customUniforms.get("uBgColor"),r=i&&typeof i!="number"&&i.length>=3&&i[0]+i[1]+(i[2]??0)>.003,s=this.uniformVec3Css("uColor1",[99,102,241],t?.38:.45),a=this.uniformVec3Css("uColor2",[6,182,212],t?.32:.38),n=this.uniformVec3Css("uColor3",[244,63,94],t?.22:.28),l=t?"transparent":r?this.uniformVec3Css("uBgColor",[6,8,16],1):"#070a14";this.canvas.style.background=`radial-gradient(circle at 22% 28%, ${s}, transparent 60%), radial-gradient(circle at 78% 72%, ${a}, transparent 62%), radial-gradient(circle at 55% 45%, ${n}, transparent 68%), ${l}`}syncDocVisibilityListener(){typeof document>"u"||(this.isOffscreen&&!this.hasDocVisibilityListener?(document.addEventListener("visibilitychange",this.handleDocVisibility),this.hasDocVisibilityListener=!0):!this.isOffscreen&&this.hasDocVisibilityListener&&(document.removeEventListener("visibilitychange",this.handleDocVisibility),this.hasDocVisibilityListener=!1))}releaseMainThreadContext(e){if(!this.gl){e||this.canvas.remove();return}let t=this.gl;if(t.isContextLost())this.pingPong=null,x.disposeContext(t),e||this.canvas.remove();else{this.destroyPingPongMain(),this.vbo&&t.deleteBuffer(this.vbo),this.vao&&t.deleteVertexArray(this.vao),x.disposeContext(t),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.useProgram(null),t.viewport(0,0,1,1),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),this.canvas.width=1,this.canvas.height=1;let r=this.canvas;if(e){let s=this.canvas.cloneNode(!1);this.canvas.replaceWith(s),this.canvas=s}else this.canvas.remove();!w.recycleMainContext(r,t)&&!Ce()&&t.getExtension("WEBGL_lose_context")?.loseContext()}this.gl=null}suspendContextForBudget(){this.isDestroyed||this.isBudgetSuspended||(this.isBudgetSuspended=!0,this.resetFrameTracking(),this.canvas.removeEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored,!1),this.isOffscreen&&this.worker&&(this.worker.postMessage({type:"destroy"}),this.worker=null),this.isOffscreen=!1,this.syncDocVisibilityListener(),this.releaseMainThreadContext(!0),this.programEntry=null,this.feedbackProgramEntry=null,this.vao=null,this.vbo=null,this.dynamicRes=null,this.isContextLost=!1,this.markContextReleased(),this.applyBudgetFallbackStyle(),this.wakeCallback?.())}restoreContextFromBudget(){if(this.isDestroyed||!this.isBudgetSuspended||!w.ensureContextBudget(this,!1))return!1;let e=this.canvas.cloneNode(!1);e.style.background="",this.canvas.replaceWith(e),this.canvas=e;let t=this.container.getBoundingClientRect();this.width=Math.max(1,Math.floor(t.width)),this.height=Math.max(1,Math.floor(t.height));let{minDpr:i,maxDpr:r}=this.resolveDprBounds(),s=this.options.dynamicResolution??!0,a=this.options.offscreen??!0;return this.isBudgetSuspended=!1,this.isContextLost=!1,this.lastActiveAt=Q(),a&&oe()?this.initOffscreenMode(this.options,i,r,s):this.initMainThreadMode(this.options,i,r,s),this.syncDocVisibilityListener(),this.wakeCallback?.(),this.countedContext}computeEffectiveQuality(){let e=this.options.quality??"medium",t=e==="high"?1:e==="low"?0:.5;return this.protectionTier>=2?t=0:this.protectionTier===1&&(t=Math.min(t,.5)),t}shouldPreserveBg(){return typeof this.options.preserveBg=="boolean"?this.options.preserveBg:this.layerMode==="overlay"}applyCanvasLayerStyle(){if(this.layerMode==="overlay"){this.canvas.style.zIndex="10";let e=typeof this.options.overlayOpacity=="number"?Math.max(.05,Math.min(1,this.options.overlayOpacity)):.78;this.canvas.style.opacity=String(e)}else this.canvas.style.zIndex="-1",this.canvas.style.opacity="1"}startPaletteTween(e,t=220){if(e.length===0)return;this.themeTweenRaf&&(cancelAnimationFrame(this.themeTweenRaf),this.themeTweenRaf=0);let i=this.toTriplet(this.activePaletteRgb.length>0?this.activePaletteRgb:this.basePaletteRgb),r=this.toTriplet(e);if(this.isReducedMotion||typeof requestAnimationFrame!="function"){this.activePaletteRgb=r,this.pushUniformBatch({uColor1:r[0],uColor2:r[1],uColor3:r[2]});return}let s=performance.now();this.boostInteraction(420);let a=n=>{if(this.isDestroyed){this.themeTweenRaf=0;return}let l=Math.min(1,(n-s)/t),c=l<.5?2*l*l:1-Math.pow(-2*l+2,2)/2,u=(m,p)=>[m[0]+(p[0]-m[0])*c,m[1]+(p[1]-m[1])*c,m[2]+(p[2]-m[2])*c],h=u(i[0],r[0]),f=u(i[1],r[1]),d=u(i[2],r[2]);this.activePaletteRgb=[h,f,d],this.pushUniformBatch({uColor1:h,uColor2:f,uColor3:d}),l<1?this.themeTweenRaf=requestAnimationFrame(a):this.themeTweenRaf=0};this.themeTweenRaf=requestAnimationFrame(a)}inspectSurfaceFromTarget(e,t=!1){if(!this.adaptToSurface||this.isDestroyed)return;let i=e instanceof HTMLElement?e:null,r=performance.now();if(!t&&i===this.lastSurfaceEl&&r-this.lastSurfaceCheckAt<180)return;this.lastSurfaceEl=i,this.lastSurfaceCheckAt=r;let s=be(i,this.container);if(!s){this.isSurfaceAdapted&&(this.isSurfaceAdapted=!1,this.lastSurfaceKey="",this.startPaletteTween(this.basePaletteRgb,220));return}let a=`${Math.round(s[0]*255)},${Math.round(s[1]*255)},${Math.round(s[2]*255)}`;if(!t&&a===this.lastSurfaceKey)return;this.lastSurfaceKey=a;let n=this.rawBasePaletteRgb.length>0?this.rawBasePaletteRgb:this.basePaletteRgb;if(n.length===0)return;let l=ye(n,[s[0],s[1],s[2]]);this.isSurfaceAdapted=!0,this.startPaletteTween(l,220)}parseColorList(e){if(!e)return[];let t=Array.isArray(e)?e:String(e).split(",").map(s=>s.trim()).filter(Boolean);if(t.length===0)return[];let i=M(t[0],"#6366f1"),r=[];for(let s=0;s<t.length;s++){let a=M(t[s],i),n=T.hexToVec3Into(a,T.scratchVec3);r.push([n[0],n[1],n[2]])}return r}parseScrollStops(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let i=0;i<e.length;i++){let r=e[i],s=Array.isArray(r)?r[0]:r;if(typeof s=="string"&&s.trim()){let a=M(s,"#6366f1"),n=T.hexToVec3Into(a,T.scratchVec3);t.push([n[0],n[1],n[2]])}}return t}detectDarkTheme(e){return e==="dark"?!0:e==="light"?!1:ve(this.container)}resolveTargetPalette(e){let t=e?this.parseColorList(this.options.darkColors):this.parseColorList(this.options.lightColors);if(t.length>0)return t;let i=this.parseColorList(this.options.colors);return i.length>0?K(i,e):this.basePaletteRgb}toTriplet(e){let t=e[0]??[.39,.4,.95],i=e[1]??t,r=e[2]??i;return[[t[0],t[1],t[2]],[i[0],i[1],i[2]],[r[0],r[1],r[2]]]}pushUniformBatch(e){if(!this.isDestroyed){for(let[t,i]of Object.entries(e))this.customUniforms.set(t,i);if(this.isBudgetSuspended){this.applyBudgetFallbackStyle();return}this.isOffscreen&&this.worker?this.worker.postMessage({type:"uniformsBatch",uniforms:e}):this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport&&this.drawMainThreadFrame()}}startThemeTransition(e){this.themeTweenRaf&&(cancelAnimationFrame(this.themeTweenRaf),this.themeTweenRaf=0);let t=e?1:0,i=this.resolveTargetPalette(e);i.length>0&&(this.basePaletteRgb=i);let r=this.currentTheme,s=this.toTriplet(this.activePaletteRgb.length>0?this.activePaletteRgb:this.basePaletteRgb),a=this.toTriplet(this.basePaletteRgb);if(this.isReducedMotion||typeof requestAnimationFrame!="function"){this.currentTheme=t,this.activePaletteRgb=a,this.pushUniformBatch({uTheme:t,uColor1:a[0],uColor2:a[1],uColor3:a[2]});return}let n=performance.now(),l=280;this.boostInteraction(500);let c=u=>{if(this.isDestroyed){this.themeTweenRaf=0;return}let h=Math.min(1,(u-n)/l),f=h<.5?2*h*h:1-Math.pow(-2*h+2,2)/2;this.currentTheme=r+(t-r)*f;let d=(g,b)=>[g[0]+(b[0]-g[0])*f,g[1]+(b[1]-g[1])*f,g[2]+(b[2]-g[2])*f],m=d(s[0],a[0]),p=d(s[1],a[1]),v=d(s[2],a[2]);this.activePaletteRgb=[m,p,v],this.pushUniformBatch({uTheme:this.currentTheme,uColor1:m,uColor2:p,uColor3:v}),h<1?this.themeTweenRaf=requestAnimationFrame(c):(this.themeTweenRaf=0,this.scrollStopsRgb.length>=2&&(this.lastScrollColorT=-1,this.updateScrollColorShift(this.computeScrollProgress())))};this.themeTweenRaf=requestAnimationFrame(c)}bindThemeWatchers(){if(this.unbindThemeWatchers(),!(typeof window>"u"||typeof document>"u")&&(typeof window.matchMedia=="function"&&(this.colorSchemeQuery=window.matchMedia("(prefers-color-scheme: dark)"),typeof this.colorSchemeQuery.addEventListener=="function"&&this.colorSchemeQuery.addEventListener("change",this.handleThemeChange)),typeof MutationObserver<"u")){this.themeMutationObserver=new MutationObserver(this.handleThemeChange);let e=["class","data-theme","data-mode","data-bs-theme","style"];this.themeMutationObserver.observe(document.documentElement,{attributes:!0,attributeFilter:e}),document.body&&this.themeMutationObserver.observe(document.body,{attributes:!0,attributeFilter:e}),this.container!==document.body&&this.container!==document.documentElement&&this.themeMutationObserver.observe(this.container,{attributes:!0,attributeFilter:e})}}unbindThemeWatchers(){this.themeTweenRaf&&(cancelAnimationFrame(this.themeTweenRaf),this.themeTweenRaf=0),this.colorSchemeQuery&&typeof this.colorSchemeQuery.removeEventListener=="function"&&this.colorSchemeQuery.removeEventListener("change",this.handleThemeChange),this.colorSchemeQuery=null,this.themeMutationObserver?.disconnect(),this.themeMutationObserver=null}updateScrollColorShift(e){if(this.scrollStopsRgb.length<2)return;let t=Math.min(1,Math.max(0,e));if(Math.abs(t-this.lastScrollColorT)<.002)return;this.lastScrollColorT=t;let i=K(this.scrollStopsRgb,this.resolvedDarkTheme),r=i.length-1,s=t*r,a=Math.min(r-1,Math.floor(s)),n=s-a,l=i[a],c=i[a+1],u=i[Math.min(i.length-1,a+2)]??l,h=[l[0]+(c[0]-l[0])*n,l[1]+(c[1]-l[1])*n,l[2]+(c[2]-l[2])*n],f=[c[0]+(u[0]-c[0])*n,c[1]+(u[1]-c[1])*n,c[2]+(u[2]-c[2])*n],d=this.basePaletteRgb[2]??u;this.activePaletteRgb=[h,f,d],this.pushUniformBatch({uColor1:h,uColor2:f,uColor3:d})}syncScrollColorListener(){if(typeof window>"u")return;let e=this.scrollStopsRgb.length>=2;e&&!this.hasScrollColorListener?(window.addEventListener("scroll",this.handleScrollColorEvent,{passive:!0}),this.hasScrollColorListener=!0,this.lastScrollColorT=-1,this.updateScrollColorShift(this.computeScrollProgress())):!e&&this.hasScrollColorListener&&(window.removeEventListener("scroll",this.handleScrollColorEvent),this.hasScrollColorListener=!1,this.scrollColorRaf&&(cancelAnimationFrame(this.scrollColorRaf),this.scrollColorRaf=0))}getLocalTouchCoords(e){let t=this.container.getBoundingClientRect();if(t.width<=0||t.height<=0)return null;let i=(e.clientX-t.left)/t.width,r=1-(e.clientY-t.top)/t.height;return i<0||i>1||r<0||r>1?null:[i,r]}syncTouchListener(){typeof window>"u"||(this.interactive&&!this.hasTouchListener?(this.container.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.container.addEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.container.addEventListener("touchend",this.handleTouchEnd,{passive:!0}),this.container.addEventListener("touchcancel",this.handleTouchEnd,{passive:!0}),this.hasTouchListener=!0):!this.interactive&&this.hasTouchListener&&(this.container.removeEventListener("touchstart",this.handleTouchStart),this.container.removeEventListener("touchmove",this.handleTouchMove),this.container.removeEventListener("touchend",this.handleTouchEnd),this.container.removeEventListener("touchcancel",this.handleTouchEnd),this.hasTouchListener=!1))}seedUniformsFromOptions(e,t=!1){let i={};if(typeof e.speed=="number"?(this.targetSpeed=e.speed,t&&(this.currentSpeed=e.speed),this.customUniforms.set("uSpeed",e.speed),i.uSpeed=e.speed):this.customUniforms.has("uSpeed")||(this.targetSpeed=1,this.currentSpeed=1,this.customUniforms.set("uSpeed",1),i.uSpeed=1),t||e.quality!==void 0){let n=this.computeEffectiveQuality();this.customUniforms.set("uQuality",n),i.uQuality=n}e.scrollColors!==void 0&&(this.scrollStopsRgb=this.parseScrollStops(e.scrollColors),this.lastScrollColorT=-1);let r=this.resolvedDarkTheme;e.theme!==void 0&&(this.themeMode=e.theme);let s=this.detectDarkTheme(this.themeMode);if(this.resolvedDarkTheme=s,t&&(this.currentTheme=s?1:0,this.customUniforms.set("uTheme",this.currentTheme),i.uTheme=this.currentTheme),t||e.colors!==void 0||e.lightColors!==void 0||e.darkColors!==void 0||e.theme!==void 0||e.scrollColors!==void 0){let n=this.parseColorList(this.options.colors);n.length>0&&(this.rawBasePaletteRgb=n);let l=this.resolveTargetPalette(s);if(l.length>0)if(this.basePaletteRgb=l,this.rawBasePaletteRgb.length===0&&(this.rawBasePaletteRgb=l),!t&&s!==r)this.startThemeTransition(s);else{let[c,u,h]=this.toTriplet(l);this.activePaletteRgb=[c,u,h],this.customUniforms.set("uColor1",c),this.customUniforms.set("uColor2",u),this.customUniforms.set("uColor3",h),i.uColor1=c,i.uColor2=u,i.uColor3=h,t||(this.currentTheme=s?1:0,this.customUniforms.set("uTheme",this.currentTheme),i.uTheme=this.currentTheme)}}if(e.uniforms)for(let[n,l]of Object.entries(e.uniforms))this.customUniforms.set(n,l),i[n]=typeof l=="number"?l:Array.from(l);return this.shouldPreserveBg()&&(this.customUniforms.set("uTransparentBg",1),i.uTransparentBg=1),i}fallbackToMainThread(e,t,i,r){if(this.isDestroyed)return;this.worker&&(this.worker.terminate(),this.worker=null),this.isOffscreen=!1,this.resetFrameTracking(),this.markContextReleased();let s=this.canvas.cloneNode(!1);this.canvas.replaceWith(s),this.canvas=s,this.initMainThreadMode(e,t,i,r)}initOffscreenMode(e,t,i,r){try{let s=Te(),a=this.canvas.transferControlToOffscreen();this.worker=s,this.isOffscreen=!0,this.markContextActive(),s.onmessage=l=>{if(l.data?.type==="error")this.fallbackToMainThread(e,t,i,r);else if(l.data?.type==="stats"){this.reportedFps=typeof l.data.fps=="number"?l.data.fps:0,this.reportedFrameTimeMs=typeof l.data.frameTimeMs=="number"?l.data.frameTimeMs:0;let c=typeof l.data.targetFps=="number"?l.data.targetFps:0;this.reportedFrameTimeMs>0&&c>0&&D.recordGpuFrame(this.reportedFrameTimeMs,c,performance.now())}},s.onerror=()=>{this.fallbackToMainThread(e,t,i,r)};let n={};this.customUniforms.forEach((l,c)=>{n[c]=typeof l=="number"?l:Array.from(l)}),s.postMessage({type:"init",canvas:a,width:this.width,height:this.height,minDpr:t,maxDpr:i,dynamicRes:r,reducedMotion:this.isReducedMotion,vertexShader:e.vertexShader??xe,fragmentShader:e.fragmentShader,feedbackShader:e.feedbackShader??null,feedbackScale:this.feedbackScale,feedbackMaxDim:this.feedbackMaxDim,feedbackFloat:this.feedbackFloat,initialScroll:this.scroll,ambientFps:this.ambientFps,activeFps:this.activeFps,survivalPaused:this.isSurvivalSuspended,uniforms:n},[a])}catch{this.isOffscreen=!1,this.markContextReleased(),this.initMainThreadMode(e,t,i,r)}}computeFboDimsMain(e,t){let i=Math.max(1,Math.floor(e*this.feedbackScale)),r=Math.max(1,Math.floor(t*this.feedbackScale)),s=Math.max(i,r);if(s>this.feedbackMaxDim){let a=this.feedbackMaxDim/s;i=Math.max(1,Math.floor(i*a)),r=Math.max(1,Math.floor(r*a))}return[i,r]}destroyPingPongMain(){if(!this.pingPong||!this.gl){this.pingPong=null;return}for(let e=0;e<2;e++)this.gl.deleteFramebuffer(this.pingPong[e].fbo),this.gl.deleteTexture(this.pingPong[e].tex);this.pingPong=null}createPingPongMain(e){if(this.destroyPingPongMain(),!this.options.feedbackShader||this.isContextLost)return;let[t,i]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);this.fboW=t,this.fboH=i;let r=e.RGBA8,s=e.UNSIGNED_BYTE;this.feedbackFloat&&(e.getExtension("EXT_color_buffer_float")||e.getExtension("EXT_color_buffer_half_float"))&&(r=e.RGBA16F,s=e.HALF_FLOAT);let n=(c,u)=>{let h=[];for(let f=0;f<2;f++){let d=e.createTexture(),m=e.createFramebuffer();if(!d||!m)return d&&e.deleteTexture(d),m&&e.deleteFramebuffer(m),h.forEach(p=>{e.deleteFramebuffer(p.fbo),e.deleteTexture(p.tex)}),null;if(e.bindTexture(e.TEXTURE_2D,d),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,c,this.fboW,this.fboH,0,e.RGBA,u,null),e.bindFramebuffer(e.FRAMEBUFFER,m),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,d,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)return e.deleteFramebuffer(m),e.deleteTexture(d),h.forEach(p=>{e.deleteFramebuffer(p.fbo),e.deleteTexture(p.tex)}),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),null;e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),h.push({fbo:m,tex:d})}return e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),[h[0],h[1]]},l=n(r,s);!l&&r!==e.RGBA8&&(r=e.RGBA8,s=e.UNSIGNED_BYTE,l=n(r,s)),this.fboFormat=r,this.fboType=s,this.pingPong=l,this.readIdx=0,this.writeIdx=1}resizePingPongMain(){if(!this.pingPong||!this.gl||this.isContextLost)return;let[e,t]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);if(e===this.fboW&&t===this.fboH)return;let i=this.gl,r=this.fboW,s=this.fboH,a=this.pingPong[this.readIdx],n=[];for(let l=0;l<2;l++){let c=i.createTexture(),u=i.createFramebuffer();i.bindTexture(i.TEXTURE_2D,c),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,this.fboFormat,e,t,0,i.RGBA,this.fboType,null),i.bindFramebuffer(i.FRAMEBUFFER,u),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,c,0),n.push({fbo:u,tex:c})}i.bindFramebuffer(i.READ_FRAMEBUFFER,a.fbo),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,n[0].fbo),i.blitFramebuffer(0,0,r,s,0,0,e,t,i.COLOR_BUFFER_BIT,i.LINEAR),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindTexture(i.TEXTURE_2D,null);for(let l=0;l<2;l++)i.deleteFramebuffer(this.pingPong[l].fbo),i.deleteTexture(this.pingPong[l].tex);this.pingPong=[n[0],n[1]],this.fboW=e,this.fboH=t,this.readIdx=0,this.writeIdx=1}initMainThreadPipeline(e){let t=this.options.vertexShader??N;this.programEntry=x.getOrCreateProgram(e,this.options.fragmentShader,t),this.options.feedbackShader?this.feedbackProgramEntry=x.getOrCreateProgram(e,this.options.feedbackShader,t):this.feedbackProgramEntry=null,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vbo=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vbo),e.bufferData(e.ARRAY_BUFFER,_e,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),this.needsResize=!1,this.applyCanvasSize(),this.options.feedbackShader&&this.createPingPongMain(e)}initMainThreadMode(e,t,i,r){let s=null,a=w.acquireRecycledMainContext();if(a?(a.canvas.style.background="",this.canvas.replaceWith(a.canvas),this.canvas=a.canvas,s=a.gl):s=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance",preserveDrawingBuffer:!1}),!s){console.warn("[FluxFX] WebGL2 is not supported on this device."),this.isBudgetSuspended=!0,this.applyBudgetFallbackStyle();return}this.gl=s,this.markContextActive(),this.canvas.addEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestored,!1),this.dynamicRes=new j({minScale:r?t:i,maxScale:i}),this.initMainThreadPipeline(s),this.drawMainThreadFrame()}applyCanvasSize(){if(!this.gl||!this.dynamicRes||this.isContextLost)return;let e=this.dynamicRes.scale,t=Math.max(1,Math.round(this.width*e)),i=Math.max(1,Math.round(this.height*e));(this.canvas.width!==t||this.canvas.height!==i)&&(this.canvas.width=t,this.canvas.height=i,this.gl.viewport(0,0,t,i)),this.pingPong&&this.resizePingPongMain()}bindCommonUniformsMain(e,t,i,r){let s=x.getUniformLocation(e,t,"uTime");s&&e.uniform1f(s,this.elapsedSec);let a=x.getUniformLocation(e,t,"uDelta");a&&e.uniform1f(a,this.lastDeltaSec);let n=x.getUniformLocation(e,t,"uResolution");n&&e.uniform2f(n,i,r);let l=x.getUniformLocation(e,t,"uCanvasResolution");l&&e.uniform2f(l,this.canvas.width,this.canvas.height);let c=x.getUniformLocation(e,t,"uDpr");c&&this.dynamicRes&&e.uniform1f(c,this.dynamicRes.scale);let u=x.getUniformLocation(e,t,"uMouse");u&&e.uniform2f(u,this.mouse[0],this.mouse[1]);let h=x.getUniformLocation(e,t,"uMouseVel");h&&e.uniform2f(h,this.mouseVel[0],this.mouseVel[1]);let f=x.getUniformLocation(e,t,"uMouseDown");f&&e.uniform1f(f,this.mouseDown);let d=x.getUniformLocation(e,t,"uMouseActive");d&&e.uniform1f(d,this.mouseActive);let m=x.getUniformLocation(e,t,"uScroll");m&&e.uniform1f(m,this.scroll);let p=x.getUniformLocation(e,t,"uScrollVel");p&&e.uniform1f(p,this.scrollVel),this.customUniforms.forEach((v,g)=>{let b=x.getUniformLocation(e,t,g);b&&(g==="uSpeed"?e.uniform1f(b,this.currentSpeed):typeof v=="number"?e.uniform1f(b,v):v.length===2?e.uniform2f(b,v[0],v[1]):v.length===3?e.uniform3f(b,v[0],v[1],v[2]):v.length===4&&e.uniform4f(b,v[0],v[1],v[2],v[3]))})}drawMainThreadFrame(){if(!this.gl||!this.programEntry||this.isContextLost)return;let e=this.gl;if(e.bindVertexArray(this.vao),this.feedbackProgramEntry&&this.pingPong){e.bindFramebuffer(e.FRAMEBUFFER,this.pingPong[this.writeIdx].fbo),e.viewport(0,0,this.fboW,this.fboH),e.useProgram(this.feedbackProgramEntry.program),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let t=x.getUniformLocation(e,this.feedbackProgramEntry,"uPrevFrame");t&&e.uniform1i(t,0),this.bindCommonUniformsMain(e,this.feedbackProgramEntry,this.fboW,this.fboH),e.drawArrays(e.TRIANGLES,0,3);let i=this.readIdx;this.readIdx=this.writeIdx,this.writeIdx=i,e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,this.canvas.width,this.canvas.height)}if(e.useProgram(this.programEntry.program),this.pingPong){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let t=x.getUniformLocation(e,this.programEntry,"uFeedback");t&&e.uniform1i(t,0);let i=x.getUniformLocation(e,this.programEntry,"uPrevFrame");i&&e.uniform1i(i,0)}this.bindCommonUniformsMain(e,this.programEntry,this.canvas.width,this.canvas.height),e.drawArrays(e.TRIANGLES,0,3)}render(e,t){if(this.isOffscreen||this.isPaused||this.isHiddenByViewport||this.isReducedMotion||this.isContextLost||this.isSurvivalSuspended||this.isBudgetSuspended||this.isDestroyed||!this.gl||!this.programEntry)return;let i=performance.now(),r=this.lastRenderNow?Math.min(i-this.lastRenderNow,100):16.67;this.lastRenderNow=i,this.prevFrameDrew&&(this.dynamicRes&&this.dynamicRes.recordFrame(r,i)&&(this.needsResize=!0),this.prevFrameDrew=!1);let a=i<this.boostUntil||this.mouseDown>.5?this.activeFps:this.ambientFps,n=1e3/a-2;if(this.lastDrawNow>0&&i-this.lastDrawNow<n)return;let l=this.lastDrawNow?i-this.lastDrawNow:1e3/a,c=Math.min(l,100);this.lastDrawNow=i,a!==this.lastTargetFps?(this.lastTargetFps=a,this.avgDrawDeltaMs=0):l>0&&l<500&&(this.avgDrawDeltaMs=this.avgDrawDeltaMs===0?l:this.avgDrawDeltaMs*.85+l*.15),this.avgDrawDeltaMs>0&&(this.reportedFps=Math.round(1e3/this.avgDrawDeltaMs),this.reportedFrameTimeMs=Math.round(this.avgDrawDeltaMs*100)/100),l>0&&l<500&&D.recordGpuFrame(l,a,i);let u=Math.max(.001,Math.min(c*.001,.05));if(this.lastDeltaSec=u,this.currentSpeed+=(this.targetSpeed-this.currentSpeed)*Y(7.5,u),this.elapsedSec+=u*this.currentSpeed,this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.mouseActive+=(this.targetMouseActive-this.mouseActive)*Y(7,u),this.mouseActive<.001&&this.targetMouseActive===0&&(this.mouseActive=0),this.targetMouseActive>.5){let h=this.mouse[0],f=this.mouse[1],d=Y(13,u);this.mouse[0]+=(this.targetMouse[0]-this.mouse[0])*d,this.mouse[1]+=(this.targetMouse[1]-this.mouse[1])*d,this.mouseVel[0]=Math.max(-8,Math.min(8,(this.mouse[0]-h)/u)),this.mouseVel[1]=Math.max(-8,Math.min(8,(this.mouse[1]-f)/u))}else this.mouseVel[0]=0,this.mouseVel[1]=0;if(this.trackScroll){let h=this.scroll;this.scroll+=(this.targetScroll-this.scroll)*Y(9.5,u),this.scrollVel=Math.max(-6,Math.min(6,(this.scroll-h)/u))}this.drawMainThreadFrame(),this.prevFrameDrew=!0}applyProtectionState(){if(this.isDestroyed||this.isBudgetSuspended)return;let e=this.resolveTierConfig(),{minDpr:t,maxDpr:i}=this.resolveDprBounds(),s=this.options.dynamicResolution??!0?t:i,a=this.isSurvivalSuspended,n=this.feedbackMaxDim;this.ambientFps=e.ambientFps,this.activeFps=e.activeFps,this.feedbackMaxDim=e.feedbackMaxDim,this.isSurvivalSuspended=e.suspended,this.isSurvivalSuspended&&!a&&this.resetFrameTracking(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"protection",minDpr:s,maxDpr:i,feedbackMaxDim:this.feedbackMaxDim,ambientFps:this.ambientFps,activeFps:this.activeFps,suspended:this.isSurvivalSuspended}):((this.dynamicRes?.setBounds(s,i)??!1)||n!==this.feedbackMaxDim)&&(this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0),a!==this.isSurvivalSuspended&&this.wakeCallback?.()}syncDprBounds(){this.applyProtectionState()}watchDevicePixelRatio(){if(this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof window>"u"||typeof window.matchMedia!="function")return;let e=window.devicePixelRatio||1;this.dprMediaQuery=window.matchMedia(`(resolution: ${e}dppx)`),this.dprMediaQuery.addEventListener("change",this.handleDprChange)}updateOptions(e){if(this.isDestroyed)return;let t=this.options.quality;this.options={...this.options,...e},e.layer!==void 0&&(this.layerMode=e.layer),(e.layer!==void 0||e.overlayOpacity!==void 0)&&this.applyCanvasLayerStyle(),typeof e.adaptToSurface=="boolean"&&(this.adaptToSurface=e.adaptToSurface,!this.adaptToSurface&&this.isSurfaceAdapted&&(this.isSurfaceAdapted=!1,this.lastSurfaceEl=null,this.lastSurfaceKey="",this.startPaletteTween(this.basePaletteRgb,200)));let i=this.seedUniformsFromOptions(e,!1);if(e.preserveBg!==void 0||e.layer!==void 0){let s=this.shouldPreserveBg()?1:Number(this.customUniforms.get("uTransparentBg")??0);this.customUniforms.set("uTransparentBg",s),i.uTransparentBg=s}if(this.boostInteraction(1200),e.quality!==void 0&&e.quality!==t){let r=G[e.quality]??G.medium;this.baseFeedbackMaxDim=this.options.feedbackMaxDim??r.fboMaxDim}if(e.feedbackMaxDim!==void 0&&(this.baseFeedbackMaxDim=e.feedbackMaxDim),(e.quality!==void 0&&e.quality!==t||e.feedbackMaxDim!==void 0||e.minDpr!==void 0||e.maxDpr!==void 0||e.dynamicResolution!==void 0)&&this.syncDprBounds(),typeof e.interactive=="boolean"&&e.interactive!==this.interactive&&(this.interactive=e.interactive,this.syncPointerListener(),this.syncTouchListener()),typeof e.trackScroll=="boolean"&&e.trackScroll!==this.trackScroll&&(this.trackScroll=e.trackScroll,this.syncScrollListener()),e.scrollColors!==void 0&&this.syncScrollColorListener(),typeof e.respectReducedMotion=="boolean"){this.respectReducedMotion=e.respectReducedMotion;let r=this.reducedMotionQuery?.matches??!1;this.applyReducedMotionState(this.respectReducedMotion&&r)}if(this.isBudgetSuspended){this.applyBudgetFallbackStyle();return}this.isOffscreen&&this.worker?Object.keys(i).length>0&&this.worker.postMessage({type:"uniformsBatch",uniforms:i}):this.isReducedMotion&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame())}applyReducedMotionState(e){this.isReducedMotion!==e&&(this.isReducedMotion=e,this.resetFrameTracking(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"reducedMotion",value:e}):e&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame()),this.wakeCallback?.())}getLocalPointerCoords(e){let t=this.container.getBoundingClientRect();if(t.width<=0||t.height<=0||e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)return null;let i=(e.clientX-t.left)/t.width,r=1-(e.clientY-t.top)/t.height;return[i,r]}syncInteractiveAttr(){if(this.interactive&&!this.isDestroyed){this.container.setAttribute("data-fluxfx-interactive","true");return}let e=!1;w.instances.forEach(t=>{t!==this&&!t.isDestroyed&&t.interactive&&t.container===this.container&&(e=!0)}),e||this.container.removeAttribute("data-fluxfx-interactive")}isShadowedByChildInteractive(e){if(!(e instanceof Element))return!1;let t=e.closest('[data-fluxfx-interactive="true"]');return!!(t&&t!==this.container&&this.container.contains(t))}syncPointerListener(){this.syncInteractiveAttr(),this.interactive&&!this.hasPointerListener?(this.container.addEventListener("pointerenter",this.handlePointerEnter,{passive:!0}),this.container.addEventListener("pointermove",this.handlePointerMove,{passive:!0}),this.container.addEventListener("pointerleave",this.handlePointerLeave,{passive:!0}),this.container.addEventListener("pointerdown",this.handlePointerDown,{passive:!0}),window.addEventListener("pointerup",this.handlePointerUp,{passive:!0}),window.addEventListener("pointercancel",this.handlePointerUp,{passive:!0}),this.hasPointerListener=!0):!this.interactive&&this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.handlePointerLeave(),this.hasPointerListener=!1)}syncScrollListener(){this.trackScroll&&!this.hasScrollListener?(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.hasScrollListener=!0,this.handleScroll()):!this.trackScroll&&this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1)}bindObservers(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(t=>{let i=t[0];if(!i)return;let r=Math.max(1,Math.floor(i.contentRect.width)),s=Math.max(1,Math.floor(i.contentRect.height));r===this.width&&s===this.height||(this.width=r,this.height=s,this.boostInteraction(600),this.trackScroll&&this.handleScroll(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"resize",width:this.width,height:this.height}):this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0)}),this.resizeObserver.observe(this.container)),e&&typeof IntersectionObserver<"u"&&(this.visibilityObserver=new IntersectionObserver(t=>{let i=t[0]?.isIntersecting??!0;if(this.isHiddenByViewport=!i,i){if(this.lastActiveAt=Q(),this.isBudgetSuspended&&!this.isPaused){this.restoreContextFromBudget();return}}else this.handlePointerLeave(),this.resetFrameTracking();this.isOffscreen&&this.worker&&this.worker.postMessage({type:i&&!this.isPaused?"resume":"pause"}),this.wakeCallback?.()},{rootMargin:"50px"}),this.visibilityObserver.observe(this.container)),this.reducedMotionQuery&&this.reducedMotionQuery.addEventListener("change",this.handleReducedMotionChange),this.isOffscreen&&typeof document<"u"&&document.addEventListener("visibilitychange",this.handleDocVisibility),this.watchDevicePixelRatio(),this.bindThemeWatchers(),this.syncPointerListener(),this.syncTouchListener(),this.syncScrollListener(),this.syncScrollColorListener()}setUniform(e,t){if(!this.isDestroyed){if(this.customUniforms.set(e,t),e==="uSpeed"&&typeof t=="number"&&(this.targetSpeed=t),this.boostInteraction(1200),this.isBudgetSuspended){this.applyBudgetFallbackStyle();return}this.isOffscreen&&this.worker?this.worker.postMessage({type:"uniform",name:e,value:typeof t=="number"?t:Array.from(t)}):this.isReducedMotion&&this.drawMainThreadFrame()}}setColor(e,t){let i=M(t,"#ffffff"),r=T.hexToVec3Into(i,T.scratchVec3);this.setUniform(e,[r[0],r[1],r[2]])}get isIdle(){return this.isDestroyed||this.isPaused||this.isHiddenByViewport||this.isReducedMotion||this.isContextLost}onWake(e){this.wakeCallback=e}pause(){this.isPaused||this.isDestroyed||(this.isPaused=!0,this.resetFrameTracking(),this.handlePointerLeave(),this.isOffscreen&&this.worker&&this.worker.postMessage({type:"pause"}))}resume(){if(!(!this.isPaused||this.isDestroyed)){if(this.isPaused=!1,this.lastRenderNow=0,this.lastDrawNow=0,this.lastActiveAt=Q(),this.isBudgetSuspended&&!this.isHiddenByViewport){this.restoreContextFromBudget();return}this.isOffscreen&&this.worker&&!this.isHiddenByViewport?this.worker.postMessage({type:"resume"}):this.isReducedMotion&&!this.isHiddenByViewport&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame())}}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.wakeCallback=null,this.unsubscribeGuard?.(),this.unsubscribeGuard=null,this.unbindThemeWatchers(),this.touchBurstTimer&&(window.clearTimeout(this.touchBurstTimer),this.touchBurstTimer=0),this.touchLeaveTimer&&(window.clearTimeout(this.touchLeaveTimer),this.touchLeaveTimer=0),this.hasTouchListener&&(this.container.removeEventListener("touchstart",this.handleTouchStart),this.container.removeEventListener("touchmove",this.handleTouchMove),this.container.removeEventListener("touchend",this.handleTouchEnd),this.container.removeEventListener("touchcancel",this.handleTouchEnd),this.hasTouchListener=!1),this.hasScrollColorListener&&(window.removeEventListener("scroll",this.handleScrollColorEvent),this.hasScrollColorListener=!1),this.scrollColorRaf&&(cancelAnimationFrame(this.scrollColorRaf),this.scrollColorRaf=0),this.isBodyMount&&(this.container.style.minHeight=this.origBodyMinHeight),w.instances.delete(this),this.syncInteractiveAttr(),this.resetFrameTracking(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.visibilityObserver?.disconnect(),this.visibilityObserver=null,this.reducedMotionQuery&&(this.reducedMotionQuery.removeEventListener("change",this.handleReducedMotionChange),this.reducedMotionQuery=null),this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleDocVisibility),this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.hasPointerListener=!1),this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1),this.canvas.removeEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored,!1),this.isOffscreen&&this.worker&&(this.worker.postMessage({type:"destroy"}),this.worker=null),this.releaseMainThreadContext(!1),this.markContextReleased(),T.releaseVec2(this.mouse),T.releaseVec2(this.targetMouse),T.releaseVec2(this.mouseVel),this.customUniforms.clear(),w.reclaimBudgetForWaiting())}};w._activeContexts=0,w._maxContexts=Me(),w.instances=new Set,w.recycledMainContexts=[];var A=w;var J=class{constructor(){this.plugins=new Map;this.activeByElement=new WeakMap;this.activeSet=new Set;this.visibilityObserver=null;this.visibilityCallbacks=new WeakMap;this.removeTicker=null;this.removeVisibilitySub=null}ensureObserver(){return typeof window>"u"||typeof IntersectionObserver>"u"?null:(this.visibilityObserver||(this.visibilityObserver=new IntersectionObserver(e=>{for(let t=0;t<e.length;t++){let i=e[t],r=this.visibilityCallbacks.get(i.target);r&&r.forEach(s=>s(i.isIntersecting))}},{rootMargin:"50px"})),this.visibilityObserver)}ensureVisibilitySub(){this.removeVisibilitySub||(this.removeVisibilitySub=B.onVisibilityChange(e=>{this.activeSet.forEach(t=>{t.faulted||(e?t.instance.pause?.():t.visible&&t.instance.resume?.())}),this.syncTickerState()}))}hasActiveTickWork(){let e=!1;return this.activeSet.forEach(t=>{e||!t.visible||t.faulted||!t.instance.update||t.instance.isIdle?.()||(e=!0)}),e}syncTickerState(){this.hasActiveTickWork()?this.ensureTicker():this.removeTicker&&(this.removeTicker(),this.removeTicker=null)}ensureTicker(){this.removeTicker||(this.removeTicker=B.add((e,t)=>{let i=!1;this.activeSet.forEach(r=>{if(!(!r.visible||r.faulted||!r.instance.update)&&!r.instance.isIdle?.()){try{r.instance.update(e,t)}catch(s){r.faulted=!0,console.error(`[FluxFX] Runtime error in "${r.name}" (auto-paused):`,s);return}r.instance.isIdle?.()||(i=!0)}}),i||this.syncTickerState()}))}cleanupEmptyEngine(){this.syncTickerState(),this.activeSet.size===0&&this.removeVisibilitySub&&(this.removeVisibilitySub(),this.removeVisibilitySub=null)}bindWake(e){e.instance.onWake?.(()=>{this.activeSet.has(e)&&this.syncTickerState()})}register(e){return this.plugins.set(e.name,e),this}has(e){return this.plugins.has(e)}setMaxWebGLContexts(e){A.setMaxActiveContexts(e)}getStats(){let e=0,t=0,i=!1,r=B.isHidden;this.activeSet.forEach(u=>{u.visible&&e++;let h=u.instance.isIdle?.()??!1;r||!u.visible||u.faulted||h?t++:!u.instance.isWebGL&&u.instance.isIdle&&(i=!0)});let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,a=A.getRenderStats(),n=B.fps,l=B.frameTimeMs;!r&&a.activeRendering>0&&!i?(n=a.fps,l=a.frameTimeMs):r&&(n=0,l=0);let c=D.getSnapshot();return{mounted:this.activeSet.size,visible:e,pausedEffects:t,activeLoops:B.isRunning?1:0,registered:this.plugins.size,webglContexts:A.activeContexts,activeContexts:A.activeContexts,maxWebGLContexts:A.maxActiveContexts,suspendedContexts:A.suspendedContexts,fps:n,frameTimeMs:l,reducedMotion:s,protectionTier:c.tier,protectionLabel:c.label}}apply(e,t,i={}){let r=this.plugins.get(t);if(!r)return console.warn(`[FluxFX] Effect "${t}" is not registered.`),()=>{};let s=this.activeByElement.get(e);s||(s=new Map,this.activeByElement.set(e,s));let a=s.get(t);a&&a.destroy();let n;try{n=r.mount(e,i)}catch(f){return console.error(`[FluxFX] Failed to mount "${t}":`,f),()=>{}}let l=i.pauseWhenHidden??!0,c=null,u=!1,h={el:e,name:t,plugin:r,instance:n,options:{...i},visible:!0,faulted:!1,destroy:()=>{if(!u){u=!0,c?.(),this.activeSet.delete(h),s?.delete(t);try{h.instance.destroy()}catch(f){console.error(`[FluxFX] Cleanup error in "${t}":`,f)}this.cleanupEmptyEngine()}}};if(l){let f=this.ensureObserver();if(f){let d=this.visibilityCallbacks.get(e);d||(d=new Set,this.visibilityCallbacks.set(e,d),f.observe(e));let m=p=>{h.visible=p,p&&!B.isHidden?h.instance.resume?.():h.instance.pause?.(),this.syncTickerState()};d.add(m),c=()=>{d?.delete(m),d&&d.size===0&&(f.unobserve(e),this.visibilityCallbacks.delete(e))}}}return s.set(t,h),this.activeSet.add(h),this.bindWake(h),this.ensureVisibilitySub(),B.isHidden&&h.instance.pause?.(),this.syncTickerState(),h.destroy}update(e,t,i={}){let s=this.activeByElement.get(e)?.get(t);if(!s)return!1;s.options={...s.options,...i};let a=s.options;if(s.instance.setOptions)try{return s.instance.setOptions(a),this.syncTickerState(),!0}catch(n){return console.error(`[FluxFX] Hot-update error in "${t}":`,n),!1}try{return s.instance.destroy(),s.instance=s.plugin.mount(e,a),s.faulted=!1,this.bindWake(s),(!s.visible||B.isHidden)&&s.instance.pause?.(),this.syncTickerState(),!0}catch(n){return s.faulted=!0,console.error(`[FluxFX] Fallback remount error in "${t}":`,n),this.syncTickerState(),!1}}scan(e=document){if(typeof document>"u")return;e.querySelectorAll("[data-fx]").forEach(i=>{let r=i.getAttribute("data-fx");if(!r)return;let s=r.trim().split(/\s+/).filter(Boolean),a=this.parseDatasetOptions(i),n=this.activeByElement.get(i);s.forEach(l=>{n?.has(l)||this.apply(i,l,a)})})}init(e){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.scan(e??document),{once:!0}):this.scan(e??document))}destroyAll(){let e=Array.from(this.activeSet);for(let t=0;t<e.length;t++)e[t].destroy()}parseDatasetOptions(e){let t={},i=new Set(["preserveBg","adaptToSurface","interactive","trackScroll","glare","offscreen","dynamicResolution","pauseWhenHidden","respectReducedMotion"]),r=new Set(["colors","lightColors","darkColors","scrollColors"]);for(let[s,a]of Object.entries(e.dataset)){if(!s.startsWith("fx")||s==="fx"||a===void 0)continue;let n=s.slice(2),l=n.charAt(0).toLowerCase()+n.slice(1),c=a.trim(),u=c.toLowerCase();c===""&&i.has(l)||u==="true"?t[l]=!0:u==="false"?t[l]=!1:r.has(l)?t[l]=c.split(",").map(h=>h.trim()).filter(Boolean):c!==""&&!Number.isNaN(Number(c))?t[l]=Number(c):t[l]=c}return t}},Z=new J;function Ve(o){if(o==null)return!1;let e=String(o).trim().toLowerCase();if(!e)return!1;if(e==="transparent"||e==="none")return!0;let t=e.match(/^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+(?:\s*,\s*([\d.]+))?\s*\)$/);return t&&t[1]!==void 0?parseFloat(t[1])<=.001:!1}function Se(o){let e=o.replace("#","").trim(),t=e.length===3?e.split("").map(a=>a+a).join(""):e;if(t.length!==6)return!0;let i=parseInt(t.slice(0,2),16)/255,r=parseInt(t.slice(2,4),16)/255,s=parseInt(t.slice(4,6),16)/255;return .2126*i+.7152*r+.0722*s>.45}function we(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let s=o.colors.filter(Boolean);if(s.length===1){let c=M(s[0],e[0]);return[c,c,c]}if(s.length===2){let c=M(s[0],e[0]),u=M(s[1],e[1]);return[c,u,u]}let a=M(s[0],e[0]),n=M(s[1]??a,e[1]),l=M(s[2]??n,e[2]);return[a,n,l]}if(typeof o.colors=="string"){let s=o.colors.split(",").map(a=>a.trim()).filter(Boolean);if(s.length===1){let a=M(s[0],e[0]);return[a,a,a]}if(s.length===2){let a=M(s[0],e[0]),n=M(s[1],e[1]);return[a,n,n]}if(s.length>2)return[M(s[0],e[0]),M(s[1],e[1]),M(s[2],e[2])]}if(o.color1===void 0&&o.color2===void 0&&o.color3===void 0)return e;let t=M(o.color1,e[0]),i=o.color2!==void 0?M(o.color2,t):t,r=o.color3!==void 0?M(o.color3,i):i;return[t,i,r]}function U(o,e){let t=Ve(o.bgColor),i=!t&&o.bgColor!==void 0&&String(o.bgColor).trim()!=="",r=i?M(o.bgColor,e):e,s=T.hexToVec3Into(r,T.scratchVec3);return{uBgColor:[s[0],s[1],s[2]],uHasBgColor:i?1:0,uTransparentBg:t?1:0,bgHex:r,hasBgColor:i,transparentBg:t}}function Oe(o){return o==="high"?.65:o==="low"?.35:.5}function _(o){return{name:o.name,mount(e,t){let i=t.quality??"medium",r=new A(e,{fragmentShader:o.fragmentShader,vertexShader:o.vertexShader,feedbackShader:o.feedbackShader,feedbackScale:o.feedbackShader?Oe(i):void 0,feedbackFloat:o.feedbackShader?o.feedbackFloat??!0:void 0,feedbackMaxDim:typeof t.feedbackMaxDim=="number"?t.feedbackMaxDim:void 0,speed:typeof t.speed=="number"?t.speed:1,quality:i,colors:we(t,o.defaultColors),uniforms:o.resolveUniforms?o.resolveUniforms(t):void 0,theme:t.theme,lightColors:t.lightColors,darkColors:t.darkColors,scrollColors:t.scrollColors,trackScroll:t.trackScroll,layer:t.layer,preserveBg:t.preserveBg,adaptToSurface:t.adaptToSurface,overlayOpacity:t.overlayOpacity,interactive:t.interactive!==!1,dynamicResolution:t.dynamicResolution,minDpr:t.minDpr,maxDpr:t.maxDpr,offscreen:t.offscreen,pauseWhenHidden:t.pauseWhenHidden,respectReducedMotion:t.respectReducedMotion});return{isWebGL:!0,update(s,a){r.render(s,a)},setOptions(s){r.updateOptions({speed:typeof s.speed=="number"?s.speed:1,quality:s.quality,colors:we(s,o.defaultColors),uniforms:o.resolveUniforms?o.resolveUniforms(s):void 0,theme:s.theme,lightColors:s.lightColors,darkColors:s.darkColors,scrollColors:s.scrollColors,trackScroll:s.trackScroll,layer:s.layer,preserveBg:s.preserveBg,adaptToSurface:s.adaptToSurface,overlayOpacity:s.overlayOpacity,interactive:s.interactive!==!1,dynamicResolution:s.dynamicResolution,minDpr:s.minDpr,maxDpr:s.maxDpr,feedbackMaxDim:typeof s.feedbackMaxDim=="number"?s.feedbackMaxDim:void 0,respectReducedMotion:s.respectReducedMotion})},isIdle(){return r.isIdle},onWake(s){r.onWake(s)},pause(){r.pause()},resume(){r.resume()},destroy(){r.destroy()}}}}}var He=`#version 300 es
681
792
  precision highp float;
682
793
 
683
794
  in vec2 vUv;
@@ -687,6 +798,11 @@ uniform float uTime;
687
798
  uniform vec2 uResolution;
688
799
  uniform vec2 uMouse;
689
800
  uniform float uMouseActive;
801
+ uniform vec3 uBgColor;
802
+ uniform float uHasBgColor;
803
+ uniform float uTransparentBg;
804
+ uniform float uTheme;
805
+ uniform float uQuality;
690
806
  uniform vec3 uColor1;
691
807
  uniform vec3 uColor2;
692
808
  uniform vec3 uColor3;
@@ -709,13 +825,17 @@ float noise(vec2 p) {
709
825
  float fbm(vec2 p) {
710
826
  float value = 0.0;
711
827
  float amp = 0.5;
828
+ float norm = 0.0;
712
829
  mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
830
+ int octaves = uQuality < 0.25 ? 2 : (uQuality < 0.75 ? 3 : 4);
713
831
  for (int i = 0; i < 4; i++) {
832
+ if (i >= octaves) break;
714
833
  value += amp * noise(p);
834
+ norm += amp;
715
835
  p = rot * p * 2.02;
716
836
  amp *= 0.5;
717
837
  }
718
- return value;
838
+ return (value / max(norm, 0.001)) * 0.9375;
719
839
  }
720
840
 
721
841
  void main() {
@@ -735,17 +855,41 @@ void main() {
735
855
  float ribbon1 = smoothstep(0.15, 0.85, sin(p.y * 3.0 + f * 4.5 + t) * 0.5 + 0.5);
736
856
  float ribbon2 = smoothstep(0.2, 0.9, cos(p.x * 2.2 - f * 3.8 - t * 1.2) * 0.5 + 0.5);
737
857
 
738
- vec3 baseDark = vec3(0.03, 0.04, 0.09);
739
- vec3 col = mix(baseDark, uColor1, smoothstep(0.1, 0.9, ribbon1) * 0.85);
740
- col = mix(col, uColor2, smoothstep(0.2, 0.85, ribbon2 * f) * 0.9);
741
- col += uColor3 * smoothstep(0.25, 0.9, f * ribbon1) * 0.65;
742
-
743
- float vig = 1.0 - dot(uv - 0.5, uv - 0.5) * 0.75;
858
+ float m1 = smoothstep(0.1, 0.9, ribbon1) * 0.85;
859
+ float m2 = smoothstep(0.2, 0.85, ribbon2 * f) * 0.9;
860
+ float m3 = smoothstep(0.25, 0.9, f * ribbon1) * 0.65;
744
861
  float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.02;
745
- col = col * vig + grain;
746
862
 
747
- fragColor = vec4(col, 1.0);
748
- }`,j=["#4f46e5","#06b6d4","#ec4899"];function $(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=c(o.colors[0],e[0]),r=c(o.colors[1]??t,e[1]),s=c(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=c(t[0],e[0]);return[r,r,c(e[2],e[2])]}if(t.length>1)return[c(t[0],e[0]),c(t[1],e[1]),c(t[2]??t[0],e[2])]}return[c(o.color1,e[0]),c(o.color2,e[1]),c(o.color3,e[2])]}var K={name:"aurora",mount(o,e){let i=new x(o,{fragmentShader:be,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:$(e,j),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:$(t,j),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var ye=`#version 300 es
863
+ if (uTransparentBg > 0.5) {
864
+ float w1 = smoothstep(0.18, 0.9, ribbon1) * 0.85;
865
+ float w2 = smoothstep(0.22, 0.88, ribbon2 * f) * 0.9;
866
+ float w3 = smoothstep(0.28, 0.92, f * ribbon1) * 0.65;
867
+ float wSum = w1 + w2 + w3 + 0.0001;
868
+ vec3 ribbonCol = (uColor1 * w1 + uColor2 * w2 + uColor3 * w3) / wSum;
869
+ ribbonCol = clamp(ribbonCol + uColor3 * w3 * 0.35 + vec3(grain), 0.0, 1.0);
870
+ float alpha = clamp(max(max(w1, w2), w3), 0.0, 1.0);
871
+ fragColor = vec4(ribbonCol * alpha, alpha);
872
+ return;
873
+ }
874
+
875
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
876
+ vec3 baseDark = uHasBgColor > 0.5 ? uBgColor : vec3(0.03, 0.04, 0.09);
877
+ vec3 baseLight = uHasBgColor > 0.5 ? uBgColor : vec3(0.96, 0.95, 0.925);
878
+
879
+ vec3 darkCol = mix(baseDark, uColor1, m1);
880
+ darkCol = mix(darkCol, uColor2, m2);
881
+ darkCol += uColor3 * m3;
882
+ float darkVig = 1.0 - dot(uv - 0.5, uv - 0.5) * 0.75;
883
+ darkCol = max(darkCol * darkVig + grain, vec3(0.0));
884
+
885
+ vec3 lightCol = mix(baseLight, uColor1, m1 * 0.44);
886
+ lightCol = mix(lightCol, uColor2, m2 * 0.40);
887
+ lightCol = mix(lightCol, uColor3, m3 * 0.34);
888
+ float lightVig = 1.0 - dot(uv - 0.5, uv - 0.5) * 0.14;
889
+ lightCol = clamp(lightCol * lightVig + grain * 0.5, 0.0, 1.0);
890
+
891
+ fragColor = vec4(mix(lightCol, darkCol, darkAmt), 1.0);
892
+ }`,Re=_({name:"aurora",fragmentShader:He,defaultColors:["#4f46e5","#06b6d4","#ec4899"],resolveUniforms(o){let e=U(o,"#080a17");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg}}});var We=`#version 300 es
749
893
  precision highp float;
750
894
 
751
895
  in vec2 vUv;
@@ -755,12 +899,19 @@ uniform float uTime;
755
899
  uniform vec2 uResolution;
756
900
  uniform vec2 uMouse;
757
901
  uniform float uMouseActive;
902
+ uniform vec3 uBgColor;
903
+ uniform float uHasBgColor;
904
+ uniform float uTransparentBg;
905
+ uniform float uTheme;
906
+ uniform float uQuality;
758
907
  uniform vec3 uColor1;
759
908
  uniform vec3 uColor2;
760
909
  uniform vec3 uColor3;
761
910
 
762
911
  float field(vec2 p, float t) {
763
- for (int i = 1; i < 6; i++) {
912
+ int iters = uQuality < 0.25 ? 3 : (uQuality < 0.75 ? 4 : 5);
913
+ for (int i = 1; i <= 5; i++) {
914
+ if (i > iters) break;
764
915
  float fi = float(i);
765
916
  p.x += 0.35 / fi * sin(fi * 2.2 * p.y + t + 0.4 * fi);
766
917
  p.y += 0.35 / fi * cos(fi * 2.2 * p.x + t * 0.9 + 0.3 * fi);
@@ -792,13 +943,34 @@ void main() {
792
943
  float spec = pow(max(dot(normal, halfVec), 0.0), 28.0);
793
944
  float fresnel = pow(1.0 - max(dot(normal, viewDir), 0.0), 3.0);
794
945
 
795
- vec3 base = mix(uColor1 * 0.25, uColor2 * 0.75, h);
796
- vec3 col = base * (0.45 + 0.75 * diff);
797
- col += mix(vec3(0.95), uColor3, 0.35) * spec * 1.1;
798
- col += uColor3 * fresnel * 0.45;
946
+ if (uTransparentBg > 0.5) {
947
+ vec3 ridgeBase = mix(uColor1, uColor2, smoothstep(0.15, 0.9, h));
948
+ vec3 metalCol = ridgeBase * (0.55 + 0.65 * diff);
949
+ metalCol += mix(vec3(0.95), uColor3, 0.35) * spec * 1.15;
950
+ metalCol += uColor3 * fresnel * 0.5;
951
+ metalCol = clamp(metalCol, 0.0, 1.0);
952
+ float alpha = clamp(smoothstep(0.2, 0.88, h) * 0.78 + spec * 0.9 + fresnel * 0.45, 0.0, 1.0);
953
+ fragColor = vec4(metalCol * alpha, alpha);
954
+ return;
955
+ }
956
+
957
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
958
+
959
+ vec3 darkBase = uHasBgColor > 0.5 ? uBgColor : uColor1 * 0.25;
960
+ vec3 baseD = mix(darkBase, uColor2 * 0.75, h);
961
+ vec3 darkCol = baseD * (0.45 + 0.75 * diff);
962
+ darkCol += mix(vec3(0.95), uColor3, 0.35) * spec * 1.1;
963
+ darkCol += uColor3 * fresnel * 0.45;
799
964
 
800
- fragColor = vec4(col, 1.0);
801
- }`,Y=["#18181b","#94a3b8","#38bdf8"];function J(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=c(o.colors[0],e[0]),r=c(o.colors[1]??t,e[1]),s=c(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=c(t[0],e[0]);return[r,r,c(e[2],e[2])]}if(t.length>1)return[c(t[0],e[0]),c(t[1],e[1]),c(t[2]??t[0],e[2])]}return[c(o.color1,e[0]),c(o.color2,e[1]),c(o.color3,e[2])]}var Z={name:"liquid-metal",mount(o,e){let i=new x(o,{fragmentShader:ye,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:J(e,Y),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:J(t,Y),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var xe=`#version 300 es
965
+ vec3 lightBase = uHasBgColor > 0.5 ? uBgColor : mix(vec3(0.92, 0.935, 0.96), uColor1, 0.16);
966
+ vec3 baseL = mix(lightBase, mix(vec3(0.76, 0.80, 0.88), uColor2, 0.42), h);
967
+ vec3 lightCol = baseL * (0.78 + 0.30 * diff);
968
+ lightCol += mix(vec3(1.0), uColor3, 0.28) * spec * 0.85;
969
+ lightCol = mix(lightCol, uColor3, fresnel * 0.24);
970
+ lightCol = clamp(lightCol, 0.0, 1.0);
971
+
972
+ fragColor = vec4(mix(lightCol, darkCol, darkAmt), 1.0);
973
+ }`,Le=_({name:"liquid-metal",fragmentShader:We,defaultColors:["#18181b","#94a3b8","#38bdf8"],resolveUniforms(o){let e=U(o,"#0f172a");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg}}});var Ge=`#version 300 es
802
974
  precision highp float;
803
975
 
804
976
  in vec2 vUv;
@@ -859,7 +1031,6 @@ void main() {
859
1031
  vel *= velDecay;
860
1032
  dye *= dyeDecay;
861
1033
 
862
- // Subtle autonomous emitter (uTime is already smoothly speed-integrated)
863
1034
  float t = uTime * 0.55;
864
1035
  vec2 autoPos = vec2(
865
1036
  0.5 + 0.28 * cos(t * 0.9) * sin(t * 0.4),
@@ -900,7 +1071,7 @@ void main() {
900
1071
  dye = clamp(dye, vec2(0.0), vec2(1.0));
901
1072
 
902
1073
  fragColor = vec4(encodedVel, dye);
903
- }`,Me=`#version 300 es
1074
+ }`,Xe=`#version 300 es
904
1075
  precision highp float;
905
1076
 
906
1077
  in vec2 vUv;
@@ -909,6 +1080,10 @@ out vec4 fragColor;
909
1080
  uniform sampler2D uFeedback;
910
1081
  uniform float uTime;
911
1082
  uniform vec2 uResolution;
1083
+ uniform vec3 uBgColor;
1084
+ uniform float uHasBgColor;
1085
+ uniform float uTransparentBg;
1086
+ uniform float uTheme;
912
1087
  uniform vec3 uColor1;
913
1088
  uniform vec3 uColor2;
914
1089
  uniform vec3 uColor3;
@@ -918,7 +1093,6 @@ float hash(vec2 p) {
918
1093
  }
919
1094
 
920
1095
  void main() {
921
- // Sample gradients using actual FBO texture resolution (eliminates Retina specular banding)
922
1096
  vec2 fboTexel = 1.0 / max(vec2(textureSize(uFeedback, 0)), vec2(1.0));
923
1097
  vec4 state = texture(uFeedback, vUv);
924
1098
 
@@ -937,20 +1111,48 @@ void main() {
937
1111
  float spec = pow(max(dot(normal, lightDir), 0.0), 20.0) * smoothstep(0.08, 0.6, density);
938
1112
 
939
1113
  float flowEnergy = clamp(length(vel) * 1.4, 0.0, 1.0);
940
- vec3 baseDark = vec3(0.025, 0.03, 0.065) + uColor1 * 0.04;
941
-
942
- vec3 col = baseDark;
943
- col = mix(col, uColor1, smoothstep(0.03, 0.78, dyeA) * 0.92);
944
- col = mix(col, uColor2, smoothstep(0.06, 0.85, dyeB) * 0.88);
945
- col += uColor3 * smoothstep(0.18, 0.95, dyeA * dyeB * 1.6 + flowEnergy * density * 0.65) * 0.75;
946
- col += mix(vec3(1.0), uColor3, 0.4) * spec * 0.55;
1114
+ float m1 = smoothstep(0.03, 0.78, dyeA) * 0.92;
1115
+ float m2 = smoothstep(0.06, 0.85, dyeB) * 0.88;
1116
+ float m3 = smoothstep(0.18, 0.95, dyeA * dyeB * 1.6 + flowEnergy * density * 0.65) * 0.75;
947
1117
 
948
- float vig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.65;
1118
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
949
1119
  float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.015;
950
- col = max(col * vig + grain, vec3(0.0));
951
1120
 
952
- fragColor = vec4(col, 1.0);
953
- }`,ee=["#6366f1","#06b6d4","#f43f5e"];function te(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=c(o.colors[0],e[0]),r=c(o.colors[1]??t,e[1]),s=c(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=c(t[0],e[0]);return[r,r,c(e[2],e[2])]}if(t.length>1)return[c(t[0],e[0]),c(t[1],e[1]),c(t[2]??t[0],e[2])]}return[c(o.color1,e[0]),c(o.color2,e[1]),c(o.color3,e[2])]}function ie(o){return{uDissipation:typeof o.dissipation=="number"?o.dissipation:.975,uRadius:typeof o.radius=="number"?o.radius:.0045,uSwirl:typeof o.swirl=="number"?o.swirl:1.4}}var re={name:"fluid",mount(o,e){let i=new x(o,{fragmentShader:Me,feedbackShader:xe,feedbackScale:e.quality==="high"?.65:e.quality==="low"?.35:.5,feedbackFloat:!0,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:te(e,ee),uniforms:ie(e),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:te(t,ee),uniforms:ie(t),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var Re=`#version 300 es
1121
+ vec3 baseDark = uHasBgColor > 0.5
1122
+ ? uBgColor
1123
+ : (vec3(0.025, 0.03, 0.065) + uColor1 * 0.04);
1124
+ vec3 darkCol = baseDark;
1125
+ darkCol = mix(darkCol, uColor1, m1);
1126
+ darkCol = mix(darkCol, uColor2, m2);
1127
+ darkCol += uColor3 * m3;
1128
+ darkCol += mix(vec3(1.0), uColor3, 0.4) * spec * 0.55;
1129
+ float darkVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.65;
1130
+ darkCol = max(darkCol * darkVig + grain, vec3(0.0));
1131
+
1132
+ vec3 baseLight = uHasBgColor > 0.5 ? uBgColor : vec3(0.96, 0.953, 0.935);
1133
+ vec3 lightCol = baseLight;
1134
+ lightCol = mix(lightCol, uColor1, m1 * 0.58);
1135
+ lightCol = mix(lightCol, uColor2, m2 * 0.54);
1136
+ lightCol = mix(lightCol, uColor3, m3 * 0.50);
1137
+ lightCol += vec3(0.28) * spec * 0.42;
1138
+ float lightVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.12;
1139
+ lightCol = clamp(lightCol * lightVig + grain * 0.5, 0.0, 1.0);
1140
+
1141
+ vec3 opaqueCol = mix(lightCol, darkCol, darkAmt);
1142
+
1143
+ float wSum = m1 + m2 + m3 + 0.0001;
1144
+ vec3 dyeCol = (uColor1 * m1 + uColor2 * m2 + uColor3 * m3) / wSum;
1145
+ dyeCol += mix(vec3(1.0), uColor3, 0.4) * spec * 0.48;
1146
+ dyeCol = clamp(dyeCol + vec3(grain), 0.0, 1.0);
1147
+
1148
+ float alpha = clamp(max(max(m1, m2), max(m3, spec * 0.55)), 0.0, 1.0);
1149
+
1150
+ if (uTransparentBg > 0.5) {
1151
+ fragColor = vec4(dyeCol * alpha, alpha);
1152
+ } else {
1153
+ fragColor = vec4(opaqueCol, 1.0);
1154
+ }
1155
+ }`,Ee=_({name:"fluid",fragmentShader:Xe,feedbackShader:Ge,feedbackFloat:!0,defaultColors:["#6366f1","#06b6d4","#f43f5e"],resolveUniforms(o){let e=U(o,"#060810");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg,uDissipation:typeof o.dissipation=="number"?o.dissipation:.975,uRadius:typeof o.radius=="number"?o.radius:.0045,uSwirl:typeof o.swirl=="number"?o.swirl:1.4}}});var ze=`#version 300 es
954
1156
  precision highp float;
955
1157
 
956
1158
  in vec2 vUv;
@@ -991,25 +1193,21 @@ void main() {
991
1193
  vec2 vD = decodeVel(d);
992
1194
  vec2 vU = decodeVel(u);
993
1195
 
994
- // Vorticity confinement for wispy ink tendrils in still water
995
1196
  float vorticity = (vR.y - vL.y) - (vU.x - vD.x);
996
1197
  vec2 grad = vec2(abs(vU.y) - abs(vD.y), abs(vR.x) - abs(vL.x));
997
1198
  vec2 perp = normalize(grad + vec2(0.0001));
998
1199
  vel += vec2(perp.y, -perp.x) * vorticity * uCurl * dt * 1.65;
999
1200
 
1000
- // Advect velocity & ink pigments backward along flow
1001
1201
  vec2 backUv = clamp(vUv - vel * dt * 0.48 * clamp(uSpeed, 0.25, 3.0), texel, 1.0 - texel);
1002
1202
  vec4 adv = texture(uPrevFrame, backUv);
1003
1203
  vec2 advVel = decodeVel(adv);
1004
1204
 
1005
- // Water viscosity: velocity damps faster than suspended ink pigments
1006
1205
  float visc = pow(clamp(uDissipation * 0.985, 0.88, 0.992), dt * 60.0);
1007
1206
  float inkHold = pow(clamp(uDissipation + 0.006, 0.92, 0.998), dt * 60.0);
1008
1207
 
1009
1208
  vel = mix(advVel, (vL + vR + vD + vU) * 0.25, 0.07) * visc;
1010
1209
  vec2 ink = mix(adv.ba, (l.ba + r.ba + d.ba + u.ba) * 0.25, 0.035) * inkHold;
1011
1210
 
1012
- // Gentle ambient ink drift so canvas feels alive before pointer interaction
1013
1211
  float t = uTime * 0.42;
1014
1212
  vec2 driftPos = vec2(
1015
1213
  0.5 + 0.25 * sin(t * 0.85),
@@ -1022,7 +1220,6 @@ void main() {
1022
1220
  ink.x += driftSplat * (0.45 + 0.45 * sin(t * 1.2)) * dt * 0.85;
1023
1221
  ink.y += driftSplat * (0.45 + 0.45 * cos(t * 0.9)) * dt * 0.75;
1024
1222
 
1025
- // Pointer ink injection (strictly scoped to active container)
1026
1223
  if (uMouseActive > 0.01) {
1027
1224
  vec2 deltaP = (vUv - uMouse) * vec2(aspect, 1.0);
1028
1225
  float dist2 = dot(deltaP, deltaP);
@@ -1038,7 +1235,6 @@ void main() {
1038
1235
  ink.y += deposit * (0.35 + 0.65 * (1.0 - wave));
1039
1236
  }
1040
1237
 
1041
- // Press & hold drops a concentrated ink bloom
1042
1238
  if (uMouseDown > 0.5) {
1043
1239
  vec2 outward = normalize(deltaP + vec2(0.0001));
1044
1240
  float bloom = exp(-dist2 / max(uRadius * 2.4, 0.003));
@@ -1052,7 +1248,7 @@ void main() {
1052
1248
  vec2 encVel = clamp(vel * 0.5 + 0.5, vec2(0.02), vec2(0.98));
1053
1249
 
1054
1250
  fragColor = vec4(encVel, ink);
1055
- }`,we=`#version 300 es
1251
+ }`,Ne=`#version 300 es
1056
1252
  precision highp float;
1057
1253
 
1058
1254
  in vec2 vUv;
@@ -1061,6 +1257,10 @@ out vec4 fragColor;
1061
1257
  uniform sampler2D uFeedback;
1062
1258
  uniform float uTime;
1063
1259
  uniform vec2 uResolution;
1260
+ uniform vec3 uBgColor;
1261
+ uniform float uHasBgColor;
1262
+ uniform float uTransparentBg;
1263
+ uniform float uTheme;
1064
1264
  uniform vec3 uColor1;
1065
1265
  uniform vec3 uColor2;
1066
1266
  uniform vec3 uColor3;
@@ -1076,7 +1276,6 @@ void main() {
1076
1276
  float ink1 = fbo.b;
1077
1277
  float ink2 = fbo.a;
1078
1278
 
1079
- // Subtle refractive distortion along ink pigment gradient
1080
1279
  float hC = ink1 * 0.7 + ink2 * 0.55;
1081
1280
  float hL = dot(texture(uFeedback, vUv - vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.7, 0.55));
1082
1281
  float hR = dot(texture(uFeedback, vUv + vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.7, 0.55));
@@ -1090,30 +1289,51 @@ void main() {
1090
1289
  float p1 = mix(ink1, refFbo.b, 0.45);
1091
1290
  float p2 = mix(ink2, refFbo.a, 0.45);
1092
1291
 
1093
- // Water backdrop + Beer-Lambert style pigment absorption
1094
- vec3 waterBase = vec3(0.025, 0.03, 0.06) + uColor1 * 0.035;
1095
1292
  float absorb1 = smoothstep(0.02, 0.82, p1);
1096
1293
  float absorb2 = smoothstep(0.04, 0.86, p2);
1097
-
1098
- vec3 col = waterBase;
1099
- col = mix(col, uColor1, absorb1 * 0.92);
1100
- col = mix(col, uColor2, absorb2 * 0.86);
1101
-
1102
- // Rich filament veins where pigments fold and overlap
1103
1294
  float filament = smoothstep(0.22, 0.92, p1 * p2 * 1.7 + length(grad) * 2.2);
1104
- col = mix(col, uColor3, filament * 0.68);
1105
1295
 
1106
- // Soft water surface sheen along pigment ridges
1107
1296
  vec3 n = normalize(vec3((hL - hR) * 2.8, (hD - hU) * 2.8, 1.0));
1108
1297
  float rim = pow(1.0 - max(n.z, 0.0), 2.2) * smoothstep(0.05, 0.65, hC);
1109
- col += mix(vec3(0.9), uColor3, 0.45) * rim * 0.35;
1110
-
1111
- float vig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.62;
1112
1298
  float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.015;
1113
- col = max(col * vig + grain, vec3(0.0));
1114
1299
 
1115
- fragColor = vec4(col, 1.0);
1116
- }`,oe=["#1e1b4b","#0284c7","#e11d48"];function se(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=c(o.colors[0],e[0]),r=c(o.colors[1]??t,e[1]),s=c(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=c(t[0],e[0]);return[r,r,c(e[2],e[2])]}if(t.length>1)return[c(t[0],e[0]),c(t[1],e[1]),c(t[2]??t[0],e[2])]}return[c(o.color1,e[0]),c(o.color2,e[1]),c(o.color3,e[2])]}function ne(o){return{uDissipation:typeof o.dissipation=="number"?o.dissipation:.982,uRadius:typeof o.radius=="number"?o.radius:.004,uCurl:typeof o.curl=="number"?o.curl:1.75}}var ae={name:"ink",mount(o,e){let i=new x(o,{fragmentShader:we,feedbackShader:Re,feedbackScale:e.quality==="high"?.65:e.quality==="low"?.35:.5,feedbackFloat:!0,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:se(e,oe),uniforms:ne(e),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:se(t,oe),uniforms:ne(t),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var Ee=`#version 300 es
1300
+ if (uTransparentBg > 0.5) {
1301
+ float a1 = absorb1 * 0.92;
1302
+ float a2 = absorb2 * 0.86;
1303
+ float a3 = filament * 0.68;
1304
+ float wSum = a1 + a2 + a3 + 0.0001;
1305
+ vec3 inkCol = (uColor1 * a1 + uColor2 * a2 + uColor3 * a3) / wSum;
1306
+ inkCol += mix(vec3(0.9), uColor3, 0.45) * rim * 0.35;
1307
+ inkCol = clamp(inkCol + vec3(grain), 0.0, 1.0);
1308
+ float alpha = clamp(max(max(a1, a2), max(a3, rim * 0.35)), 0.0, 1.0);
1309
+ fragColor = vec4(inkCol * alpha, alpha);
1310
+ return;
1311
+ }
1312
+
1313
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
1314
+
1315
+ vec3 waterDark = uHasBgColor > 0.5
1316
+ ? uBgColor
1317
+ : (vec3(0.025, 0.03, 0.06) + uColor1 * 0.035);
1318
+ vec3 darkCol = waterDark;
1319
+ darkCol = mix(darkCol, uColor1, absorb1 * 0.92);
1320
+ darkCol = mix(darkCol, uColor2, absorb2 * 0.86);
1321
+ darkCol = mix(darkCol, uColor3, filament * 0.68);
1322
+ darkCol += mix(vec3(0.9), uColor3, 0.45) * rim * 0.35;
1323
+ float darkVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.62;
1324
+ darkCol = max(darkCol * darkVig + grain, vec3(0.0));
1325
+
1326
+ vec3 waterLight = uHasBgColor > 0.5 ? uBgColor : vec3(0.965, 0.955, 0.935);
1327
+ vec3 lightCol = waterLight;
1328
+ lightCol = mix(lightCol, uColor1 * 0.82, absorb1 * 0.68);
1329
+ lightCol = mix(lightCol, uColor2 * 0.86, absorb2 * 0.62);
1330
+ lightCol = mix(lightCol, uColor3 * 0.90, filament * 0.55);
1331
+ lightCol += vec3(0.14) * rim * 0.25;
1332
+ float lightVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.12;
1333
+ lightCol = clamp(lightCol * lightVig + grain * 0.5, 0.0, 1.0);
1334
+
1335
+ fragColor = vec4(mix(lightCol, darkCol, darkAmt), 1.0);
1336
+ }`,Fe=_({name:"ink",fragmentShader:Ne,feedbackShader:ze,feedbackFloat:!0,defaultColors:["#1e1b4b","#0284c7","#e11d48"],resolveUniforms(o){let e=U(o,"#060810");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg,uDissipation:typeof o.dissipation=="number"?o.dissipation:.982,uRadius:typeof o.radius=="number"?o.radius:.004,uCurl:typeof o.curl=="number"?o.curl:1.75}}});var Qe=`#version 300 es
1117
1337
  precision highp float;
1118
1338
 
1119
1339
  in vec2 vUv;
@@ -1154,18 +1374,15 @@ void main() {
1154
1374
  vec2 vD = decodeVel(d);
1155
1375
  vec2 vU = decodeVel(u);
1156
1376
 
1157
- // Vorticity confinement for wispy curling ink tendrils
1158
1377
  float curl = (vR.y - vL.y) - (vU.x - vD.x);
1159
1378
  vec2 grad = vec2(abs(vU.y) - abs(vD.y), abs(vR.x) - abs(vL.x));
1160
1379
  vec2 swirlDir = normalize(grad + vec2(0.0001));
1161
1380
  vel += vec2(swirlDir.y, -swirlDir.x) * curl * uCurl * dt * 1.5;
1162
1381
 
1163
- // Semi-Lagrangian advection along flow
1164
1382
  vec2 backUv = clamp(vUv - vel * dt * 0.52 * clamp(uSpeed, 0.25, 3.0), texel, 1.0 - texel);
1165
1383
  vec4 adv = texture(uPrevFrame, backUv);
1166
1384
  vec2 advVel = decodeVel(adv);
1167
1385
 
1168
- // Soft pressure-like neighbor smoothing keeps incompressible swirls silky
1169
1386
  vec2 avgVel = (vL + vR + vD + vU) * 0.25;
1170
1387
  vec2 avgInk = (l.ba + r.ba + d.ba + u.ba) * 0.25;
1171
1388
 
@@ -1175,7 +1392,6 @@ void main() {
1175
1392
  vel = mix(advVel, avgVel, 0.09) * velDecay;
1176
1393
  vec2 ink = mix(adv.ba, avgInk, 0.032) * inkDecay;
1177
1394
 
1178
- // Autonomous curving ink plumes (gives live video-like motion on load)
1179
1395
  float t = uTime * 0.45;
1180
1396
  for (int i = 0; i < 3; i++) {
1181
1397
  float fi = float(i);
@@ -1195,7 +1411,6 @@ void main() {
1195
1411
  ink.y += splat * (1.0 - pulse * 0.65) * dt * 0.75;
1196
1412
  }
1197
1413
 
1198
- // Interactive cursor stroke & click/hold ink bloom (strictly inside container)
1199
1414
  if (uMouseActive > 0.01) {
1200
1415
  vec2 diff = (vUv - uMouse) * vec2(aspect, 1.0);
1201
1416
  float distSq = dot(diff, diff);
@@ -1224,7 +1439,7 @@ void main() {
1224
1439
  vec2 encVel = clamp(vel * 0.5 + 0.5, vec2(0.02), vec2(0.98));
1225
1440
 
1226
1441
  fragColor = vec4(encVel, ink);
1227
- }`,Fe=`#version 300 es
1442
+ }`,$e=`#version 300 es
1228
1443
  precision highp float;
1229
1444
 
1230
1445
  in vec2 vUv;
@@ -1234,8 +1449,11 @@ uniform sampler2D uFeedback;
1234
1449
  uniform float uTime;
1235
1450
  uniform vec2 uResolution;
1236
1451
  uniform vec3 uBgColor;
1452
+ uniform float uHasBgColor;
1453
+ uniform float uHasExplicitLightMode;
1237
1454
  uniform float uTransparentBg;
1238
1455
  uniform float uLightMode;
1456
+ uniform float uTheme;
1239
1457
  uniform float uAbsorptionGain;
1240
1458
  uniform vec3 uColor1;
1241
1459
  uniform vec3 uColor2;
@@ -1254,7 +1472,6 @@ void main() {
1254
1472
  float pA = fbo.b;
1255
1473
  float pB = fbo.a;
1256
1474
 
1257
- // Fluid surface relief normal from pigment density gradient
1258
1475
  float hC = pA * 0.72 + pB * 0.58;
1259
1476
  float hL = dot(texture(uFeedback, vUv - vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.72, 0.58));
1260
1477
  float hR = dot(texture(uFeedback, vUv + vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.72, 0.58));
@@ -1266,38 +1483,40 @@ void main() {
1266
1483
  float diffuse = clamp(dot(normal, lightDir), 0.0, 1.0);
1267
1484
  float rimSheen = pow(clamp(dot(normal, normalize(vec3(0.4, 0.6, 0.7))), 0.0, 1.0), 8.0);
1268
1485
 
1269
- // Combine 3 palette tones across dual pigment channels
1270
1486
  vec3 tintMix = normalize(uColor1 * pA + uColor2 * pB + uColor3 * (pA * pB * 1.8) + vec3(0.0001));
1271
1487
  float totalInk = (pA + pB * 0.85) * uAbsorptionGain;
1272
1488
 
1273
- // Light water: Beer-Lambert exponential light absorption on solid bg
1489
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
1490
+ float effectiveLightMode = uHasExplicitLightMode > 0.5
1491
+ ? clamp(uLightMode, 0.0, 1.0)
1492
+ : (1.0 - darkAmt);
1493
+ vec3 effectiveBg = uHasBgColor > 0.5
1494
+ ? uBgColor
1495
+ : mix(vec3(0.96, 0.953, 0.933), vec3(0.032, 0.04, 0.075), darkAmt);
1496
+
1274
1497
  vec3 transmittance = exp(-tintMix * totalInk * 1.35);
1275
1498
  float inkMask = clamp(1.0 - exp(-hC * 1.5), 0.0, 1.0);
1276
- vec3 lightCol = uBgColor * transmittance;
1499
+ vec3 lightCol = effectiveBg * transmittance;
1277
1500
  lightCol *= mix(1.0, 0.90 + 0.16 * diffuse, inkMask * 0.72);
1278
1501
  lightCol += vec3(0.025) * rimSheen * inkMask * (1.0 - inkMask * 0.45);
1279
1502
 
1280
- // Dark water: Luminous bioluminescent plumes on solid bg
1281
1503
  vec3 luminous = (vec3(1.0) - exp(-tintMix * totalInk * 1.25)) * (0.86 + 0.24 * diffuse);
1282
- vec3 darkCol = uBgColor + luminous + luminous * rimSheen * 0.12;
1504
+ vec3 darkCol = effectiveBg + luminous + luminous * rimSheen * 0.12;
1283
1505
 
1284
- vec3 opaqueCol = mix(darkCol, lightCol, clamp(uLightMode, 0.0, 1.0));
1506
+ vec3 opaqueCol = mix(darkCol, lightCol, effectiveLightMode);
1285
1507
 
1286
- // Subtle vignette + fine organic grain on solid bg
1287
1508
  vec2 centered = vUv - 0.5;
1288
- float vignetteStrength = mix(0.36, 0.085, clamp(uLightMode, 0.0, 1.0));
1509
+ float vignetteStrength = mix(0.36, 0.085, effectiveLightMode);
1289
1510
  opaqueCol *= (1.0 - dot(centered, centered) * vignetteStrength);
1290
1511
  float grain = (hash12(vUv * 900.0 + fract(uTime * 0.05)) - 0.5) * 0.011;
1291
1512
  opaqueCol = clamp(opaqueCol + grain, 0.0, 1.0);
1292
1513
 
1293
- // Transparent backdrop mode: only render pigment/ink with alpha over page/body bg
1294
1514
  float inkAlpha = clamp(1.0 - exp(-totalInk * 1.35), 0.0, 1.0);
1295
1515
  vec3 inkRgb = clamp(tintMix * (0.82 + 0.28 * diffuse) + vec3(0.04) * rimSheen, 0.0, 1.0);
1296
1516
 
1297
1517
  if (uTransparentBg > 0.5) {
1298
- // Premultiplied alpha works cleanly with standard canvas alpha blending
1299
1518
  fragColor = vec4(inkRgb * inkAlpha, inkAlpha);
1300
1519
  } else {
1301
1520
  fragColor = vec4(opaqueCol, 1.0);
1302
1521
  }
1303
- }`,ce=["#1e3a5f","#2d3748","#0284c7"],Le="#f5f3ee";function Te(o){if(o==null)return!1;let e=String(o).trim().toLowerCase();if(!e||e==="transparent"||e==="none")return!0;let i=e.match(/^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+(?:\s*,\s*([\d.]+))?\s*\)$/);return i&&i[1]!==void 0?parseFloat(i[1])<=.001:!1}function Se(o){let e=o.replace("#","").trim(),i=e.length===3?e.split("").map(n=>n+n).join(""):e;if(i.length!==6)return!0;let t=parseInt(i.slice(0,2),16)/255,r=parseInt(i.slice(2,4),16)/255,s=parseInt(i.slice(4,6),16)/255;return .2126*t+.7152*r+.0722*s>.45}function le(o,e){if(Array.isArray(o.colors)){let t=c(o.colors[0],e[0]),r=c(o.colors[1]??t,e[1]),s=c(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=c(t[0],e[0]);return[r,r,c(e[2],e[2])]}return[c(t[0],e[0]),c(t[1],e[1]),c(t[2]??t[0],e[2])]}return[c(o.color1,e[0]),c(o.color2,e[1]),c(o.color3,e[2])]}function ue(o){let e=Te(o.bgColor),i=e?"#000000":c(o.bgColor,Le),t=g.hexToVec3Into(i,g.scratchVec3),r=Se(i)?1:0,s=typeof o.lightMode=="number"?o.lightMode:typeof o.lightMode=="boolean"?o.lightMode?1:0:r;return{uBgColor:[t[0],t[1],t[2]],uTransparentBg:e?1:0,uLightMode:s,uAbsorptionGain:typeof o.absorptionGain=="number"?o.absorptionGain:1.45,uDissipation:typeof o.dissipation=="number"?o.dissipation:.978,uRadius:typeof o.radius=="number"?o.radius:.0032,uCurl:typeof o.curl=="number"?o.curl:1.85}}var de={name:"aetheria",mount(o,e){let i=new x(o,{fragmentShader:Fe,feedbackShader:Ee,feedbackScale:e.quality==="high"?.65:e.quality==="low"?.35:.5,feedbackFloat:!0,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:le(e,ce),uniforms:ue(e),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:le(t,ce),uniforms:ue(t),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var fe={name:"tilt-3d",mount(o,e){let i=typeof e.maxTilt=="number"?e.maxTilt:12,t=typeof e.scale=="number"?e.scale:1.03,r=typeof e.perspective=="number"?e.perspective:900,s=e.glare!==!1,a=o.style.transform,n=o.style.position,l=o.style.overflow,u=o.style.willChange;o.style.willChange="transform";let d=null;s&&(getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.style.overflow="hidden",d=document.createElement("div"),Object.assign(d.style,{position:"absolute",inset:"0",pointerEvents:"none",borderRadius:"inherit",opacity:"0",transition:"opacity 0.25s ease",zIndex:"2"}),o.appendChild(d));let f=0,h=0,m=1,p=0,b=0,y=1,S=50,M=50,A=!1,W=I=>{let F=o.getBoundingClientRect(),L=(I.clientX-F.left)/F.width,G=(I.clientY-F.top)/F.height;f=(.5-G)*i*2,h=(L-.5)*i*2,m=t,S=L*100,M=G*100,A=!0,d&&(d.style.opacity="1")},z=()=>{f=0,h=0,m=1,A=!0,d&&(d.style.opacity="0")};return o.addEventListener("pointermove",W,{passive:!0}),o.addEventListener("pointerleave",z,{passive:!0}),{update(I,F){if(!A)return;let L=1-Math.exp(-12*F);p+=(f-p)*L,b+=(h-b)*L,y+=(m-y)*L,o.style.transform=`perspective(${r}px) rotateX(${p.toFixed(2)}deg) rotateY(${b.toFixed(2)}deg) scale3d(${y.toFixed(3)}, ${y.toFixed(3)}, 1)`,d&&(d.style.background=`radial-gradient(circle at ${S.toFixed(1)}% ${M.toFixed(1)}%, rgba(255,255,255,0.22), transparent 60%)`),Math.abs(f-p)<.02&&Math.abs(h-b)<.02&&Math.abs(m-y)<.001&&(A=!1,m===1&&(o.style.transform=a))},destroy(){o.removeEventListener("pointermove",W),o.removeEventListener("pointerleave",z),d?.remove(),o.style.transform=a,o.style.position=n,o.style.overflow=l,o.style.willChange=u}}}};var me={name:"magnetic",mount(o,e){let i=typeof e.strength=="number"?e.strength:.35,t=o.style.transform,r=o.style.willChange;o.style.willChange="transform";let s=0,a=0,n=0,l=0,u=!1,d=h=>{let m=o.getBoundingClientRect(),p=m.left+m.width/2,b=m.top+m.height/2;s=(h.clientX-p)*i,a=(h.clientY-b)*i,u=!0},f=()=>{s=0,a=0,u=!0};return o.addEventListener("pointermove",d,{passive:!0}),o.addEventListener("pointerleave",f,{passive:!0}),{update(h,m){if(!u)return;let p=1-Math.exp(-10*m);n+=(s-n)*p,l+=(a-l)*p,o.style.transform=`translate3d(${n.toFixed(2)}px, ${l.toFixed(2)}px, 0)`,Math.abs(s-n)<.05&&Math.abs(a-l)<.05&&(u=!1,s===0&&a===0&&(o.style.transform=t))},destroy(){o.removeEventListener("pointermove",d),o.removeEventListener("pointerleave",f),o.style.transform=t,o.style.willChange=r}}}};_.register(K).register(Z).register(re).register(ae).register(de).register(fe).register(me);var X=_;typeof window<"u"&&(window.FluxFX=_);function E(o,e={},i=!1){let t=O(null),r=Array.isArray(o)?o.join(" "):o,s=JSON.stringify(e),a=O(s);a.current=s;let n=O(!1),l=O(null);return he(()=>{if(i||typeof window>"u")return;let u=t.current;if(!u||!r.trim())return;let d=a.current,f=JSON.parse(d),m=r.trim().split(/\s+/).map(p=>X.apply(u,p,f));return n.current=!0,l.current=d,()=>{n.current=!1,l.current=null,m.forEach(p=>p())}},[r,i]),he(()=>{if(!n.current||i||typeof window>"u"||l.current===s)return;let u=t.current;if(!u||!r.trim())return;let d=JSON.parse(s);r.trim().split(/\s+/).forEach(h=>{X.update(u,h,d)}),l.current=s},[s,r,i]),t}function xt({as:o="section",speed:e=1,quality:i="medium",colors:t=["#4f46e5","#06b6d4","#ec4899"],interactive:r=!0,respectReducedMotion:s=!0,disabled:a=!1,children:n,...l}){let u=E("aurora",{speed:e,quality:i,color1:t[0],color2:t[1],color3:t[2],interactive:r,respectReducedMotion:s},a);return w.createElement(o,{ref:u,...l},n)}function Mt({as:o="section",speed:e=1,quality:i="medium",colors:t=["#0f172a","#94a3b8","#38bdf8"],interactive:r=!0,respectReducedMotion:s=!0,disabled:a=!1,children:n,...l}){let u=E("liquid-metal",{speed:e,quality:i,color1:t[0],color2:t[1],color3:t[2],interactive:r,respectReducedMotion:s},a);return w.createElement(o,{ref:u,...l},n)}function Rt({as:o="section",speed:e=1,quality:i="medium",colors:t=["#6366f1","#06b6d4","#f43f5e"],dissipation:r=.975,radius:s=.0045,swirl:a=1.4,interactive:n=!0,respectReducedMotion:l=!0,disabled:u=!1,children:d,...f}){let h=E("fluid",{speed:e,quality:i,color1:t[0],color2:t[1],color3:t[2],dissipation:r,radius:s,swirl:a,interactive:n,respectReducedMotion:l},u);return w.createElement(o,{ref:h,...f},d)}function wt({as:o="div",maxTilt:e=12,scale:i=1.03,perspective:t=900,glare:r=!0,disabled:s=!1,children:a,...n}){let l=E("tilt-3d",{maxTilt:e,scale:i,perspective:t,glare:r},s);return w.createElement(o,{ref:l,...n},a)}function Et({as:o="div",strength:e=.35,disabled:i=!1,style:t,children:r,...s}){let a=E("magnetic",{strength:e},i);return w.createElement(o,{ref:a,style:{display:"inline-block",...t},...s},r)}function Ft({as:o="section",speed:e=1,quality:i="medium",colors:t=["#1e1b4b","#0284c7","#e11d48"],dissipation:r=.982,radius:s=.004,curl:a=1.75,interactive:n=!0,respectReducedMotion:l=!0,disabled:u=!1,children:d,...f}){let h=E("ink",{speed:e,quality:i,color1:t[0],color2:t[1],color3:t[2],dissipation:r,radius:s,curl:a,interactive:n,respectReducedMotion:l},u);return w.createElement(o,{ref:h,...f},d)}function Lt({as:o="section",speed:e=1,quality:i="medium",colors:t=["#1e3a5f","#2d3748","#0284c7"],bgColor:r="#f5f3ee",lightMode:s,absorptionGain:a=1.45,dissipation:n=.978,radius:l=.0032,curl:u=1.85,interactive:d=!0,respectReducedMotion:f=!0,disabled:h=!1,children:m,...p}){let b=E("aetheria",{speed:e,quality:i,color1:t[0],color2:t[1],color3:t[2],bgColor:r,lightMode:s,absorptionGain:a,dissipation:n,radius:l,curl:u,interactive:d,respectReducedMotion:f},h);return w.createElement(o,{ref:b,...p},m)}export{Lt as Aetheria,xt as Aurora,Rt as Fluid,Ft as Ink,Mt as LiquidMetal,Et as Magnetic,wt as TiltCard,E as useFX};
1522
+ }`,ke=_({name:"aetheria",fragmentShader:$e,feedbackShader:Qe,feedbackFloat:!0,defaultColors:["#1e3a5f","#2d3748","#0284c7"],resolveUniforms(o){let e=U(o,"#f5f3ee"),t=typeof o.lightMode=="number"||typeof o.lightMode=="boolean"||e.hasBgColor,i=Se(e.bgHex)?1:0,r=typeof o.lightMode=="number"?o.lightMode:typeof o.lightMode=="boolean"?o.lightMode?1:0:i;return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uHasExplicitLightMode:t?1:0,uTransparentBg:e.uTransparentBg,uLightMode:r,uAbsorptionGain:typeof o.absorptionGain=="number"?o.absorptionGain:1.45,uDissipation:typeof o.dissipation=="number"?o.dissipation:.978,uRadius:typeof o.radius=="number"?o.radius:.0032,uCurl:typeof o.curl=="number"?o.curl:1.85}}});var Pe={name:"tilt-3d",mount(o,e){let t=typeof e.maxTilt=="number"?e.maxTilt:12,i=typeof e.scale=="number"?e.scale:1.03,r=typeof e.perspective=="number"?e.perspective:900,s=e.glare!==!1,a=e.respectReducedMotion??!0,n=o.style.transform,l=o.style.position,c=o.style.overflow,u=o.style.willChange,h=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)"):null,f=a&&(h?.matches??!1);f||(o.style.willChange="transform");let d=null;s&&(getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.style.overflow="hidden",d=document.createElement("div"),Object.assign(d.style,{position:"absolute",inset:"0",pointerEvents:"none",borderRadius:"inherit",opacity:"0",transition:"opacity 0.25s ease",zIndex:"2"}),o.appendChild(d));let m=0,p=0,v=1,g=0,b=0,y=1,L=50,k=50,S=!1,E=!1,C=null,R=null,P=!0,z=()=>{P=!0},Be=()=>{let F=o.getBoundingClientRect();R={left:F.left,top:F.top,width:F.width,height:F.height},P=!1},ce=F=>{let I=a&&F.matches;f!==I&&(f=I,f?(m=0,p=0,v=1,g=0,b=0,y=1,S=!1,d&&(d.style.opacity="0"),o.style.transform=n,o.style.willChange=u):(o.style.willChange="transform",P=!0),C?.())},ue=()=>{P=!0},he=F=>{if(E||f||((P||!R)&&Be(),!R||R.width<=0||R.height<=0))return;let I=(F.clientX-R.left)/R.width,H=(F.clientY-R.top)/R.height;m=(.5-H)*t*2,p=(I-.5)*t*2,v=i,L=I*100,k=H*100,S=!0,d&&(d.style.opacity="1"),C?.()},de=()=>{f||(m=0,p=0,v=1,d&&(d.style.opacity="0"),(Math.abs(g)>.01||Math.abs(b)>.01||Math.abs(y-1)>.001)&&(S=!0,E||C?.()))},$=null;return typeof ResizeObserver<"u"&&($=new ResizeObserver(z),$.observe(o)),h&&typeof h.addEventListener=="function"&&h.addEventListener("change",ce),o.addEventListener("pointerenter",ue,{passive:!0}),o.addEventListener("pointermove",he,{passive:!0}),o.addEventListener("pointerleave",de,{passive:!0}),window.addEventListener("resize",z,{passive:!0}),window.addEventListener("scroll",z,{passive:!0,capture:!0}),{update(F,I){if(!S||E||f)return;let H=1-Math.exp(-12*I);if(g+=(m-g)*H,b+=(p-b)*H,y+=(v-y)*H,d&&(d.style.background=`radial-gradient(circle at ${L.toFixed(1)}% ${k.toFixed(1)}%, rgba(255,255,255,0.22), transparent 60%)`),Math.abs(m-g)<.02&&Math.abs(p-b)<.02&&Math.abs(v-y)<.001){g=m,b=p,y=v,S=!1,o.style.transform=v===1&&m===0&&p===0?n:`perspective(${r}px) rotateX(${g.toFixed(2)}deg) rotateY(${b.toFixed(2)}deg) scale3d(${y.toFixed(3)}, ${y.toFixed(3)}, 1)`;return}o.style.transform=`perspective(${r}px) rotateX(${g.toFixed(2)}deg) rotateY(${b.toFixed(2)}deg) scale3d(${y.toFixed(3)}, ${y.toFixed(3)}, 1)`},isIdle(){return!S||E||f},onWake(F){C=F},pause(){E=!0},resume(){E=!1,P=!0,S&&!f&&C?.()},destroy(){C=null,S=!1,R=null,$?.disconnect(),$=null,h&&typeof h.removeEventListener=="function"&&h.removeEventListener("change",ce),o.removeEventListener("pointerenter",ue),o.removeEventListener("pointermove",he),o.removeEventListener("pointerleave",de),window.removeEventListener("resize",z),window.removeEventListener("scroll",z,!0),d?.remove(),o.style.transform=n,o.style.position=l,o.style.overflow=c,o.style.willChange=u}}}};var De={name:"magnetic",mount(o,e){let t=typeof e.strength=="number"?e.strength:.35,i=e.respectReducedMotion??!0,r=o.style.transform,s=o.style.willChange,a=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)"):null,n=i&&(a?.matches??!1);n||(o.style.willChange="transform");let l=0,c=0,u=0,h=0,f=!1,d=!1,m=null,p=null,v=!0,g=()=>{v=!0},b=()=>{let C=o.getBoundingClientRect();p={left:C.left-u,top:C.top-h,width:C.width,height:C.height},v=!1},y=C=>{let R=i&&C.matches;n!==R&&(n=R,n?(l=0,c=0,u=0,h=0,f=!1,o.style.transform=r,o.style.willChange=s):(o.style.willChange="transform",v=!0),m?.())},L=()=>{v=!0},k=C=>{if(d||n||((v||!p)&&b(),!p||p.width<=0||p.height<=0))return;let R=p.left+p.width*.5,P=p.top+p.height*.5;l=(C.clientX-R)*t,c=(C.clientY-P)*t,f=!0,m?.()},S=()=>{n||(l=0,c=0,(Math.abs(u)>.01||Math.abs(h)>.01)&&(f=!0,d||m?.()))},E=null;return typeof ResizeObserver<"u"&&(E=new ResizeObserver(g),E.observe(o)),a&&typeof a.addEventListener=="function"&&a.addEventListener("change",y),o.addEventListener("pointerenter",L,{passive:!0}),o.addEventListener("pointermove",k,{passive:!0}),o.addEventListener("pointerleave",S,{passive:!0}),window.addEventListener("resize",g,{passive:!0}),window.addEventListener("scroll",g,{passive:!0,capture:!0}),{update(C,R){if(!f||d||n)return;let P=1-Math.exp(-10*R);if(u+=(l-u)*P,h+=(c-h)*P,Math.abs(l-u)<.05&&Math.abs(c-h)<.05){u=l,h=c,f=!1,o.style.transform=l===0&&c===0?r:`translate3d(${u.toFixed(2)}px, ${h.toFixed(2)}px, 0)`;return}o.style.transform=`translate3d(${u.toFixed(2)}px, ${h.toFixed(2)}px, 0)`},isIdle(){return!f||d||n},onWake(C){m=C},pause(){d=!0},resume(){d=!1,v=!0,f&&!n&&m?.()},destroy(){m=null,f=!1,p=null,E?.disconnect(),E=null,a&&typeof a.removeEventListener=="function"&&a.removeEventListener("change",y),o.removeEventListener("pointerenter",L),o.removeEventListener("pointermove",k),o.removeEventListener("pointerleave",S),window.removeEventListener("resize",g),window.removeEventListener("scroll",g,!0),o.style.transform=r,o.style.willChange=s}}}};Z.register(Re).register(Le).register(Ee).register(Fe).register(ke).register(Pe).register(De);var le=Z;typeof window<"u"&&(window.FluxFX=Z);function O(o,e={},t=!1){let i=ee(null),r=Array.isArray(o)?o.join(" "):o,s=JSON.stringify(e),a=ee(s);a.current=s;let n=ee(!1),l=ee(null);return Ae(()=>{if(t||typeof window>"u")return;let c=i.current;if(!c||!r.trim())return;let u=a.current,h=JSON.parse(u),d=r.trim().split(/\s+/).map(m=>le.apply(c,m,h));return n.current=!0,l.current=u,()=>{n.current=!1,l.current=null,d.forEach(m=>m())}},[r,t]),Ae(()=>{if(!n.current||t||typeof window>"u"||l.current===s)return;let c=i.current;if(!c||!r.trim())return;let u=JSON.parse(s);r.trim().split(/\s+/).forEach(f=>{le.update(c,f,u)}),l.current=s},[s,r,t]),i}function Wt({as:o="section",speed:e=1,quality:t="medium",colors:i=["#4f46e5","#06b6d4","#ec4899"],bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,interactive:m=!0,respectReducedMotion:p=!0,disabled:v=!1,children:g,...b}){let y=O("aurora",{speed:e,quality:t,colors:i,bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,interactive:m,respectReducedMotion:p},v);return V.createElement(o,{ref:y,...b},g)}function Gt({as:o="section",speed:e=1,quality:t="medium",colors:i=["#0f172a","#94a3b8","#38bdf8"],bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,interactive:m=!0,respectReducedMotion:p=!0,disabled:v=!1,children:g,...b}){let y=O("liquid-metal",{speed:e,quality:t,colors:i,bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,interactive:m,respectReducedMotion:p},v);return V.createElement(o,{ref:y,...b},g)}function Xt({as:o="section",speed:e=1,quality:t="medium",colors:i=["#6366f1","#06b6d4","#f43f5e"],bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,dissipation:m=.975,radius:p=.0045,swirl:v=1.4,interactive:g=!0,respectReducedMotion:b=!0,disabled:y=!1,children:L,...k}){let S=O("fluid",{speed:e,quality:t,colors:i,bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,dissipation:m,radius:p,swirl:v,interactive:g,respectReducedMotion:b},y);return V.createElement(o,{ref:S,...k},L)}function zt({as:o="div",maxTilt:e=12,scale:t=1.03,perspective:i=900,glare:r=!0,respectReducedMotion:s=!0,disabled:a=!1,children:n,...l}){let c=O("tilt-3d",{maxTilt:e,scale:t,perspective:i,glare:r,respectReducedMotion:s},a);return V.createElement(o,{ref:c,...l},n)}function Nt({as:o="div",strength:e=.35,respectReducedMotion:t=!0,disabled:i=!1,style:r,children:s,...a}){let n=O("magnetic",{strength:e,respectReducedMotion:t},i);return V.createElement(o,{ref:n,style:{display:"inline-block",...r},...a},s)}function Qt({as:o="section",speed:e=1,quality:t="medium",colors:i=["#1e1b4b","#0284c7","#e11d48"],bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,dissipation:m=.982,radius:p=.004,curl:v=1.75,interactive:g=!0,respectReducedMotion:b=!0,disabled:y=!1,children:L,...k}){let S=O("ink",{speed:e,quality:t,colors:i,bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,dissipation:m,radius:p,curl:v,interactive:g,respectReducedMotion:b},y);return V.createElement(o,{ref:S,...k},L)}function $t({as:o="section",speed:e=1,quality:t="medium",colors:i=["#1e3a5f","#2d3748","#0284c7"],bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,lightMode:m,absorptionGain:p=1.45,dissipation:v=.978,radius:g=.0032,curl:b=1.85,interactive:y=!0,respectReducedMotion:L=!0,disabled:k=!1,children:S,...E}){let C=O("aetheria",{speed:e,quality:t,colors:i,bgColor:r,theme:s,lightColors:a,darkColors:n,scrollColors:l,trackScroll:c,layer:u,preserveBg:h,adaptToSurface:f,overlayOpacity:d,lightMode:m,absorptionGain:p,dissipation:v,radius:g,curl:b,interactive:y,respectReducedMotion:L},k);return V.createElement(o,{ref:C,...E},S)}export{$t as Aetheria,Wt as Aurora,Xt as Fluid,Qt as Ink,Gt as LiquidMetal,Nt as Magnetic,zt as TiltCard,O as useFX};