string-tune-3d 0.0.6 → 0.0.8

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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var StringTune3D=(()=>{var ee=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var le=Object.prototype.hasOwnProperty;var ce=(h,t)=>{for(var e in t)ee(h,e,{get:t[e],enumerable:!0})},he=(h,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of oe(t))!le.call(h,i)&&i!==e&&ee(h,i,{get:()=>t[i],enumerable:!(r=ae(t,i))||r.enumerable});return h};var ue=h=>he(ee({},"__esModule",{value:!0}),h);var be={};ce(be,{String3D:()=>G,String3DCamera:()=>N,String3DCustomFilterRegistry:()=>R,String3DObject:()=>D,String3DRenderer:()=>_,String3DScene:()=>W,String3DSynchronizer:()=>H,ThreeJSEngine:()=>$,ThreeJSProvider:()=>Q});var de=class{constructor(){this.desktop={rebuild:{width:!0,height:!0,scrollHeight:!0}},this.mobile={rebuild:{width:!0,height:!0,scrollHeight:!0}}}},X=class{constructor(h){this.objectMapOnPage=new Map,this.objectsOnPage=[],this.objectMap=new Map,this.objects=[],this.htmlKey="",this._type=1,this.permissions=new de,this.tools=h.tools,this.data=h.data,this.settings=h.settings,this.events=h.events,this.centers=h.centers,this.hover=h.hover,this.attributesToMap=[{key:"active",type:"boolean",fallback:this.settings.active},{key:"fixed",type:"boolean",fallback:this.settings.fixed},{key:"outside-container",type:"boolean",fallback:this.settings["outside-container"]},{key:"repeat",type:"boolean",fallback:this.settings.repeat},{key:"self-disable",type:"boolean",fallback:this.settings["self-disable"]},{key:"abs",type:"boolean",fallback:this.settings.abs},{key:"key",type:"string",fallback:this.settings.key},{key:"offset-top",type:"dimension",fallback:this.settings["offset-top"]},{key:"offset-bottom",type:"dimension",fallback:this.settings["offset-bottom"]},{key:"inview-top",type:"dimension",fallback:this.settings["inview-top"]},{key:"inview-bottom",type:"dimension",fallback:this.settings["inview-bottom"]},{key:"start",type:"number",fallback:(t,e,r)=>{let i=r.top;return Math.floor(i)+this.data.scroll.container.scrollTop*this.data.viewport.transformScale}},{key:"end",type:"number",fallback:(t,e,r)=>{let i=r.top,s=r.height;return i+s-this.data.scroll.transformedCurrent}},{key:"size",type:"number",fallback:(t,e,r)=>r.height},{key:"half-width",type:"number",fallback:(t,e,r)=>r.width/2},{key:"half-height",type:"number",fallback:(t,e,r)=>r.height/2},{key:"enter-el",type:"string",fallback:this.settings["enter-el"]},{key:"enter-vp",type:"string",fallback:this.settings["enter-vp"]},{key:"exit-el",type:"string",fallback:this.settings["exit-el"]},{key:"exit-vp",type:"string",fallback:this.settings["exit-vp"]}]}get type(){return this._type}initializeObject(h,t,e,r){let i=this.tools.boundingClientRect.process({element:e});for(let{key:s,type:n,fallback:a,transform:l}of this.attributesToMap){let o=typeof a=="function"?a(e,t,i):a,c=this.tools.domAttribute.process({element:e,key:s,fallback:r[s]??this.settings[s]??o}),p=this.parseAttribute(c,n,{element:e,boundingRect:i,viewportHeight:this.data.viewport.windowHeight,baseRem:this.data.viewport.baseRem});l&&(p=l(p)),t.setProperty(s,p)}}calculatePositions(h,t){let e=h.getProperty("start"),r=h.getProperty("size"),i=h.getProperty("offset-bottom"),s=h.getProperty("offset-top"),n=h.getProperty("enter-el"),a=h.getProperty("enter-vp"),l=h.getProperty("exit-el"),o=h.getProperty("exit-vp"),c=0,p=0,m=0,u=0;n==="top"&&a==="top"||n==="left"&&a==="left"?(m=-t+1,c=e-i):n==="top"&&a==="bottom"||n==="left"&&a==="right"?c=e-t-i:n==="bottom"&&a==="top"||n==="right"&&a==="left"?(m=-t-r+1,c=e+r-i):(n==="bottom"&&a==="bottom"||n==="right"&&a==="right")&&(m=-r+1,c=e-t+r-i),l==="top"&&o==="top"||l==="left"&&o==="left"?(u=-r+1,p=e+s):l==="top"&&o==="bottom"||l==="left"&&o==="right"?(u=-t-r+1,p=e-t+s):l==="bottom"&&o==="top"||l==="right"&&o==="left"?p=e+r+s:(l==="bottom"&&o==="bottom"||l==="right"&&o==="right")&&(u=-t+1,p=e-t+r+s),h.setProperty("start-bias",m),h.setProperty("end-bias",u),h.setProperty("start-position",c-this.data.scroll.topPosition),h.setProperty("end-position",p-this.data.scroll.topPosition),h.setProperty("difference-position",p-c);let g=h.getProperty("inview-top")??0,d=h.getProperty("inview-bottom")??0;h.setProperty("inview-start-position",h.getProperty("start-position")+g),h.setProperty("inview-end-position",h.getProperty("end-position")+d)}parseAttribute(h,t,e={}){if(h==null)return null;if(typeof t=="object"&&t.type==="enum")return t.values.includes(h)?h:t.values[0];switch(t){case"number":return parseFloat(h);case"boolean":return h===""||h==="true";case"json":try{return JSON.parse(h)}catch{return null}case"tuple":return h.trim().split(/\s+/);case"easing":return this.tools.easingFunction.process({easing:h});case"color":return this.tools.colorParser.process({value:h});case"dimension":return h=="0"?0:e.element!=null&&e.viewportHeight!=null&&e.baseRem!=null&&e.boundingRect!=null?this.tools.unitParser.process({value:h,element:e.element,viewportHeight:e.viewportHeight,boundingRect:e.boundingRect,baseRem:e.baseRem}):0;case"breakpoint-dimension":if(e.element!=null&&e.viewportHeight!=null&&e.baseRem!=null&&e.boundingRect!=null){let r=h.trim().split("|"),i=[];for(let s of r)if(s.includes(":")){let[n,a]=s.split(":");i.push({breakpoint:parseInt(n),value:this.tools.unitParser.process({value:`${a}|`,element:e.element,viewportHeight:e.viewportHeight,boundingRect:e.boundingRect,baseRem:e.baseRem})})}else i.push({breakpoint:0,value:this.tools.unitParser.process({value:s,element:e.element,viewportHeight:e.viewportHeight,boundingRect:e.boundingRect,baseRem:e.baseRem})});return i}default:return h}}canConnect(h){return h.keys.includes(this.htmlKey)}connectObject(h){h.connect(this),this.onObjectConnected(h)}enterObject(h,t){this.objectMap.has(h)||(this.objectMap.set(h,t),this.objects.push(t))}exitObject(h){let t=this.objectMap.get(h);if(!t)return;this.objectMap.delete(h);let e=this.objects.indexOf(t);e!==-1&&this.objects.splice(e,1)}addObject(h,t){this.objectMapOnPage.has(h)||(this.objectMapOnPage.set(h,t),this.objectsOnPage.push(t))}removeObject(h){let t=this.objectMapOnPage.get(h);if(!t)return;this.objectMapOnPage.delete(h);let e=this.objectsOnPage.indexOf(t);e!==-1&&this.objectsOnPage.splice(e,1),this.onObjectDisconnected(t)}onObjectConnected(h){}onObjectDisconnected(h){}applyToElementAndConnects(h,t,e=t){h.getProperty("self-disable")!==!0&&t(h.htmlElement),h.mirrorObjects.forEach(r=>e(r.htmlElement,r))}destroy(){this.objects=[],this.objectMap=new Map}onInit(){}onFrame(h){}onMutate(h){}onScrollMeasure(h){}onMouseMoveMeasure(h){}onResize(){}onResizeWidth(){}onScroll(h){}onDirectionChange(){}onScrollStart(){}onScrollStop(){}onScrollDirectionChange(){}onAxisChange(){}onDeviceChange(){}onScrollConfigChange(){}onSettingsChange(){}onDOMRebuild(){}onMouseMove(h){}onWheel(h){}onDOMMutate(h,t){}};var pe=class{constructor(){this.pendingVars=new Map,this.pendingProps=new Map,this.isOpen=!1}begin(){this.isOpen||(this.isOpen=!0)}setVars(h,t){if(!this.isOpen){console.warn("StyleTxn: call begin() first to set custom properties.");return}let e=this.pendingVars.get(h)??{};for(let[r,i]of Object.entries(t))e[r]!==i&&(e[r]=i);this.pendingVars.set(h,e)}setProps(h,t){if(!this.isOpen){console.warn("StyleTxn: call begin() first to set standard properties.");return}let e=this.pendingProps.get(h)??{};for(let[r,i]of Object.entries(t))e[r]!==i&&(e[r]=i);this.pendingProps.set(h,e)}run(h){let t=this.isOpen;t||this.begin();try{h(),t||this.commit()}catch(e){throw t||this.cancel(),e}}commit(){if(this.isOpen){this.isOpen=!1;for(let[h,t]of this.pendingVars){let e=h.style;for(let[r,i]of Object.entries(t))e.setProperty(r,String(i))}this.pendingVars.clear();for(let[h,t]of this.pendingProps){let e=h.style;for(let[r,i]of Object.entries(t))e[r]=String(i)}this.pendingProps.clear()}}cancel(){this.pendingVars.clear(),this.pendingProps.clear(),this.isOpen=!1}},ie=new pe;var Se=1/240;var me=class{constructor(){this.measureQueue=[],this.mutateQueue=[],this.scheduled=!1}measure(h){this.measureQueue.push(h),this.schedule()}mutate(h){this.mutateQueue.push(h),this.schedule()}schedule(){this.scheduled||(this.scheduled=!0,requestAnimationFrame(()=>{let h=this.measureQueue;this.measureQueue=[];for(let e=0;e<h.length;e++)try{h[e]()}catch(r){console.error("Error in frameDOM measure task:",r)}let t=this.mutateQueue;this.mutateQueue=[];for(let e=0;e<t.length;e++)try{t[e]()}catch(r){console.error("Error in frameDOM mutate task:",r)}this.scheduled=!1}))}},Me=new me;var we=Math.PI*2,xe=180/Math.PI;var se=(h=>(h.ACTIVE="-active",h.ENTERING="-entering",h.LEAVING="-leaving",h.DISABLED="-disabled",h))(se||{}),ge={PROGRESS:"--sequence-progress",DIRECTION:"--sequence-direction"},fe=class ne extends X{constructor(t){super(t),this.activeStep=new Map,this.leavingStep=new Map,this.transitions=new Map,this.elementIndex=new Map,this.triggerElements=new Map,this.globalSettings=new Map,this.initialized=!1,this.onTriggerClick=e=>{let r=this.triggerElements.get(e.currentTarget);if(!r)return;let i=this.activeStep.get(r.slider)??0,s=this.getMaxStep(r.slider),n,a;if(r.step==="next"){if(n=i+1,a=1,!this.elementIndex.has(`${r.slider}[${n}]`))if(r.loop&&s>=0)n=0;else return}else if(r.step==="prev"){if(n=i-1,a=-1,n<0)if(r.loop&&s>=0)n=s;else return;if(!this.elementIndex.has(`${r.slider}[${n}]`))return}else{if(n=r.step,i===n)return;a=n>i?1:-1}this.startTransition(r.slider,n,a)},this.htmlKey="sequence",this.defaultDuration=this.settings["sequence-duration"]??600,this.attributesToMap=[...this.attributesToMap,{key:"sequence",type:"string",fallback:""},{key:"sequence-trigger",type:"string",fallback:""},{key:"entering-easing",type:"string",fallback:""},{key:"leaving-easing",type:"string",fallback:""},{key:"entering-duration",type:"string",fallback:""},{key:"leaving-duration",type:"string",fallback:""},{key:"sequence-duration",type:"string",fallback:""},{key:"active-step",type:"string",fallback:""}]}onInit(){super.onInit(),this.events.on("sequence",this.onSequenceEvent.bind(this)),this.scanStandaloneTriggers()}scanStandaloneTriggers(){let t=document.querySelectorAll("[string-sequence-trigger]:not([string-inited])");for(let e of t){let r=e.getAttribute("string-sequence-trigger"),i=r?this.parseTriggerKey(r):null;i&&(this.triggerElements.set(e,i),e.addEventListener("click",this.onTriggerClick))}}parseGlobalSettingsFromObject(t){let e=i=>t.getProperty(i),r=e("sequence-duration");this.tryParseGlobalSetting(r,"enteringDuration"),this.tryParseGlobalSetting(r,"leavingDuration"),this.tryParseGlobalSetting(e("entering-duration"),"enteringDuration"),this.tryParseGlobalSetting(e("leaving-duration"),"leavingDuration"),this.tryParseGlobalSetting(e("entering-easing"),"enteringEasing"),this.tryParseGlobalSetting(e("leaving-easing"),"leavingEasing"),this.tryParseGlobalSetting(e("active-step"),"activeStep")}tryParseGlobalSetting(t,e){if(!t)return;let r=t.match(/^(.+)\[(.+)\]$/);if(!r)return;let[,i,s]=r,n=this.globalSettings.get(i)??{};this.globalSettings.set(i,n),n[e]=e==="enteringEasing"||e==="leavingEasing"?s:parseFloat(s),this.applyGlobalSettingsToExistingObjects(i)}applyGlobalSettingsToExistingObjects(t){let e=this.globalSettings.get(t);if(e){for(let[r,i]of this.elementIndex)if(this.parseSequenceKey(r)?.slider===t){e.enteringDuration!==void 0&&(i.enteringDuration=e.enteringDuration),e.leavingDuration!==void 0&&(i.leavingDuration=e.leavingDuration);for(let s of i.objects)this.resolveEasings(s,r)}}}initializeSliders(){let t=new Set;for(let e of this.elementIndex.keys()){let r=this.parseSequenceKey(e);r&&t.add(r.slider)}for(let e of t){if(this.activeStep.has(e))continue;let r=this.globalSettings.get(e)?.activeStep??0;this.elementIndex.has(`${e}[${r}]`)||(r=0),this.switchInstant(e,r,1)}}tryApplyPendingActiveStep(t){if(this.activeStep.has(t))return;let e=this.globalSettings.get(t)?.activeStep;e!==void 0&&this.elementIndex.has(`${t}[${e}]`)&&this.switchInstant(t,e,1)}canConnect(t){return t.keys.includes("sequence")||t.keys.includes("sequence-trigger")}onObjectConnected(t){super.onObjectConnected(t),this.parseGlobalSettingsFromObject(t);let e=t.getProperty("sequence"),r=t.getProperty("sequence-trigger");if(!e&&r){let i=this.parseTriggerKey(r);i&&typeof i.step=="number"&&(e=`${i.slider}[${i.step}]`,t.setProperty("sequence",e))}if(e){let i=this.parseSequenceKey(e);if(i){let s=this.elementIndex.get(e);if(!s){let{enteringDuration:a,leavingDuration:l}=this.resolveDurations(t,e);s={objects:[],enteringDuration:a,leavingDuration:l},this.elementIndex.set(e,s)}s.objects.push(t),this.resolveEasings(t,e);let n=this.activeStep.get(i.slider);this.setState(t,n===i.step?"-active":"-disabled",n===i.step?1:0,1),this.tryApplyPendingActiveStep(i.slider)}}if(r){let i=this.parseTriggerKey(r);i&&(this.triggerElements.set(t.htmlElement,i),t.htmlElement.addEventListener("click",this.onTriggerClick))}}parseTriggerKey(t){let e=t.match(/^(.+)\[(next|prev|\d+)(\|loop)?\]$/);if(!e)return null;let r=e[2]==="next"||e[2]==="prev"?e[2]:parseInt(e[2],10);return{slider:e[1],step:r,loop:e[3]==="|loop"}}getMaxStep(t){let e=-1;for(let r of this.elementIndex.keys()){let i=this.parseSequenceKey(r);i?.slider===t&&i.step>e&&(e=i.step)}return e}resolveDuration(t,e,r,i){let s=t.getProperty(i),n=t.getProperty("sequence-duration"),a=this.globalSettings.get(e)?.[r];if(s&&!s.includes("[")){let l=parseFloat(s);if(!isNaN(l))return l}if(n&&!n.includes("[")){let l=parseFloat(n);if(!isNaN(l))return l}return a??this.defaultDuration}resolveDurations(t,e){let r=this.parseSequenceKey(e)?.slider??"";return{enteringDuration:this.resolveDuration(t,r,"enteringDuration","entering-duration"),leavingDuration:this.resolveDuration(t,r,"leavingDuration","leaving-duration")}}resolveEasing(t,e,r,i){let s=t.getProperty(i);(!s||typeof s=="string"&&s.includes("["))&&(s=this.globalSettings.get(e)?.[r]??this.settings.easing??"ease-out"),typeof s=="string"&&t.setProperty(i,this.tools.easingFunction.process({easing:s}))}resolveEasings(t,e){let r=this.parseSequenceKey(e)?.slider;r&&(this.resolveEasing(t,r,"enteringEasing","entering-easing"),this.resolveEasing(t,r,"leavingEasing","leaving-easing"))}onObjectDisconnected(t){super.onObjectDisconnected(t);let e=t.getProperty("sequence");if(e){let r=this.elementIndex.get(e);if(r){let i=r.objects.indexOf(t);i!==-1&&r.objects.splice(i,1),r.objects.length||this.elementIndex.delete(e)}}this.triggerElements.has(t.htmlElement)&&(t.htmlElement.removeEventListener("click",this.onTriggerClick),this.triggerElements.delete(t.htmlElement))}parseSequenceKey(t){let e=t.match(/^(.+)\[(\d+)\]$/);return e?{slider:e[1],step:parseInt(e[2],10)}:null}onSequenceEvent(t){let{slider:e,step:r,transitionProgress:i,direction:s=1,duration:n,instant:a}=t;this.activeStep.get(e)===r&&i===void 0||(i!==void 0?this.handleScrub(e,r,i,s):a?this.switchInstant(e,r,s):this.startTransition(e,r,s,n))}startTransition(t,e,r,i){let s=this.activeStep.get(t),n=this.leavingStep.get(t);n!==void 0&&n!==s&&this.setStepState(t,n,"-disabled",0,r);let a=this.elementIndex.get(`${t}[${e}]`),l=s!==void 0?this.elementIndex.get(`${t}[${s}]`):null;s!==void 0&&this.leavingStep.set(t,s),this.activeStep.set(t,e),this.transitions.set(t,{fromStep:s??e,toStep:e,direction:r,startTime:this.data.time.now,enteringDuration:i??a?.enteringDuration??this.defaultDuration,leavingDuration:i??l?.leavingDuration??this.defaultDuration})}handleScrub(t,e,r,i){this.transitions.delete(t);let s=this.activeStep.get(t);if(s!==e){let n=this.leavingStep.get(t);n!==void 0&&this.setStepState(t,n,"-disabled",0,i),s!==void 0&&this.leavingStep.set(t,s),this.activeStep.set(t,e)}this.applyProgress(t,r,r,i)}switchInstant(t,e,r){this.transitions.delete(t);let i=this.activeStep.get(t),s=this.leavingStep.get(t);s!==void 0&&this.setStepState(t,s,"-disabled",0,r),i!==void 0&&i!==e&&this.setStepState(t,i,"-disabled",0,r),this.activeStep.set(t,e),this.leavingStep.delete(t),this.setStepState(t,e,"-active",1,r)}applyProgress(t,e,r,i){let s=this.activeStep.get(t),n=this.leavingStep.get(t);this.setStepState(t,s,e>=1?"-active":"-entering",e,i),n!==void 0&&n!==s&&(r>=1?(this.setStepState(t,n,"-disabled",0,i),this.leavingStep.delete(t)):this.setStepState(t,n,"-leaving",r,i))}setStepState(t,e,r,i,s){let n=this.elementIndex.get(`${t}[${e}]`);if(n)for(let a of n.objects)this.setState(a,r,i,s)}setState(t,e,r,i){let s=t.htmlElement,n=t.getProperty("_state"),a=t.getProperty("_direction"),l=t.getProperty(e==="-leaving"?"leaving-easing":"entering-easing"),o=typeof l=="function"?l(r):r;n!==e&&(s.classList.remove(...ne.ALL_STATES),s.classList.add(e),t.setProperty("_state",e)),a!==i&&(t.setProperty("_direction",i),ie.run(()=>ie.setVars(s,{[ge.DIRECTION]:i.toString()})))}onFrame(t){super.onFrame(t),this.initialized||(this.initialized=!0,this.initializeSliders());for(let[e,r]of this.transitions){let i=t.time.now-r.startTime,s=Math.min(1,i/r.enteringDuration),n=Math.min(1,i/r.leavingDuration);this.applyProgress(e,s,n,r.direction),s>=1&&n>=1&&this.transitions.delete(e)}}};fe.ALL_STATES=Object.values(se);var te=class Y extends X{constructor(t){super(t),this.htmlKey="form"}initializeObject(t,e,r,i){super.initializeObject(t,e,r,i);let s=e.getProperty("form-events")??[];s.forEach(c=>{c.eventElement.removeEventListener(c.eventType,c.eventCallback)}),s.length=0,e.setProperty("form-events",s),super.onObjectConnected(e);let n=e.htmlElement,a=[],l={};this.getInteractiveFields(n).forEach((c,p)=>this.registerField(c,n,a,l,s,p));let o=c=>{c.preventDefault();let p=!0,m={},u=new Set;for(let g of a){let d=g.field;if(!d.isConnected||!this.shouldValidateField(d))continue;if(this.isRadioField(d)){if(u.has(g.key))continue;u.add(g.key)}let{key:f,rules:v,needsContext:b}=g,M=this.getFieldValue(d);m[f]=M,l[f]=M;let{valid:y,errors:w}=this.tools.validation.process({rules:v,value:M,context:this.buildContext(b,f,l)});this.applyValidationState(n,d,f,y,w,"submit"),y||(p=!1)}if(p)this.events.emit(`form:submit:${e.id}`,m);else{let g=new Set,d=a.find(f=>{let v=f.field;if(!v.isConnected||!this.shouldValidateField(v))return!1;if(this.isRadioField(v)){if(g.has(f.key))return!1;g.add(f.key)}let{key:b,rules:M,needsContext:y}=f,w=this.getFieldValue(v);l[b]=w;let{valid:x}=this.tools.validation.process({rules:M,value:w,context:this.buildContext(y,b,l)});return!x});d?.field&&typeof d.field.focus=="function"&&d.field.focus(),this.events.emit(`form:invalid:${e.id}`)}};n.addEventListener("submit",o),s.push({eventElement:n,eventType:"submit",eventCallback:o}),e.setProperty("form-field-entries",a),e.setProperty("form-field-values",l)}onObjectConnected(t){}onDOMMutate(t,e){this.objects.length!==0&&(t.length>0&&this.handleMutationAdditions(t),e.length>0&&this.handleMutationRemovals(e))}applyValidationState(t,e,r,i,s,n){let a=t.querySelector(`[string-input="error[${r}]"]`),l=t.querySelector(`[string-input="group[${r}]"]`);a&&(a.innerHTML="",s.forEach(c=>{let p=document.createElement("span");p.textContent=c,a.appendChild(p)})),n==="live"?(e.classList.toggle("-invalid",!i),e.classList.remove("-error")):(e.classList.remove("-invalid"),e.classList.toggle("-error",!i)),e.classList.toggle("-valid",i),l&&(n==="live"?(l.classList.toggle("-invalid",!i),l.classList.remove("-error")):(l.classList.remove("-invalid"),l.classList.toggle("-error",!i)),l.classList.toggle("-valid",i));let o=i?"valid":n==="live"?"invalid":"error";this.events.emit(`form:field:${o}:${r}`,{key:r,field:e,errors:s,phase:n,valid:i})}getInteractiveFields(t){return Array.from(t.querySelectorAll("[string-input]")).filter(e=>!this.isServiceFieldAttribute(e.getAttribute("string-input")||"")).filter(e=>this.isFormFieldElement(e)).map(e=>e)}getFieldRules(t){let e=this.tools.domAttribute.process({element:t,key:"input"})??"";return this.tools.ruleParser.process({value:e})}registerField(t,e,r,i,s,n){if(!this.isFormFieldElement(t)||t.closest("form")!==e||r.some(d=>d.field===t))return;let a=this.registerFieldIndex(t,n??r.length),l=this.getInputKey(t,a),o=this.getFieldRules(t),c=this.supportsBeforeInputValidation(o),p=this.requiresContext(o),m=this.getInputEventType(t),u={field:t,key:l,rules:o,supportsRealtime:c,needsContext:p,inputEventType:m,inputHandler:()=>{}},g=d=>{let f=d.currentTarget||d.target;if(!f||!f.isConnected||!this.shouldValidateField(f))return;let v=this.getFieldValue(f);i[u.key]=v;let b=this.buildContext(u.needsContext,u.key,i),{valid:M,errors:y}=this.tools.validation.process({rules:u.rules,value:v,context:b});this.applyValidationState(e,f,u.key,M,y,"live")};if(u.inputHandler=g,t.addEventListener(m,g),s.push({eventElement:t,eventType:m,eventCallback:g}),c&&(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)){let d=f=>{let v=f;if(v.isComposing||v.inputType?.startsWith("insertComposition"))return;let b=f.currentTarget||f.target;if(!b||!(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement)||!b.isConnected)return;let M=b.selectionStart??0,y=b.selectionEnd??0,w=b.value;switch(v.inputType){case"deleteContentBackward":w=M===y&&M>0?b.value.slice(0,M-1)+b.value.slice(y):b.value.slice(0,M)+b.value.slice(y);break;case"deleteContentForward":w=M===y&&M<b.value.length?b.value.slice(0,M)+b.value.slice(M+1):b.value.slice(0,M)+b.value.slice(y);break;case"insertFromPaste":case"insertFromDrop":case"insertReplacementText":w=b.value.slice(0,M)+(v.data||"")+b.value.slice(y);break;default:typeof v.data=="string"&&(w=b.value.slice(0,M)+v.data+b.value.slice(y))}let{errors:x}=this.tools.validation.process({rules:u.rules,value:w,type:"beforeinput",context:this.buildContext(u.needsContext,u.key,i,{applied:!0,value:w})});x.length>0&&f.cancelable&&f.preventDefault()};u.beforeInputHandler=d,t.addEventListener("beforeinput",d),s.push({eventElement:t,eventType:"beforeinput",eventCallback:d})}t.classList.add("-inited"),r.push(u),i[l]=this.getFieldValue(t)}unregisterField(t,e,r,i){let s=e.findIndex(a=>a.field===t);if(s===-1)return;let n=e[s];n.inputHandler&&t.removeEventListener(n.inputEventType,n.inputHandler),n.beforeInputHandler&&t.removeEventListener("beforeinput",n.beforeInputHandler),delete r[n.key],e.splice(s,1);for(let a=i.length-1;a>=0;a--){let l=i[a];l.eventElement===t&&(l.eventCallback===n.inputHandler||n.beforeInputHandler&&l.eventCallback===n.beforeInputHandler)&&i.splice(a,1)}t.classList.remove("-inited")}collectInteractiveFieldsFromNode(t){let e=[];return t instanceof Element?(t.hasAttribute("string-input")&&e.push(t),e.push(...Array.from(t.querySelectorAll("[string-input]")))):t instanceof DocumentFragment&&e.push(...Array.from(t.querySelectorAll("[string-input]"))),e.filter(r=>!this.isServiceFieldAttribute(r.getAttribute("string-input")||"")).filter(r=>this.isFormFieldElement(r))}isRadioField(t){return t instanceof HTMLInputElement&&t.type==="radio"}handleMutationAdditions(t){t.forEach(e=>{this.collectInteractiveFieldsFromNode(e).forEach(r=>{let i=this.getFormStateByContainment(r);i&&this.registerField(r,i.form,i.entries,i.values,i.events)})})}handleMutationRemovals(t){t.forEach(e=>{this.collectInteractiveFieldsFromNode(e).forEach(r=>{let i=this.getFormStateByReference(r);i&&this.unregisterField(r,i.entries,i.values,i.events)})})}getFormStateByContainment(t){let e=this.objects.find(r=>r.htmlElement instanceof HTMLFormElement&&r.htmlElement.contains(t));return e?this.buildFormState(e):null}getFormStateByReference(t){for(let e of this.objects){let r=e.getProperty("form-field-entries");if(r&&r.some(i=>i.field===t))return this.buildFormState(e,r)}return null}buildFormState(t,e){let r=t.htmlElement;if(!(r instanceof HTMLFormElement))return null;let i=e??t.getProperty("form-field-entries"),s=t.getProperty("form-field-values"),n=t.getProperty("form-events");return!i||!s||!n?null:{object:t,form:r,entries:i,values:s,events:n}}registerFieldIndex(t,e){let r=t.getAttribute("data-string-form-index");return r!==null?Number(r):(t.setAttribute("data-string-form-index",String(e)),e)}getFieldIndex(t,e){let r=t.getAttribute("data-string-form-index");if(r!==null){let i=Number(r);return Number.isNaN(i)?e:i}return this.registerFieldIndex(t,e)}shouldValidateField(t){return!(t.disabled||t instanceof HTMLInputElement&&t.type==="hidden")}supportsBeforeInputValidation(t){return t.some(e=>Y.beforeInputRuleKeys.has(e.key))}requiresContext(t){return t.some(e=>Y.crossFieldRuleKeys.has(e.key))}buildContext(t,e,r,i){if(!t)return{fieldKey:e};let s=!!i?.applied,n=s?{...r,[e]:i.value}:r;return{fieldKey:e,values:n,getValue:a=>s&&a===e?i.value:n[a]}}getInputKey(t,e){return this.tools.domAttribute.process({element:t,key:"id"})||t.getAttribute("name")||t.getAttribute("id")||`input-${e}`}getFieldValue(t){if(t instanceof HTMLInputElement){if(t.type==="checkbox"){if(t.name){let e=t.form||t.closest("form"),r=e?Array.from(e.querySelectorAll(`input[type="checkbox"][name="${t.name}"]:checked`)):[t];return r.length>1?r.map(i=>i.value):r.length===1?r[0].value:""}return t.checked}if(t.type==="radio"){if(t.name){let e=(t.form||t.closest("form"))?.querySelector(`input[type="radio"][name="${t.name}"]:checked`);return e?e.value:""}return t.checked?t.value:""}return t.type==="file"&&t.files&&t.files.length>0?t.multiple?Array.from(t.files):t.files[0]:t.value}return t instanceof HTMLSelectElement?t.multiple?Array.from(t.selectedOptions).map(e=>e.value):t.value:t instanceof HTMLTextAreaElement?t.value:""}isServiceFieldAttribute(t){return Y.serviceAttributePrefixes.some(e=>t.startsWith(`${e}[`))}isFormFieldElement(t){return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement}getInputEventType(t){return t instanceof HTMLSelectElement||t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?"change":"input"}};te.beforeInputRuleKeys=new Set(["number","integer","email","phone","letters","lettersSpaces","lettersNumbers","alpha","alpha_num","alpha_dash","digits","url","pattern"]),te.crossFieldRuleKeys=new Set(["same","different","after","before"]),te.serviceAttributePrefixes=["error","group"];var N=class{constructor(t,e="orthographic",r=50,i=.1,s=1e4){this.scaleCache=new Map;this._width=1;this._height=1;this.engine=t,this.mode=e,this.perspectiveFov=r,e==="orthographic"?this._camera=t.createOrthographicCamera(-1,1,1,-1,i,s):this._camera=t.createPerspectiveCamera(r,1,i,s),this._position=t.createVector3(0,0,1e3),this.update()}get camera(){return this._camera}resize(t,e){if(this._width=t,this._height=e,this.mode==="orthographic"){let r=this._camera;r.left=-t/2,r.right=t/2,r.top=e/2,r.bottom=-e/2}else this._camera.aspect=t/e;this.update()}setPosition(t,e,r){this._position.set(t,e,r),this._camera.position.copy(this._position),this.update()}lookAt(t,e,r){this._camera.lookAt(t,e,r),this.update()}update(){this._camera.updateProjectionMatrix(),this._camera.updateMatrixWorld?.()}screenToWorld(t,e,r=0){if(this.mode==="orthographic"){let i=t-this._width/2,s=-(e-this._height/2);return this.engine.createVector3(i,s,r)}else{let{width:i,height:s}=this.getFrustumSizeAt(r),n=t/this._width,a=e/this._height,l=(n-.5)*i,o=-(a-.5)*s;return this.engine.createVector3(l,o,r)}}getFrustumSizeAt(t){if(this.mode==="orthographic")return{width:this._width,height:this._height};let e=this.engine.degToRad(this.perspectiveFov),r=Math.abs(t-this._camera.position.z),i=2*Math.tan(e/2)*r;return{width:i*this._camera.aspect,height:i}}getScaleAtZ(t,e){if(this.mode==="orthographic")return 1;let r=Math.round(t*1e3)/1e3;if(this.scaleCache.has(r))return this.scaleCache.get(r);let{height:i}=this.getFrustumSizeAt(t),s=i/e;return this.scaleCache.set(r,s),s}clearScaleCache(){this.scaleCache.clear()}getMode(){return this.mode}getPerspectiveFov(){return this.perspectiveFov}getPositionZ(){return this._position.z}};var R=class{static register(t){let e=t.name.trim().toLowerCase();if(!e)throw new Error("[String3D] Custom filter name is required.");this.filters.set(e,{...t,name:e})}static get(t){return this.filters.get(t.trim().toLowerCase())}static has(t){return this.filters.has(t.trim().toLowerCase())}static list(){return Array.from(this.filters.values())}};R.filters=new Map;var re=class{constructor(t){this.pool=[];this.create=t}acquire(t,e){let r=this.pool.pop()||this.create(t,e);return(r.width!==t||r.height!==e)&&r.setSize(t,e),r}release(t){this.pool.push(t)}dispose(){this.pool.forEach(t=>t.dispose()),this.pool=[]}},K=class{constructor(t,e,r,i){this.scale=1;this.customMaterials=new Map;this.engine=t,this.renderer=e,this.width=r,this.height=i,this.scene=t.createScene(),this.camera=t.createOrthographicCamera(-1,1,1,-1,0,1);let s=t.createPlaneGeometry(2,2);this.copyMaterial=this.createCopyMaterial(),this.blurMaterial=this.createBlurMaterial(),this.pixelMaterial=this.createPixelMaterial(),this.bloomExtractMaterial=this.createBloomExtractMaterial(),this.bloomAddMaterial=this.createBloomAddMaterial(),this.colorMaterial=this.createColorMaterial(),this.quad=t.createMesh(s,this.copyMaterial),this.scene.add(this.quad);let n=(a,l)=>{if(!this.engine.createRenderTarget)throw new Error("[String3DFilterPipeline] Render target support missing.");return this.engine.createRenderTarget(a,l)};this.pool=new re(n)}isSupported(){return!!this.engine.createRenderTarget&&!!this.engine.createShaderMaterial&&!!this.renderer.setRenderTarget}resize(t,e){this.width=t,this.height=e}setScale(t){let e=Math.max(.75,Math.min(1,t));this.scale=e}applyFilters(t,e,r=1){let i=t,s=[],n=l=>{let o=s.indexOf(l);o>=0&&(s.splice(o,1),this.pool.release(l))},a=()=>{let{width:l,height:o}=this.getScaledSize(),c=this.pool.acquire(l,o);return s.push(c),c};return e.forEach(l=>{if(l.type==="blur"){let o=l.amount*r;if(o<=1e-4)return;let c=a();this.renderPass(this.blurMaterial,i,c,{uDirection:[1,0],uRadius:o});let p=a();this.renderPass(this.blurMaterial,c,p,{uDirection:[0,1],uRadius:o}),n(c),i!==t&&n(i),i=p}else if(l.type==="pixel"){if(l.size<=.5)return;let o=a();this.renderPass(this.pixelMaterial,i,o,{uPixelSize:l.size}),i!==t&&n(i),i=o}else if(l.type==="bloom"){let o=l.intensity;if(o<=1e-4||l.threshold>=.99)return;let c=Math.max(1,4*r),p=a();this.renderPass(this.bloomExtractMaterial,i,p,{uThreshold:l.threshold});let m=a();this.renderPass(this.blurMaterial,p,m,{uDirection:[1,0],uRadius:c});let u=a();this.renderPass(this.blurMaterial,m,u,{uDirection:[0,1],uRadius:c}),n(p),n(m);let g=a();this.renderAddPass(i,u,g,o),n(u),i!==t&&n(i),i=g}else if(l.type==="brightness"||l.type==="contrast"||l.type==="saturate"||l.type==="grayscale"||l.type==="sepia"||l.type==="invert"||l.type==="hue-rotate"){let o=a(),c=this.getColorMode(l.type),p=l.type==="hue-rotate"?l.angle:l.amount;this.renderPass(this.colorMaterial,i,o,{uMode:c,uAmount:p}),i!==t&&n(i),i=o}else if(l.type==="custom"){let o=a(),c=this.getCustomMaterial(l.name);c?(this.renderPass(c,i,o,l.uniforms),i!==t&&n(i),i=o):n(o)}}),s.forEach(l=>{l!==i&&this.pool.release(l)}),i}acquireTarget(){let{width:t,height:e}=this.getScaledSize();return this.pool.acquire(t,e)}releaseTarget(t){this.pool.release(t)}renderToScreen(t){this.renderPass(this.copyMaterial,t,null,{},!1)}dispose(){this.pool.dispose(),this.customMaterials.forEach(t=>t.dispose()),this.customMaterials.clear()}renderPass(t,e,r,i={},s=!0){let n=this.renderer;n.setRenderTarget&&n.setRenderTarget(r),this.setMaterial(this.quad,t),this.setUniform(t,"tDiffuse",e.texture);let{width:a,height:l}=this.getScaledSize();this.setUniform(t,"uResolution",[a,l]),this.setUniform(t,"uTexel",[1/a,1/l]),Object.entries(i).forEach(([o,c])=>this.setUniform(t,o,c)),s&&n.clear&&n.clear(!0,!0,!0),this.renderer.render(this.scene,this.camera)}renderAddPass(t,e,r,i){let s=this.renderer;s.setRenderTarget&&s.setRenderTarget(r),this.setMaterial(this.quad,this.bloomAddMaterial),this.setUniform(this.bloomAddMaterial,"tBase",t.texture),this.setUniform(this.bloomAddMaterial,"tBloom",e.texture),this.setUniform(this.bloomAddMaterial,"uIntensity",i);let{width:n,height:a}=this.getScaledSize();this.setUniform(this.bloomAddMaterial,"uResolution",[n,a]),s.clear&&s.clear(!0,!0,!0),this.renderer.render(this.scene,this.camera)}setMaterial(t,e){let r=t;r.material!==e&&(r.material=e)}setUniform(t,e,r){let i=t.uniforms;i&&(i[e]?i[e].value=r:i[e]={value:r})}createCopyMaterial(){return this.createShaderMaterial({uniforms:{tDiffuse:{value:null}},vertexShader:this.getVertexShader(),fragmentShader:`
1
+ "use strict";var StringTune3D=(()=>{var Ze=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var gt=(p,e)=>{for(var t in e)Ze(p,t,{get:e[t],enumerable:!0})},ft=(p,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pt(e))!mt.call(p,r)&&r!==t&&Ze(p,r,{get:()=>e[r],enumerable:!(i=dt(e,r))||i.enumerable});return p};var yt=p=>ft(Ze({},"__esModule",{value:!0}),p);var Ft={};gt(Ft,{FontConverter:()=>ge,String3D:()=>Ge,String3DCamera:()=>we,String3DCustomFilterRegistry:()=>ve,String3DCustomMaterialRegistry:()=>ue,String3DFontRegistry:()=>ne,String3DObject:()=>J,String3DRenderer:()=>Ee,String3DScene:()=>Ce,String3DSynchronizer:()=>Fe,ThreeJSEngine:()=>Re,ThreeJSMaterialFactory:()=>Le,ThreeJSProvider:()=>qe});var bt=class{constructor(){this.desktop={rebuild:{width:!0,height:!0,scrollHeight:!0}},this.mobile={rebuild:{width:!0,height:!0,scrollHeight:!0}}}},ke=class{constructor(p){this.objectMapOnPage=new Map,this.objectsOnPage=[],this.objectMap=new Map,this.objects=[],this.htmlKey="",this._type=1,this.permissions=new bt,this.tools=p.tools,this.data=p.data,this.settings=p.settings,this.events=p.events,this.centers=p.centers,this.hover=p.hover,this.attributesToMap=[{key:"active",type:"boolean",fallback:this.settings.active},{key:"fixed",type:"boolean",fallback:this.settings.fixed},{key:"outside-container",type:"boolean",fallback:this.settings["outside-container"]},{key:"repeat",type:"boolean",fallback:this.settings.repeat},{key:"self-disable",type:"boolean",fallback:this.settings["self-disable"]},{key:"abs",type:"boolean",fallback:this.settings.abs},{key:"key",type:"string",fallback:this.settings.key},{key:"offset-top",type:"dimension",fallback:this.settings["offset-top"]},{key:"offset-bottom",type:"dimension",fallback:this.settings["offset-bottom"]},{key:"inview-top",type:"dimension",fallback:this.settings["inview-top"]},{key:"inview-bottom",type:"dimension",fallback:this.settings["inview-bottom"]},{key:"start",type:"number",fallback:(e,t,i)=>{let r=i.top;return Math.floor(r)+this.data.scroll.container.scrollTop*this.data.viewport.transformScale}},{key:"end",type:"number",fallback:(e,t,i)=>{let r=i.top,s=i.height;return r+s-this.data.scroll.transformedCurrent}},{key:"size",type:"number",fallback:(e,t,i)=>i.height},{key:"half-width",type:"number",fallback:(e,t,i)=>i.width/2},{key:"half-height",type:"number",fallback:(e,t,i)=>i.height/2},{key:"enter-el",type:"string",fallback:this.settings["enter-el"]},{key:"enter-vp",type:"string",fallback:this.settings["enter-vp"]},{key:"exit-el",type:"string",fallback:this.settings["exit-el"]},{key:"exit-vp",type:"string",fallback:this.settings["exit-vp"]}]}get type(){return this._type}initializeObject(p,e,t,i){let r=this.tools.boundingClientRect.process({element:t});for(let{key:s,type:n,fallback:o,transform:a}of this.attributesToMap){let l=typeof o=="function"?o(t,e,r):o,c=this.tools.domAttribute.process({element:t,key:s,fallback:i[s]??this.settings[s]??l}),u=this.parseAttribute(c,n,{element:t,boundingRect:r,viewportHeight:this.data.viewport.windowHeight,baseRem:this.data.viewport.baseRem});a&&(u=a(u)),e.setProperty(s,u)}}calculatePositions(p,e){let t=p.getProperty("start"),i=p.getProperty("size"),r=p.getProperty("offset-bottom"),s=p.getProperty("offset-top"),n=p.getProperty("enter-el"),o=p.getProperty("enter-vp"),a=p.getProperty("exit-el"),l=p.getProperty("exit-vp"),c=0,u=0,h=0,d=0;n==="top"&&o==="top"||n==="left"&&o==="left"?(h=-e+1,c=t-r):n==="top"&&o==="bottom"||n==="left"&&o==="right"?c=t-e-r:n==="bottom"&&o==="top"||n==="right"&&o==="left"?(h=-e-i+1,c=t+i-r):(n==="bottom"&&o==="bottom"||n==="right"&&o==="right")&&(h=-i+1,c=t-e+i-r),a==="top"&&l==="top"||a==="left"&&l==="left"?(d=-i+1,u=t+s):a==="top"&&l==="bottom"||a==="left"&&l==="right"?(d=-e-i+1,u=t-e+s):a==="bottom"&&l==="top"||a==="right"&&l==="left"?u=t+i+s:(a==="bottom"&&l==="bottom"||a==="right"&&l==="right")&&(d=-e+1,u=t-e+i+s),p.setProperty("start-bias",h),p.setProperty("end-bias",d),p.setProperty("start-position",c-this.data.scroll.topPosition),p.setProperty("end-position",u-this.data.scroll.topPosition),p.setProperty("difference-position",u-c);let m=p.getProperty("inview-top")??0,g=p.getProperty("inview-bottom")??0;p.setProperty("inview-start-position",p.getProperty("start-position")+m),p.setProperty("inview-end-position",p.getProperty("end-position")+g)}parseAttribute(p,e,t={}){if(p==null)return null;if(typeof e=="object"&&e.type==="enum")return e.values.includes(p)?p:e.values[0];switch(e){case"number":return parseFloat(p);case"boolean":return p===""||p==="true";case"json":try{return JSON.parse(p)}catch{return null}case"tuple":return p.trim().split(/\s+/);case"easing":return this.tools.easingFunction.process({easing:p});case"color":return this.tools.colorParser.process({value:p});case"dimension":return p=="0"?0:t.element!=null&&t.viewportHeight!=null&&t.baseRem!=null&&t.boundingRect!=null?this.tools.unitParser.process({value:p,element:t.element,viewportHeight:t.viewportHeight,boundingRect:t.boundingRect,baseRem:t.baseRem}):0;case"breakpoint-dimension":if(t.element!=null&&t.viewportHeight!=null&&t.baseRem!=null&&t.boundingRect!=null){let i=p.trim().split("|"),r=[];for(let s of i)if(s.includes(":")){let[n,o]=s.split(":");r.push({breakpoint:parseInt(n),value:this.tools.unitParser.process({value:`${o}|`,element:t.element,viewportHeight:t.viewportHeight,boundingRect:t.boundingRect,baseRem:t.baseRem})})}else r.push({breakpoint:0,value:this.tools.unitParser.process({value:s,element:t.element,viewportHeight:t.viewportHeight,boundingRect:t.boundingRect,baseRem:t.baseRem})});return r}default:return p}}canConnect(p){return p.keys.includes(this.htmlKey)}connectObject(p){p.connect(this),this.onObjectConnected(p)}enterObject(p,e){this.objectMap.has(p)||(this.objectMap.set(p,e),this.objects.push(e))}exitObject(p){let e=this.objectMap.get(p);if(!e)return;this.objectMap.delete(p);let t=this.objects.indexOf(e);t!==-1&&this.objects.splice(t,1)}addObject(p,e){this.objectMapOnPage.has(p)||(this.objectMapOnPage.set(p,e),this.objectsOnPage.push(e))}removeObject(p){let e=this.objectMapOnPage.get(p);if(!e)return;this.objectMapOnPage.delete(p);let t=this.objectsOnPage.indexOf(e);t!==-1&&this.objectsOnPage.splice(t,1),this.onObjectDisconnected(e)}onObjectConnected(p){}onObjectDisconnected(p){}applyToElementAndConnects(p,e,t=e){p.getProperty("self-disable")!==!0&&e(p.htmlElement),p.mirrorObjects.forEach(i=>t(i.htmlElement,i))}destroy(){this.objects=[],this.objectMap=new Map}onInit(){}onFrame(p){}onMutate(p){}onScrollMeasure(p){}onMouseMoveMeasure(p){}onResize(){}onResizeWidth(){}onScroll(p){}onDirectionChange(){}onScrollStart(){}onScrollStop(){}onScrollDirectionChange(){}onAxisChange(){}onDeviceChange(){}onScrollConfigChange(){}onSettingsChange(){}onDOMRebuild(){}onMouseMove(p){}onWheel(p){}onDOMMutate(p,e){}};var vt=class{constructor(){this.pendingVars=new Map,this.pendingProps=new Map,this.isOpen=!1}begin(){this.isOpen||(this.isOpen=!0)}setVars(p,e){if(!this.isOpen){console.warn("StyleTxn: call begin() first to set custom properties.");return}let t=this.pendingVars.get(p)??{};for(let[i,r]of Object.entries(e))t[i]!==r&&(t[i]=r);this.pendingVars.set(p,t)}setProps(p,e){if(!this.isOpen){console.warn("StyleTxn: call begin() first to set standard properties.");return}let t=this.pendingProps.get(p)??{};for(let[i,r]of Object.entries(e))t[i]!==r&&(t[i]=r);this.pendingProps.set(p,t)}run(p){let e=this.isOpen;e||this.begin();try{p(),e||this.commit()}catch(t){throw e||this.cancel(),t}}commit(){if(this.isOpen){this.isOpen=!1;for(let[p,e]of this.pendingVars){let t=p.style;for(let[i,r]of Object.entries(e))t.setProperty(i,String(r))}this.pendingVars.clear();for(let[p,e]of this.pendingProps){let t=p.style;for(let[i,r]of Object.entries(e))t[i]=String(r)}this.pendingProps.clear()}}cancel(){this.pendingVars.clear(),this.pendingProps.clear(),this.isOpen=!1}},ot=new vt;var It=1/240;var St=class{constructor(){this.measureQueue=[],this.mutateQueue=[],this.scheduled=!1}measure(p){this.measureQueue.push(p),this.schedule()}mutate(p){this.mutateQueue.push(p),this.schedule()}schedule(){this.scheduled||(this.scheduled=!0,requestAnimationFrame(()=>{let p=this.measureQueue;this.measureQueue=[];for(let t=0;t<p.length;t++)try{p[t]()}catch(i){console.error("Error in frameDOM measure task:",i)}let e=this.mutateQueue;this.mutateQueue=[];for(let t=0;t<e.length;t++)try{e[t]()}catch(i){console.error("Error in frameDOM mutate task:",i)}this.scheduled=!1}))}},Ot=new St;var Rt=Math.PI*2,At=180/Math.PI;var lt=(p=>(p.ACTIVE="-active",p.ENTERING="-entering",p.LEAVING="-leaving",p.DISABLED="-disabled",p))(lt||{}),Mt={PROGRESS:"--sequence-progress",DIRECTION:"--sequence-direction"},xt=class ct extends ke{constructor(e){super(e),this.activeStep=new Map,this.leavingStep=new Map,this.transitions=new Map,this.elementIndex=new Map,this.triggerElements=new Map,this.globalSettings=new Map,this.initialized=!1,this.onTriggerClick=t=>{let i=this.triggerElements.get(t.currentTarget);if(!i)return;let r=this.activeStep.get(i.slider)??0,s=this.getMaxStep(i.slider),n,o;if(i.step==="next"){if(n=r+1,o=1,!this.elementIndex.has(`${i.slider}[${n}]`))if(i.loop&&s>=0)n=0;else return}else if(i.step==="prev"){if(n=r-1,o=-1,n<0)if(i.loop&&s>=0)n=s;else return;if(!this.elementIndex.has(`${i.slider}[${n}]`))return}else{if(n=i.step,r===n)return;o=n>r?1:-1}this.startTransition(i.slider,n,o)},this.htmlKey="sequence",this.defaultDuration=this.settings["sequence-duration"]??600,this.attributesToMap=[...this.attributesToMap,{key:"sequence",type:"string",fallback:""},{key:"sequence-trigger",type:"string",fallback:""},{key:"entering-easing",type:"string",fallback:""},{key:"leaving-easing",type:"string",fallback:""},{key:"entering-duration",type:"string",fallback:""},{key:"leaving-duration",type:"string",fallback:""},{key:"sequence-duration",type:"string",fallback:""},{key:"active-step",type:"string",fallback:""}]}onInit(){super.onInit(),this.events.on("sequence",this.onSequenceEvent.bind(this)),this.scanStandaloneTriggers()}scanStandaloneTriggers(){let e=document.querySelectorAll("[string-sequence-trigger]:not([string-inited])");for(let t of e){let i=t.getAttribute("string-sequence-trigger"),r=i?this.parseTriggerKey(i):null;r&&(this.triggerElements.set(t,r),t.addEventListener("click",this.onTriggerClick))}}parseGlobalSettingsFromObject(e){let t=r=>e.getProperty(r),i=t("sequence-duration");this.tryParseGlobalSetting(i,"enteringDuration"),this.tryParseGlobalSetting(i,"leavingDuration"),this.tryParseGlobalSetting(t("entering-duration"),"enteringDuration"),this.tryParseGlobalSetting(t("leaving-duration"),"leavingDuration"),this.tryParseGlobalSetting(t("entering-easing"),"enteringEasing"),this.tryParseGlobalSetting(t("leaving-easing"),"leavingEasing"),this.tryParseGlobalSetting(t("active-step"),"activeStep")}tryParseGlobalSetting(e,t){if(!e)return;let i=e.match(/^(.+)\[(.+)\]$/);if(!i)return;let[,r,s]=i,n=this.globalSettings.get(r)??{};this.globalSettings.set(r,n),n[t]=t==="enteringEasing"||t==="leavingEasing"?s:parseFloat(s),this.applyGlobalSettingsToExistingObjects(r)}applyGlobalSettingsToExistingObjects(e){let t=this.globalSettings.get(e);if(t){for(let[i,r]of this.elementIndex)if(this.parseSequenceKey(i)?.slider===e){t.enteringDuration!==void 0&&(r.enteringDuration=t.enteringDuration),t.leavingDuration!==void 0&&(r.leavingDuration=t.leavingDuration);for(let s of r.objects)this.resolveEasings(s,i)}}}initializeSliders(){let e=new Set;for(let t of this.elementIndex.keys()){let i=this.parseSequenceKey(t);i&&e.add(i.slider)}for(let t of e){if(this.activeStep.has(t))continue;let i=this.globalSettings.get(t)?.activeStep??0;this.elementIndex.has(`${t}[${i}]`)||(i=0),this.switchInstant(t,i,1)}}tryApplyPendingActiveStep(e){if(this.activeStep.has(e))return;let t=this.globalSettings.get(e)?.activeStep;t!==void 0&&this.elementIndex.has(`${e}[${t}]`)&&this.switchInstant(e,t,1)}canConnect(e){return e.keys.includes("sequence")||e.keys.includes("sequence-trigger")}onObjectConnected(e){super.onObjectConnected(e),this.parseGlobalSettingsFromObject(e);let t=e.getProperty("sequence"),i=e.getProperty("sequence-trigger");if(!t&&i){let r=this.parseTriggerKey(i);r&&typeof r.step=="number"&&(t=`${r.slider}[${r.step}]`,e.setProperty("sequence",t))}if(t){let r=this.parseSequenceKey(t);if(r){let s=this.elementIndex.get(t);if(!s){let{enteringDuration:o,leavingDuration:a}=this.resolveDurations(e,t);s={objects:[],enteringDuration:o,leavingDuration:a},this.elementIndex.set(t,s)}s.objects.push(e),this.resolveEasings(e,t);let n=this.activeStep.get(r.slider);this.setState(e,n===r.step?"-active":"-disabled",n===r.step?1:0,1),this.tryApplyPendingActiveStep(r.slider)}}if(i){let r=this.parseTriggerKey(i);r&&(this.triggerElements.set(e.htmlElement,r),e.htmlElement.addEventListener("click",this.onTriggerClick))}}parseTriggerKey(e){let t=e.match(/^(.+)\[(next|prev|\d+)(\|loop)?\]$/);if(!t)return null;let i=t[2]==="next"||t[2]==="prev"?t[2]:parseInt(t[2],10);return{slider:t[1],step:i,loop:t[3]==="|loop"}}getMaxStep(e){let t=-1;for(let i of this.elementIndex.keys()){let r=this.parseSequenceKey(i);r?.slider===e&&r.step>t&&(t=r.step)}return t}resolveDuration(e,t,i,r){let s=e.getProperty(r),n=e.getProperty("sequence-duration"),o=this.globalSettings.get(t)?.[i];if(s&&!s.includes("[")){let a=parseFloat(s);if(!isNaN(a))return a}if(n&&!n.includes("[")){let a=parseFloat(n);if(!isNaN(a))return a}return o??this.defaultDuration}resolveDurations(e,t){let i=this.parseSequenceKey(t)?.slider??"";return{enteringDuration:this.resolveDuration(e,i,"enteringDuration","entering-duration"),leavingDuration:this.resolveDuration(e,i,"leavingDuration","leaving-duration")}}resolveEasing(e,t,i,r){let s=e.getProperty(r);(!s||typeof s=="string"&&s.includes("["))&&(s=this.globalSettings.get(t)?.[i]??this.settings.easing??"ease-out"),typeof s=="string"&&e.setProperty(r,this.tools.easingFunction.process({easing:s}))}resolveEasings(e,t){let i=this.parseSequenceKey(t)?.slider;i&&(this.resolveEasing(e,i,"enteringEasing","entering-easing"),this.resolveEasing(e,i,"leavingEasing","leaving-easing"))}onObjectDisconnected(e){super.onObjectDisconnected(e);let t=e.getProperty("sequence");if(t){let i=this.elementIndex.get(t);if(i){let r=i.objects.indexOf(e);r!==-1&&i.objects.splice(r,1),i.objects.length||this.elementIndex.delete(t)}}this.triggerElements.has(e.htmlElement)&&(e.htmlElement.removeEventListener("click",this.onTriggerClick),this.triggerElements.delete(e.htmlElement))}parseSequenceKey(e){let t=e.match(/^(.+)\[(\d+)\]$/);return t?{slider:t[1],step:parseInt(t[2],10)}:null}onSequenceEvent(e){let{slider:t,step:i,transitionProgress:r,direction:s=1,duration:n,instant:o}=e;this.activeStep.get(t)===i&&r===void 0||(r!==void 0?this.handleScrub(t,i,r,s):o?this.switchInstant(t,i,s):this.startTransition(t,i,s,n))}startTransition(e,t,i,r){let s=this.activeStep.get(e),n=this.leavingStep.get(e);n!==void 0&&n!==s&&this.setStepState(e,n,"-disabled",0,i);let o=this.elementIndex.get(`${e}[${t}]`),a=s!==void 0?this.elementIndex.get(`${e}[${s}]`):null;s!==void 0&&this.leavingStep.set(e,s),this.activeStep.set(e,t),this.transitions.set(e,{fromStep:s??t,toStep:t,direction:i,startTime:this.data.time.now,enteringDuration:r??o?.enteringDuration??this.defaultDuration,leavingDuration:r??a?.leavingDuration??this.defaultDuration})}handleScrub(e,t,i,r){this.transitions.delete(e);let s=this.activeStep.get(e);if(s!==t){let n=this.leavingStep.get(e);n!==void 0&&this.setStepState(e,n,"-disabled",0,r),s!==void 0&&this.leavingStep.set(e,s),this.activeStep.set(e,t)}this.applyProgress(e,i,i,r)}switchInstant(e,t,i){this.transitions.delete(e);let r=this.activeStep.get(e),s=this.leavingStep.get(e);s!==void 0&&this.setStepState(e,s,"-disabled",0,i),r!==void 0&&r!==t&&this.setStepState(e,r,"-disabled",0,i),this.activeStep.set(e,t),this.leavingStep.delete(e),this.setStepState(e,t,"-active",1,i)}applyProgress(e,t,i,r){let s=this.activeStep.get(e),n=this.leavingStep.get(e);this.setStepState(e,s,t>=1?"-active":"-entering",t,r),n!==void 0&&n!==s&&(i>=1?(this.setStepState(e,n,"-disabled",0,r),this.leavingStep.delete(e)):this.setStepState(e,n,"-leaving",i,r))}setStepState(e,t,i,r,s){let n=this.elementIndex.get(`${e}[${t}]`);if(n)for(let o of n.objects)this.setState(o,i,r,s)}setState(e,t,i,r){let s=e.htmlElement,n=e.getProperty("_state"),o=e.getProperty("_direction"),a=e.getProperty(t==="-leaving"?"leaving-easing":"entering-easing"),l=typeof a=="function"?a(i):i;n!==t&&(s.classList.remove(...ct.ALL_STATES),s.classList.add(t),e.setProperty("_state",t)),o!==r&&(e.setProperty("_direction",r),ot.run(()=>ot.setVars(s,{[Mt.DIRECTION]:r.toString()})))}onFrame(e){super.onFrame(e),this.initialized||(this.initialized=!0,this.initializeSliders());for(let[t,i]of this.transitions){let r=e.time.now-i.startTime,s=Math.min(1,r/i.enteringDuration),n=Math.min(1,r/i.leavingDuration);this.applyProgress(t,s,n,i.direction),s>=1&&n>=1&&this.transitions.delete(t)}}};xt.ALL_STATES=Object.values(lt);var Ke=class Ae extends ke{constructor(e){super(e),this.htmlKey="form"}initializeObject(e,t,i,r){super.initializeObject(e,t,i,r);let s=t.getProperty("form-events")??[];s.forEach(c=>{c.eventElement.removeEventListener(c.eventType,c.eventCallback)}),s.length=0,t.setProperty("form-events",s),super.onObjectConnected(t);let n=t.htmlElement,o=[],a={};this.getInteractiveFields(n).forEach((c,u)=>this.registerField(c,n,o,a,s,u));let l=c=>{c.preventDefault();let u=!0,h={},d=new Set;for(let m of o){let g=m.field;if(!g.isConnected||!this.shouldValidateField(g))continue;if(this.isRadioField(g)){if(d.has(m.key))continue;d.add(m.key)}let{key:f,rules:S,needsContext:y}=m,b=this.getFieldValue(g);h[f]=b,a[f]=b;let{valid:v,errors:E}=this.tools.validation.process({rules:S,value:b,context:this.buildContext(y,f,a)});this.applyValidationState(n,g,f,v,E,"submit"),v||(u=!1)}if(u)this.events.emit(`form:submit:${t.id}`,h);else{let m=new Set,g=o.find(f=>{let S=f.field;if(!S.isConnected||!this.shouldValidateField(S))return!1;if(this.isRadioField(S)){if(m.has(f.key))return!1;m.add(f.key)}let{key:y,rules:b,needsContext:v}=f,E=this.getFieldValue(S);a[y]=E;let{valid:I}=this.tools.validation.process({rules:b,value:E,context:this.buildContext(v,y,a)});return!I});g?.field&&typeof g.field.focus=="function"&&g.field.focus(),this.events.emit(`form:invalid:${t.id}`)}};n.addEventListener("submit",l),s.push({eventElement:n,eventType:"submit",eventCallback:l}),t.setProperty("form-field-entries",o),t.setProperty("form-field-values",a)}onObjectConnected(e){}onDOMMutate(e,t){this.objects.length!==0&&(e.length>0&&this.handleMutationAdditions(e),t.length>0&&this.handleMutationRemovals(t))}applyValidationState(e,t,i,r,s,n){let o=e.querySelector(`[string-input="error[${i}]"]`),a=e.querySelector(`[string-input="group[${i}]"]`);o&&(o.innerHTML="",s.forEach(c=>{let u=document.createElement("span");u.textContent=c,o.appendChild(u)})),n==="live"?(t.classList.toggle("-invalid",!r),t.classList.remove("-error")):(t.classList.remove("-invalid"),t.classList.toggle("-error",!r)),t.classList.toggle("-valid",r),a&&(n==="live"?(a.classList.toggle("-invalid",!r),a.classList.remove("-error")):(a.classList.remove("-invalid"),a.classList.toggle("-error",!r)),a.classList.toggle("-valid",r));let l=r?"valid":n==="live"?"invalid":"error";this.events.emit(`form:field:${l}:${i}`,{key:i,field:t,errors:s,phase:n,valid:r})}getInteractiveFields(e){return Array.from(e.querySelectorAll("[string-input]")).filter(t=>!this.isServiceFieldAttribute(t.getAttribute("string-input")||"")).filter(t=>this.isFormFieldElement(t)).map(t=>t)}getFieldRules(e){let t=this.tools.domAttribute.process({element:e,key:"input"})??"";return this.tools.ruleParser.process({value:t})}registerField(e,t,i,r,s,n){if(!this.isFormFieldElement(e)||e.closest("form")!==t||i.some(g=>g.field===e))return;let o=this.registerFieldIndex(e,n??i.length),a=this.getInputKey(e,o),l=this.getFieldRules(e),c=this.supportsBeforeInputValidation(l),u=this.requiresContext(l),h=this.getInputEventType(e),d={field:e,key:a,rules:l,supportsRealtime:c,needsContext:u,inputEventType:h,inputHandler:()=>{}},m=g=>{let f=g.currentTarget||g.target;if(!f||!f.isConnected||!this.shouldValidateField(f))return;let S=this.getFieldValue(f);r[d.key]=S;let y=this.buildContext(d.needsContext,d.key,r),{valid:b,errors:v}=this.tools.validation.process({rules:d.rules,value:S,context:y});this.applyValidationState(t,f,d.key,b,v,"live")};if(d.inputHandler=m,e.addEventListener(h,m),s.push({eventElement:e,eventType:h,eventCallback:m}),c&&(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)){let g=f=>{let S=f;if(S.isComposing||S.inputType?.startsWith("insertComposition"))return;let y=f.currentTarget||f.target;if(!y||!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement)||!y.isConnected)return;let b=y.selectionStart??0,v=y.selectionEnd??0,E=y.value;switch(S.inputType){case"deleteContentBackward":E=b===v&&b>0?y.value.slice(0,b-1)+y.value.slice(v):y.value.slice(0,b)+y.value.slice(v);break;case"deleteContentForward":E=b===v&&b<y.value.length?y.value.slice(0,b)+y.value.slice(b+1):y.value.slice(0,b)+y.value.slice(v);break;case"insertFromPaste":case"insertFromDrop":case"insertReplacementText":E=y.value.slice(0,b)+(S.data||"")+y.value.slice(v);break;default:typeof S.data=="string"&&(E=y.value.slice(0,b)+S.data+y.value.slice(v))}let{errors:I}=this.tools.validation.process({rules:d.rules,value:E,type:"beforeinput",context:this.buildContext(d.needsContext,d.key,r,{applied:!0,value:E})});I.length>0&&f.cancelable&&f.preventDefault()};d.beforeInputHandler=g,e.addEventListener("beforeinput",g),s.push({eventElement:e,eventType:"beforeinput",eventCallback:g})}e.classList.add("-inited"),i.push(d),r[a]=this.getFieldValue(e)}unregisterField(e,t,i,r){let s=t.findIndex(o=>o.field===e);if(s===-1)return;let n=t[s];n.inputHandler&&e.removeEventListener(n.inputEventType,n.inputHandler),n.beforeInputHandler&&e.removeEventListener("beforeinput",n.beforeInputHandler),delete i[n.key],t.splice(s,1);for(let o=r.length-1;o>=0;o--){let a=r[o];a.eventElement===e&&(a.eventCallback===n.inputHandler||n.beforeInputHandler&&a.eventCallback===n.beforeInputHandler)&&r.splice(o,1)}e.classList.remove("-inited")}collectInteractiveFieldsFromNode(e){let t=[];return e instanceof Element?(e.hasAttribute("string-input")&&t.push(e),t.push(...Array.from(e.querySelectorAll("[string-input]")))):e instanceof DocumentFragment&&t.push(...Array.from(e.querySelectorAll("[string-input]"))),t.filter(i=>!this.isServiceFieldAttribute(i.getAttribute("string-input")||"")).filter(i=>this.isFormFieldElement(i))}isRadioField(e){return e instanceof HTMLInputElement&&e.type==="radio"}handleMutationAdditions(e){e.forEach(t=>{this.collectInteractiveFieldsFromNode(t).forEach(i=>{let r=this.getFormStateByContainment(i);r&&this.registerField(i,r.form,r.entries,r.values,r.events)})})}handleMutationRemovals(e){e.forEach(t=>{this.collectInteractiveFieldsFromNode(t).forEach(i=>{let r=this.getFormStateByReference(i);r&&this.unregisterField(i,r.entries,r.values,r.events)})})}getFormStateByContainment(e){let t=this.objects.find(i=>i.htmlElement instanceof HTMLFormElement&&i.htmlElement.contains(e));return t?this.buildFormState(t):null}getFormStateByReference(e){for(let t of this.objects){let i=t.getProperty("form-field-entries");if(i&&i.some(r=>r.field===e))return this.buildFormState(t,i)}return null}buildFormState(e,t){let i=e.htmlElement;if(!(i instanceof HTMLFormElement))return null;let r=t??e.getProperty("form-field-entries"),s=e.getProperty("form-field-values"),n=e.getProperty("form-events");return!r||!s||!n?null:{object:e,form:i,entries:r,values:s,events:n}}registerFieldIndex(e,t){let i=e.getAttribute("data-string-form-index");return i!==null?Number(i):(e.setAttribute("data-string-form-index",String(t)),t)}getFieldIndex(e,t){let i=e.getAttribute("data-string-form-index");if(i!==null){let r=Number(i);return Number.isNaN(r)?t:r}return this.registerFieldIndex(e,t)}shouldValidateField(e){return!(e.disabled||e instanceof HTMLInputElement&&e.type==="hidden")}supportsBeforeInputValidation(e){return e.some(t=>Ae.beforeInputRuleKeys.has(t.key))}requiresContext(e){return e.some(t=>Ae.crossFieldRuleKeys.has(t.key))}buildContext(e,t,i,r){if(!e)return{fieldKey:t};let s=!!r?.applied,n=s?{...i,[t]:r.value}:i;return{fieldKey:t,values:n,getValue:o=>s&&o===t?r.value:n[o]}}getInputKey(e,t){return this.tools.domAttribute.process({element:e,key:"id"})||e.getAttribute("name")||e.getAttribute("id")||`input-${t}`}getFieldValue(e){if(e instanceof HTMLInputElement){if(e.type==="checkbox"){if(e.name){let t=e.form||e.closest("form"),i=t?Array.from(t.querySelectorAll(`input[type="checkbox"][name="${e.name}"]:checked`)):[e];return i.length>1?i.map(r=>r.value):i.length===1?i[0].value:""}return e.checked}if(e.type==="radio"){if(e.name){let t=(e.form||e.closest("form"))?.querySelector(`input[type="radio"][name="${e.name}"]:checked`);return t?t.value:""}return e.checked?e.value:""}return e.type==="file"&&e.files&&e.files.length>0?e.multiple?Array.from(e.files):e.files[0]:e.value}return e instanceof HTMLSelectElement?e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value:e instanceof HTMLTextAreaElement?e.value:""}isServiceFieldAttribute(e){return Ae.serviceAttributePrefixes.some(t=>e.startsWith(`${t}[`))}isFormFieldElement(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}getInputEventType(e){return e instanceof HTMLSelectElement||e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")?"change":"input"}};Ke.beforeInputRuleKeys=new Set(["number","integer","email","phone","letters","lettersSpaces","lettersNumbers","alpha","alpha_num","alpha_dash","digits","url","pattern"]),Ke.crossFieldRuleKeys=new Set(["same","different","after","before"]),Ke.serviceAttributePrefixes=["error","group"];var we=class{constructor(e,t="perspective",i=50,r=.1,s=1e4){this.scaleCache=new Map;this._width=1;this._height=1;this.engine=e,this.mode=t,this.perspectiveFov=i,t==="orthographic"?this._camera=e.createOrthographicCamera(-1,1,1,-1,r,s):this._camera=e.createPerspectiveCamera(i,1,r,s),this._position=e.createVector3(0,0,1e3),this.update()}get camera(){return this._camera}resize(e,t){if(this._width=e,this._height=t,this.mode==="orthographic"){let i=this._camera;i.left=-e/2,i.right=e/2,i.top=t/2,i.bottom=-t/2}else this._camera.aspect=e/t;this.update()}setPosition(e,t,i){this._position.set(e,t,i),this._camera.position.copy(this._position),this.update()}lookAt(e,t,i){this._camera.lookAt(e,t,i),this.update()}update(){this._camera.updateProjectionMatrix(),this._camera.updateMatrixWorld?.()}screenToWorld(e,t,i=0){if(this.mode==="orthographic"){let r=e-this._width/2,s=-(t-this._height/2);return this.engine.createVector3(r,s,i)}else{let{width:r,height:s}=this.getFrustumSizeAt(i),n=e/this._width,o=t/this._height,a=(n-.5)*r,l=-(o-.5)*s;return this.engine.createVector3(a,l,i)}}getFrustumSizeAt(e){if(this.mode==="orthographic")return{width:this._width,height:this._height};let t=this.engine.degToRad(this.perspectiveFov),i=Math.abs(e-this._camera.position.z),r=2*Math.tan(t/2)*i;return{width:r*this._camera.aspect,height:r}}getScaleAtZ(e,t){if(this.mode==="orthographic")return 1;let i=Math.round(e*1e3)/1e3;if(this.scaleCache.has(i))return this.scaleCache.get(i);let{height:r}=this.getFrustumSizeAt(e),s=r/t;return this.scaleCache.set(i,s),s}clearScaleCache(){this.scaleCache.clear()}getMode(){return this.mode}getPerspectiveFov(){return this.perspectiveFov}getPositionZ(){return this._position.z}};var ve=class{static register(e){let t=e.name.trim().toLowerCase();if(!t)throw new Error("[String3D] Custom filter name is required.");this.filters.set(t,{...e,name:t})}static get(e){return this.filters.get(e.trim().toLowerCase())}static has(e){return this.filters.has(e.trim().toLowerCase())}static list(){return Array.from(this.filters.values())}};ve.filters=new Map;var Qe=class{constructor(e){this.pool=[];this.create=e}acquire(e,t){let i=this.pool.pop()||this.create(e,t);return(i.width!==e||i.height!==t)&&i.setSize(e,t),i}release(e){this.pool.push(e)}dispose(){this.pool.forEach(e=>e.dispose()),this.pool=[]}},je=class{constructor(e,t,i,r){this.scale=1;this.customMaterials=new Map;this.engine=e,this.renderer=t,this.width=i,this.height=r,this.scene=e.createScene(),this.camera=e.createOrthographicCamera(-1,1,1,-1,0,1);let s=e.createPlaneGeometry(2,2);this.copyMaterial=this.createCopyMaterial(),this.blurMaterial=this.createBlurMaterial(),this.pixelMaterial=this.createPixelMaterial(),this.bloomExtractMaterial=this.createBloomExtractMaterial(),this.bloomAddMaterial=this.createBloomAddMaterial(),this.colorMaterial=this.createColorMaterial(),this.quad=e.createMesh(s,this.copyMaterial),this.scene.add(this.quad);let n=(o,a)=>{if(!this.engine.createRenderTarget)throw new Error("[String3DFilterPipeline] Render target support missing.");return this.engine.createRenderTarget(o,a)};this.pool=new Qe(n)}isSupported(){return!!this.engine.createRenderTarget&&!!this.engine.createShaderMaterial&&!!this.renderer.setRenderTarget}resize(e,t){this.width=e,this.height=t}setScale(e){let t=Math.max(.75,Math.min(1,e));this.scale=t}applyFilters(e,t,i=1){let r=e,s=[],n=a=>{let l=s.indexOf(a);l>=0&&(s.splice(l,1),this.pool.release(a))},o=()=>{let{width:a,height:l}=this.getScaledSize(),c=this.pool.acquire(a,l);return s.push(c),c};return t.forEach(a=>{if(a.type==="blur"){let l=a.amount*i;if(l<=1e-4)return;let c=o();this.renderPass(this.blurMaterial,r,c,{uDirection:[1,0],uRadius:l});let u=o();this.renderPass(this.blurMaterial,c,u,{uDirection:[0,1],uRadius:l}),n(c),r!==e&&n(r),r=u}else if(a.type==="pixel"){if(a.size<=.5)return;let l=o();this.renderPass(this.pixelMaterial,r,l,{uPixelSize:a.size}),r!==e&&n(r),r=l}else if(a.type==="bloom"){let l=a.intensity;if(l<=1e-4||a.threshold>=.99)return;let c=Math.max(1,4*i),u=o();this.renderPass(this.bloomExtractMaterial,r,u,{uThreshold:a.threshold});let h=o();this.renderPass(this.blurMaterial,u,h,{uDirection:[1,0],uRadius:c});let d=o();this.renderPass(this.blurMaterial,h,d,{uDirection:[0,1],uRadius:c}),n(u),n(h);let m=o();this.renderAddPass(r,d,m,l),n(d),r!==e&&n(r),r=m}else if(a.type==="brightness"||a.type==="contrast"||a.type==="saturate"||a.type==="grayscale"||a.type==="sepia"||a.type==="invert"||a.type==="hue-rotate"){let l=o(),c=this.getColorMode(a.type),u=a.type==="hue-rotate"?a.angle:a.amount;this.renderPass(this.colorMaterial,r,l,{uMode:c,uAmount:u}),r!==e&&n(r),r=l}else if(a.type==="custom"){let l=o(),c=this.getCustomMaterial(a.name);c?(this.renderPass(c,r,l,a.uniforms),r!==e&&n(r),r=l):n(l)}}),s.forEach(a=>{a!==r&&this.pool.release(a)}),r}acquireTarget(){let{width:e,height:t}=this.getScaledSize();return this.pool.acquire(e,t)}releaseTarget(e){this.pool.release(e)}renderToScreen(e){this.renderPass(this.copyMaterial,e,null,{},!1)}dispose(){this.pool.dispose(),this.customMaterials.forEach(e=>e.dispose()),this.customMaterials.clear()}renderPass(e,t,i,r={},s=!0){let n=this.renderer;n.setRenderTarget&&n.setRenderTarget(i),this.setMaterial(this.quad,e),this.setUniform(e,"tDiffuse",t.texture);let{width:o,height:a}=this.getScaledSize();this.setUniform(e,"uResolution",[o,a]),this.setUniform(e,"uTexel",[1/o,1/a]),Object.entries(r).forEach(([l,c])=>this.setUniform(e,l,c)),s&&n.clear&&n.clear(!0,!0,!0),this.renderer.render(this.scene,this.camera)}renderAddPass(e,t,i,r){let s=this.renderer;s.setRenderTarget&&s.setRenderTarget(i),this.setMaterial(this.quad,this.bloomAddMaterial),this.setUniform(this.bloomAddMaterial,"tBase",e.texture),this.setUniform(this.bloomAddMaterial,"tBloom",t.texture),this.setUniform(this.bloomAddMaterial,"uIntensity",r);let{width:n,height:o}=this.getScaledSize();this.setUniform(this.bloomAddMaterial,"uResolution",[n,o]),s.clear&&s.clear(!0,!0,!0),this.renderer.render(this.scene,this.camera)}setMaterial(e,t){let i=e;i.material!==t&&(i.material=t)}setUniform(e,t,i){let r=e.uniforms;r&&(r[t]?r[t].value=i:r[t]={value:i})}createCopyMaterial(){return this.createShaderMaterial({uniforms:{tDiffuse:{value:null}},vertexShader:this.getVertexShader(),fragmentShader:`
2
2
  varying vec2 vUv;
3
3
  uniform sampler2D tDiffuse;
4
4
  void main() {
@@ -105,146 +105,43 @@
105
105
 
106
106
  gl_FragColor = color;
107
107
  }
108
- `,transparent:!0,depthTest:!1,depthWrite:!1})}getColorMode(t){switch(t){case"brightness":return 1;case"contrast":return 2;case"saturate":return 3;case"grayscale":return 4;case"sepia":return 5;case"invert":return 6;case"hue-rotate":return 7;default:return 0}}createShaderMaterial(t){if(!this.engine.createShaderMaterial)throw new Error("[String3DFilterPipeline] Shader material support missing.");return this.engine.createShaderMaterial(t)}getCustomMaterial(t){let e=t.trim().toLowerCase();if(!e)return null;if(this.customMaterials.has(e))return this.customMaterials.get(e);let r=R.get(e);if(!r)return null;let i={tDiffuse:{value:null}},{width:s,height:n}=this.getScaledSize();i.uResolution={value:[s,n]},i.uTexel={value:[1/s,1/n]},Object.entries(r.uniforms||{}).forEach(([l,o])=>{i[l]={value:o}});let a=this.createShaderMaterial({uniforms:i,vertexShader:this.getVertexShader(),fragmentShader:r.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1});return this.customMaterials.set(e,a),a}getScaledSize(){let t=Math.max(1,Math.round(this.width*this.scale)),e=Math.max(1,Math.round(this.height*this.scale));return{width:t,height:e}}getVertexShader(){return`
108
+ `,transparent:!0,depthTest:!1,depthWrite:!1})}getColorMode(e){switch(e){case"brightness":return 1;case"contrast":return 2;case"saturate":return 3;case"grayscale":return 4;case"sepia":return 5;case"invert":return 6;case"hue-rotate":return 7;default:return 0}}createShaderMaterial(e){if(!this.engine.createShaderMaterial)throw new Error("[String3DFilterPipeline] Shader material support missing.");return this.engine.createShaderMaterial(e)}getCustomMaterial(e){let t=e.trim().toLowerCase();if(!t)return null;if(this.customMaterials.has(t))return this.customMaterials.get(t);let i=ve.get(t);if(!i)return null;let r={tDiffuse:{value:null}},{width:s,height:n}=this.getScaledSize();r.uResolution={value:[s,n]},r.uTexel={value:[1/s,1/n]},Object.entries(i.uniforms||{}).forEach(([a,l])=>{r[a]={value:l}});let o=this.createShaderMaterial({uniforms:r,vertexShader:this.getVertexShader(),fragmentShader:i.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1});return this.customMaterials.set(t,o),o}getScaledSize(){let e=Math.max(1,Math.round(this.width*this.scale)),t=Math.max(1,Math.round(this.height*this.scale));return{width:e,height:t}}getVertexShader(){return`
109
109
  varying vec2 vUv;
110
110
  void main() {
111
111
  vUv = uv;
112
112
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
113
113
  }
114
- `}};var _=class{constructor(t,e){this.filterPipeline=null;this.filterCache=new Map;this.frameId=0;this.lastFrameTime=performance.now();this.avgFrameMs=16.7;this.qualityScale=1;this.lastQualityChange=0;this.filterLayer=1;this.engine=e,this._container=t;let{width:r,height:i}=t.getBoundingClientRect();this._width=r,this._height=i,this._renderer=e.createRenderer({antialias:!0,alpha:!0,logarithmicDepthBuffer:!0}),this._renderer.setPixelRatio(window.devicePixelRatio),this._renderer.setSize(r,i),this._renderer.shadowMap&&(this._renderer.shadowMap.enabled=!0)}attach(){this._container.appendChild(this._renderer.domElement)}render(t,e,r=[]){if(r.length===0){this._renderer.render(t.getScene(),e.camera);return}let i=this.ensureFilterPipeline();if(!i?.isSupported()){this._renderer.render(t.getScene(),e.camera);return}this.frameId+=1,this.updateQuality(r.length,i);let s=t.getAllObjects(),n=new Map;s.forEach(m=>{let u=m.object;"visible"in u&&n.set(m.object,u.visible)});let a=new Set;r.forEach(m=>{this.collectSubtreeObjects(m.object,a)}),s.forEach(m=>{a.has(m.object)&&this.setVisible(m.object,!1)});let l=this._renderer,o=l.autoClear;l.autoClear=!0,l.setRenderTarget&&l.setRenderTarget(null),l.clear&&l.clear(!0,!0,!0),this._renderer.render(t.getScene(),e.camera),l.autoClear=!1,s.forEach(m=>{let u=n.get(m.object);typeof u<"u"&&this.setVisible(m.object,u)});let c=s.filter(m=>m.type.endsWith("Light")),p=this.supportsLayers(e.camera,s);r.forEach(m=>{let u=this.filterCache.get(m.object.id);if(!m.dirty&&u&&u.effectsKey===m.effectsKey&&u.qualityScale===this.qualityScale){u.lastUsedFrame=this.frameId,i.renderToScreen(u.target);return}let d=this.injectEffectContext(m.object.el,m.effects),f=new Set;this.collectSubtreeObjects(m.object,f);let v=[],b=null;if(p){let S=m.object.getSubtreeObjects();v=this.applyLayerMask(S,c,this.filterLayer),b=this.setCameraLayer(e.camera,this.filterLayer)}else s.forEach(S=>{if(n.get(S.object)===!1){this.setVisible(S.object,!1);return}if(S.type.endsWith("Light")){this.setVisible(S.object,!0);return}this.setVisible(S.object,f.has(S.object))});let M=i.acquireTarget();l.setRenderTarget&&l.setRenderTarget(M),l.clear&&l.clear(!0,!0,!0),this._renderer.render(t.getScene(),e.camera);let y=i.applyFilters(M,d,this.qualityScale);l.setRenderTarget&&l.setRenderTarget(null),i.renderToScreen(y),p&&(this.restoreLayerMask(v),b!==null&&this.restoreCameraLayer(e.camera,b)),y!==M&&i.releaseTarget(M);let w={target:y,effectsKey:m.effectsKey,lastUsedFrame:this.frameId,qualityScale:this.qualityScale},x=this.filterCache.get(m.object.id);x&&x.target!==y&&i.releaseTarget(x.target),this.filterCache.set(m.object.id,w)}),p||s.forEach(m=>{let u=n.get(m.object);typeof u<"u"&&this.setVisible(m.object,u)}),l.autoClear=o,this.evictCache()}resize(t){let{width:e,height:r}=this._container.getBoundingClientRect();this._width=e,this._height=r,this._renderer.setSize(e,r),t.resize(e,r),this.filterPipeline?.resize(e,r),this.invalidateFilterCache()}get width(){return this._width}get height(){return this._height}get renderer(){return this._renderer}destroy(){this._renderer.dispose(),this.filterPipeline?.dispose(),this.filterCache.clear()}ensureFilterPipeline(){return this.canCreateFilterPipeline()?(this.filterPipeline||(this.filterPipeline=new K(this.engine,this._renderer,this._width,this._height),this.filterPipeline.setScale(this.qualityScale)),this.filterPipeline):null}canCreateFilterPipeline(){return typeof this.engine.createRenderTarget=="function"&&typeof this.engine.createShaderMaterial=="function"&&typeof this._renderer.setRenderTarget=="function"}collectSubtreeObjects(t,e){e.add(t.object),t.children.forEach(r=>this.collectSubtreeObjects(r,e))}setVisible(t,e){let r=t;"visible"in r&&(r.visible=e)}getFilterCenter(t){if(!t||!this._width||!this._height)return[.5,.5];let e=t.getBoundingClientRect(),r=(e.left+e.width/2)/this._width,i=1-(e.top+e.height/2)/this._height,s=n=>Math.max(0,Math.min(1,n));return[s(r),s(i)]}injectEffectContext(t,e){if(!e.some(n=>n.type==="custom"))return e;let r=this.getFilterCenter(t),i=!1,s=e.map(n=>{if(n.type!=="custom"||n.uniforms&&"uCenter"in n.uniforms)return n;let a={...n.uniforms||{},uCenter:r};return i=!0,{...n,uniforms:a}});return i?s:e}updateQuality(t,e){let r=performance.now(),i=Math.max(.1,r-this.lastFrameTime);this.lastFrameTime=r,this.avgFrameMs=this.avgFrameMs*.9+i*.1;let s=1e3/this.avgFrameMs,n=Math.max(.75,1-Math.min(.4,t*.03)),a=n;s<48&&(a=Math.max(.75,n-.1)),s<40&&(a=Math.max(.75,n-.2)),s>58&&(a=Math.min(1,n+.05)),Math.abs(a-this.qualityScale)>=.05&&r-this.lastQualityChange>300&&(this.qualityScale=a,this.lastQualityChange=r,e.setScale(this.qualityScale),this.invalidateFilterCache())}invalidateFilterCache(){this.filterPipeline&&(this.filterCache.forEach(t=>{this.filterPipeline?.releaseTarget(t.target)}),this.filterCache.clear())}evictCache(){if(!this.filterPipeline)return;let t=120;this.filterCache.forEach((e,r)=>{this.frameId-e.lastUsedFrame>t&&(this.filterPipeline?.releaseTarget(e.target),this.filterCache.delete(r))})}supportsLayers(t,e){return!t?.layers||typeof t.layers.set!="function"?!1:e.some(r=>this.hasLayers(r.object))}hasLayers(t){return t?.layers&&typeof t.layers.set=="function"}applyLayerMask(t,e,r){let i=new Map,s=(n,a)=>{let l=n;this.hasLayers(l)&&(i.has(n)||i.set(n,l.layers.mask),a==="set"?l.layers.set(r):l.layers.enable(r))};return t.forEach(n=>s(n,"set")),e.forEach(n=>s(n.object,"enable")),Array.from(i.entries()).map(([n,a])=>({object:n,mask:a}))}restoreLayerMask(t){t.forEach(e=>{let r=e.object;this.hasLayers(r)&&(r.layers.mask=e.mask)})}setCameraLayer(t,e){if(!t?.layers||typeof t.layers.set!="function")return null;let r=t.layers.mask;return t.layers.set(e),r}restoreCameraLayer(t,e){t?.layers&&(t.layers.mask=e)}};var D=class{constructor(t,e,r,i,s={}){this._uniforms={};this._children=[];this._flatObjectsCache=null;this._subtreeCache=null;this.id=t,this.type=e,this._object=r,this.engine=i,this._material=s.material,this._geometry=s.geometry,this._texture=s.texture,this._quaternion=i.createQuaternion(),this._originalSize=i.createVector3(),this._bbox=i.createBox3(),this.updateBoundingBox()}get children(){return this._children}get object(){return this._object}get material(){return this._material}get originalSize(){return this._originalSize.clone()}get boundingBox(){return this._bbox.clone()}addChild(t){this._children.push(t),this.object.add(t.object),this.invalidateFlatCache(),this.invalidateSubtreeCache()}getWorldMatrix(){return this._object.matrixWorld.clone()}getWorldPosition(){return this.engine.createVector3().setFromMatrixPosition(this._object.matrixWorld)}getOriginalBoundingBox(){if(!this._originalBoundingBox){let t=this.object.scale.clone();this.object.scale.set(1,1,1),this.object.updateMatrixWorld(!0),this._originalBoundingBox=this.engine.computeBoundingBoxRecursively(this.object),this.object.scale.copy(t),this.object.updateMatrixWorld(!0)}return this._originalBoundingBox.clone()}syncTransformFromMatrix(t){let e=this.engine.createVector3(),r=this.engine.createQuaternion(),i=this.engine.createVector3();t.decompose(e,r,i),this._object.position.copy(e),this._object.quaternion.copy(r),this._object.scale.copy(i),this._object.updateMatrix(),this._object.updateMatrixWorld()}applyWorldTransform(t,e,r){this._object.position.copy(t),this._object.quaternion.copy(e),this._object.scale.copy(r),this._object.updateMatrix(),this._object.updateMatrixWorld()}set quaternion(t){this._quaternion.copy(t),this._object.quaternion.copy(this._quaternion),this._object.updateMatrixWorld()}set position(t){this._object.position.copy(t)}set scale(t){this._object.scale.copy(t)}set rotation(t){this._object.rotation.copy(t)}set opacity(t){let e=this._object;e.material&&"opacity"in e.material&&(e.material.opacity=t)}set metalness(t){let e=this._object;e.material&&"metalness"in e.material&&(e.material.metalness=t)}set roughness(t){let e=this._object;e.material&&"roughness"in e.material&&(e.material.roughness=t)}set texture(t){this._texture=t,this._object.isMesh&&t?.applyTexture&&t.applyTexture(this._object)}set material(t){this._material=t}set geometry(t){this._geometry=t}updateBoundingBox(){this._bbox.setFromObject(this._object),this._bbox.getSize(this._originalSize)}destroy(){this.disposeObjectResources(this._object),this._texture?.dispose?.(),this._material?.dispose(),this._geometry?.dispose(),this._subtreeCache=null}getFlatObjects(){if(this._flatObjectsCache)return this._flatObjectsCache;let t=[],e=r=>{t.push(r.object),r.children.forEach(i=>e(i))};return e(this),this._flatObjectsCache=t,t}getSubtreeObjects(){if(this._subtreeCache)return this._subtreeCache;let t=[],e=this._object;return t.push(this._object),typeof e.traverse=="function"&&e.traverse(r=>{r&&r!==this._object&&t.push(r)}),this._subtreeCache=t,t}invalidateFlatCache(){this._flatObjectsCache=null}invalidateSubtreeCache(){this._subtreeCache=null}disposeObjectResources(t){let e=t;e?.geometry?.dispose&&e.geometry.dispose();let r=e?.material;Array.isArray(r)?r.forEach(i=>i?.dispose?.()):r?.dispose&&r.dispose(),typeof e?.traverse=="function"&&e.traverse(i=>{i?.geometry?.dispose&&i.geometry.dispose();let s=i?.material;Array.isArray(s)?s.forEach(n=>n?.dispose?.()):s?.dispose&&s.dispose()})}};var W=class{constructor(t,e={}){this._objects=new Map;this._rootObjects=[];this._elementMap=new Map;this._modelLoaderCache=new Map;this.engine=t,this._modelLoader=e.modelLoader,this._modelLoaderFactory=e.modelLoaderFactory,this._scene=t.createScene()}get rootObjects(){return this._rootObjects}getScene(){return this._scene}getObject(t){return this._objects.get(t)}getAllObjects(){let t=[],e=r=>{t.push(r),r.children.forEach(i=>e(i))};return this._rootObjects.forEach(r=>e(r)),t}hasObject(t){return this._objects.has(t)}deleteObject(t){let e=this._objects.get(t);return e?(this._scene.remove(e.object),this._objects.delete(t),e.destroy(),!0):!1}createFromElement(t){let e=t.getProperty("3d");if(!e)return;let r=t.htmlElement;if(!r)return;let i=s=>{if(s){let n=t.getProperty("parentId");n==null?(this._scene.add(s.object),this._rootObjects.push(s)):this._objects.get(n)?.addChild(s),this._objects.set(t.id,s),this._elementMap.set(t.id,r),s.el=r}};switch(e){case"group":this.createGroup(t,i);break;case"pointLight":this.createLight(t,"point",i);break;case"ambientLight":this.createLight(t,"ambient",i);break;case"directionalLight":this.createLight(t,"directional",i);break;case"spotLight":this.createLight(t,"spot",i);break;case"hemisphereLight":this.createLight(t,"hemisphere",i);break;case"model":this.createModel(t,i);break;case"box":this.createBox(t,i);break;case"sphere":this.createSphere(t,i);break;case"plane":this.createPlane(t,i);break;case"cylinder":this.createCylinder(t,i);break}}createGroup(t,e){let r=this.engine.createGroup(),i=new D(t.id,"group",r,this.engine);return e(i),i}createLight(t,e,r){let i=t.getProperty("3d-color")||"#ffffff",s=t.getProperty("3d-intensity")??1,n;if(e==="point"){let o=t.getProperty("3d-distance")??1e3,c=t.getProperty("3d-decay")??0;n=this.engine.createPointLight(i,s,o,c)}else if(e==="directional")n=this.engine.createDirectionalLight(i,s);else if(e==="spot"){let o=t.getProperty("3d-distance")??0,c=t.getProperty("3d-angle")??Math.PI/3,p=t.getProperty("3d-penumbra")??0,m=t.getProperty("3d-decay")??1;n=this.engine.createSpotLight(i,s,o,c,p,m)}else if(e==="hemisphere"){let o=t.getProperty("3d-ground-color")||"#ffffff";n=this.engine.createHemisphereLight(i,o,s)}else n=this.engine.createAmbientLight(i,s);if((t.getProperty("3d-cast-shadow")??!1)&&n.shadow){n.castShadow=!0;let o=t.getProperty("3d-shadow-bias")??0,c=t.getProperty("3d-shadow-map-size")??512;n.shadow.bias=o,n.shadow.mapSize.width=c,n.shadow.mapSize.height=c}let l=new D(t.id,e+"Light",n,this.engine);return r(l),l}applyShadowProps(t,e){let r=t.getProperty("3d-cast-shadow")??!1,i=t.getProperty("3d-receive-shadow")??!1;e.castShadow=r,e.receiveShadow=i}createBox(t,e){let r=this.engine.createBoxGeometry(1,1,1),i=this.createMaterialFromObject(t),s=this.engine.createMesh(r,i);this.applyShadowProps(t,s);let n=new D(t.id,"box",s,this.engine,{geometry:r,material:i});return e(n),n}createSphere(t,e){let r=t.getProperty("3d-segments-width")??32,i=t.getProperty("3d-segments-height")??32,s=this.engine.createSphereGeometry(.5,r,i),n=this.createMaterialFromObject(t),a=this.engine.createMesh(s,n);this.applyShadowProps(t,a);let l=new D(t.id,"sphere",a,this.engine,{geometry:s,material:n});return e(l),l}createPlane(t,e){let r=this.engine.createPlaneGeometry(1,1),i=this.createMaterialFromObject(t),s=this.engine.createMesh(r,i);this.applyShadowProps(t,s);let n=new D(t.id,"plane",s,this.engine,{geometry:r,material:i});return e(n),n}createCylinder(t,e){let r=t.getProperty("3d-segments")??32,i=this.engine.createCylinderGeometry(.5,.5,1,r),s=this.createMaterialFromObject(t),n=this.engine.createMesh(i,s);this.applyShadowProps(t,n);let a=new D(t.id,"cylinder",n,this.engine,{geometry:i,material:s});return e(a),a}createModel(t,e){let r=t.getProperty("3d-model");if(!r)return;let i=t.getProperty("3d-model-loader")||void 0,s=this.resolveModelLoader(i);if(!s){console.warn("[String3D] Model loader not configured");return}let n=t.htmlElement;n&&this.applyModelTextureRemap(s,n);let a=t.getProperty("3d-model-center")??!1;s.load(r,l=>{let o=l?.scene||l?.object||l;if(!o){console.warn("[String3D] Model loader returned empty result");return}let c=n&&this.shouldOverrideModelMaterial(n)?this.createMaterialFromElement(n,t):null;typeof o.traverse=="function"&&o.traverse(m=>{m.isMesh&&(c&&(m.material=c),this.applyShadowProps(t,m))}),a&&this.centerObject(o);let p=new D(t.id,"model",o,this.engine);e(p)},l=>{console.log(l.loaded/l.total*100+"% loaded")},l=>{console.error("[String3D] Model loading error:",l)})}resolveModelLoader(t){if(t){if(this._modelLoaderCache.has(t))return this._modelLoaderCache.get(t);if(!this._modelLoaderFactory){console.warn(`[String3D] No model loader factory for type "${t}"`);return}let e=this._modelLoaderFactory(this.engine,t);return this._modelLoaderCache.set(t,e),e}if(this._modelLoader)return this._modelLoader;if(this._modelLoaderFactory)return this._modelLoaderFactory(this.engine)}centerObject(t){if(!t)return;let e=this.engine.computeBoundingBoxRecursively(t),r=this.getBoxCenter(e);t.position?.set&&t.position.set(-r.x,-r.y,-r.z),t.updateMatrixWorld(!0)}getBoxCenter(t){let e=this.engine.createVector3();return e.x=(t.min.x+t.max.x)/2,e.y=(t.min.y+t.max.y)/2,e.z=(t.min.z+t.max.z)/2,e}createMaterialFromObject(t){return this.createMaterialFromElement(t.htmlElement,t)}createMaterialFromElement(t,e){let r=e?.getProperty("3d-material")||"basic[#ffffff]",[i,s]=r.split(/\[|\]/),n=s||"#ffffff",a=e?.getProperty("3d-opacity")??1,l=e?.getProperty("3d-metalness"),o=e?.getProperty("3d-roughness"),c={color:n,transparent:a<1,opacity:a},p=t?.getAttribute("string-3d-map"),m=t?.getAttribute("string-3d-normalMap"),u=t?.getAttribute("string-3d-roughnessMap"),g=t?.getAttribute("string-3d-metalnessMap"),d=t?.getAttribute("string-3d-aoMap"),f=this.parseFlipY(e,t),v=e?.getProperty("3d-colorSpace")||t?.getAttribute("string-3d-colorSpace")||"";return i!=="standard"&&!!(p||m||u||g||d)&&(i="standard"),i==="standard"?(p&&(c.map=this.loadTexture(p,{flipY:f,colorSpace:v})),m&&(c.normalMap=this.loadTexture(m,{flipY:f})),u&&(c.roughnessMap=this.loadTexture(u,{flipY:f})),g&&(c.metalnessMap=this.loadTexture(g,{flipY:f})),d&&(c.aoMap=this.loadTexture(d,{flipY:f})),typeof l=="number"&&(c.metalness=l),typeof o=="number"&&(c.roughness=o),this.engine.createMeshStandardMaterial(c)):this.engine.createMeshBasicMaterial(c)}loadTexture(t,e={}){let i=this.engine.createTextureLoader().load(t);typeof e.flipY=="boolean"&&(i.flipY=e.flipY);let s=(e.colorSpace||"").toLowerCase().trim();return s&&"colorSpace"in i&&(i.colorSpace=s==="srgb"?"srgb":"linear"),i.needsUpdate=!0,i}parseFlipY(t,e){let r=t?.getProperty("3d-texture-flipY")??e?.getAttribute("string-3d-texture-flipY");if(r==null||r==="")return;if(typeof r=="boolean")return r;let i=String(r).toLowerCase().trim();if(i==="false"||i==="0"||i==="no")return!1;if(i==="true"||i==="1"||i==="yes")return!0}shouldOverrideModelMaterial(t){return["string-3d-material","string-3d-color","string-3d-opacity","string-3d-map","string-3d-normalMap","string-3d-roughnessMap","string-3d-metalnessMap","string-3d-aoMap","string-3d-metalness","string-3d-roughness"].some(r=>t.hasAttribute(r))}applyModelTextureRemap(t,e){let r=(e.getAttribute("string-3d-model-texture-base")||"").trim(),i=r?r.replace(/\/?$/,"/"):"",s=e.getAttribute("string-3d-model-textures"),n=null;if(s)try{n=JSON.parse(s)}catch(l){console.warn("[String3D] Invalid model texture mapping JSON:",l)}let a=t?.manager;if(!a||typeof a.setURLModifier!="function"){(n||i)&&console.warn("[String3D] Model loader does not support URL remap.");return}a.setURLModifier(l=>{let o=n&&l in n?n[l]:l;return!i||/^(blob:|data:|https?:|file:|\/)/i.test(o)?o:i+o.replace(/^\.?\//,"")})}destroy(){this._objects.forEach(t=>t.destroy()),this._objects.clear(),this._rootObjects=[]}};var Z=class{sync(t,e,r,i){let s=t.getBoundingClientRect(),n=s.left+s.width/2,a=s.top+s.height/2,l=t.computedStyleMap?.(),o=null,c=()=>(o||(o=getComputedStyle(t)),o),p=(b,M)=>{let y=l?.get?.(b);if(y!==void 0){if(typeof y=="number")return y;if(typeof y=="string"){let S=Number.parseFloat(y);if(!Number.isNaN(S))return S}if(y&&typeof y=="object"){let S=y.value;if(typeof S=="number")return S;if(typeof S=="string"){let C=Number.parseFloat(S);if(!Number.isNaN(C))return C}}}let w=c().getPropertyValue(b),x=Number.parseFloat(w);return Number.isNaN(x)?M:x},m=p("--translate-z",0),u=r.camera.screenToWorld(n,a,m);e.position=u;let g=p("--scale",1);e.scale=r.engine.createVector3(g,g,g);let d=-r.engine.degToRad(p("--rotate-x",0)),f=r.engine.degToRad(p("--rotate-y",0)),v=-r.engine.degToRad(p("--rotate-z",0));return e.rotation=r.engine.createEuler(d,f,v,"XYZ"),e.object.updateMatrixWorld(!0),{scale:g}}};var F=class{sync(t,e,r,i){let s=t.getBoundingClientRect(),n=s.left+s.width/2,a=s.top+s.height/2,l=parseFloat(getComputedStyle(t).getPropertyValue("--translate-z")||"0"),o=r.camera.screenToWorld(n,a,l);e.position=o;let c=e.object,p=t.getAttribute("string-3d-color");p&&c.color&&typeof c.color.set=="function"&&c.color.set(p);let m=t.getAttribute("string-3d-intensity");m&&(c.intensity=parseFloat(m));let u=t.getAttribute("string-3d-distance");u&&typeof c.distance<"u"&&(c.distance=parseFloat(u));let g=t.getAttribute("string-3d-decay");g&&typeof c.decay<"u"&&(c.decay=parseFloat(g));let d=t.getAttribute("string-3d-angle");d&&typeof c.angle<"u"&&(c.angle=parseFloat(d));let f=t.getAttribute("string-3d-penumbra");f&&typeof c.penumbra<"u"&&(c.penumbra=parseFloat(f));let v=t.getAttribute("string-3d-ground-color");v&&c.groundColor&&typeof c.groundColor.set=="function"&&c.groundColor.set(v);let b=t.getAttribute("string-3d-cast-shadow")==="true";if(c.castShadow!==b&&(c.castShadow=b),b&&c.shadow){let y=t.getAttribute("string-3d-shadow-bias");y&&(c.shadow.bias=parseFloat(y));let w=t.getAttribute("string-3d-shadow-map-size");if(w){let x=parseFloat(w);c.shadow.mapSize.width!==x&&(c.shadow.mapSize.width=x,c.shadow.mapSize.height=x)}}let M=t.getAttribute("string-3d-target");if(M&&c.target){let y=document.querySelector(`[string-id="${M}"]`);if(y){let w=y.getBoundingClientRect(),x=w.left+w.width/2,S=w.top+w.height/2,C=parseFloat(getComputedStyle(y).getPropertyValue("--translate-z")||"0"),P=r.camera.screenToWorld(x,S,C);c.target.position.copy(P),c.target.updateMatrixWorld(!0)}}return null}};var k=class h{static applyVisualProps(t,e,r){let i=t.getAttribute("string-3d-cast-shadow")==="true",s=t.getAttribute("string-3d-receive-shadow")==="true",n=typeof r=="number"?r:NaN;if(e.object.traverse)e.object.traverse(a=>{a.isMesh&&(a.castShadow!==i&&(a.castShadow=i),a.receiveShadow!==s&&(a.receiveShadow=s),isNaN(n)||(Array.isArray(a.material)?a.material:[a.material]).forEach(o=>{o&&(o.opacity=n,o.transparent=n<1)}))});else if(e.object.isMesh){let a=e.object;a.castShadow!==i&&(a.castShadow=i),a.receiveShadow!==s&&(a.receiveShadow=s),isNaN(n)||(Array.isArray(a.material)?a.material:[a.material]).forEach(o=>{o&&(o.opacity=n,o.transparent=n<1)})}}sync(t,e,r,i){let s=t.computedStyleMap?.(),n=null,a=()=>(n||(n=getComputedStyle(t)),n),l=t.getBoundingClientRect(),o=t.offsetWidth||l.width,c=t.offsetHeight||l.height,p=(T,z)=>{let L=s?.get?.(T);if(L!==void 0){if(typeof L=="number")return L;if(typeof L=="string"){let E=Number.parseFloat(L);if(!Number.isNaN(E))return E}if(L&&typeof L=="object"){let E=L.value;if(typeof E=="number")return E;if(typeof E=="string"){let V=Number.parseFloat(E);if(!Number.isNaN(V))return V}}}let q=a().getPropertyValue(T),O=Number.parseFloat(q);return Number.isNaN(O)?z:O},m=p("--translate-z",0),u=p("--scale",1),g=l.left+l.width/2,d=l.top+l.height/2,f=r.camera.screenToWorld(g,d,m);e.position=f;let v=-r.engine.degToRad(p("--rotate-x",0)),b=r.engine.degToRad(p("--rotate-y",0)),M=-r.engine.degToRad(p("--rotate-z",0));e.rotation=r.engine.createEuler(v,b,M,"XYZ");let y=o*u,w=c*u,x=p("--scale-z",1),S=i?.scale||1,C=e.type,P,A,I;switch(C){case"box":case"sphere":{let T=Math.min(y,w);P=T*S,A=T*S,I=T*x*S;break}case"model":{let z=e.getOriginalBoundingBox().getSize(r.engine.createVector3()),L=(t.getAttribute("string-3d-model-fit")||"contain").toLowerCase().trim(),q=parseFloat(t.getAttribute("string-3d-model-scale")||"1"),O=Number.isFinite(q)?q:1;if(z.x>0&&z.y>0){let E=y/z.x,V=w/z.y,J=L==="cover"?Math.max(E,V):Math.min(E,V);P=J*O*S,A=J*O*S,I=J*O*x*S}else{let E=Math.min(y,w);P=E*O*S,A=E*O*S,I=E*O*x*S}break}case"cylinder":{let T=y;P=T*S,A=w*S,I=T*x*S;break}case"plane":default:P=y*S,A=w*S,I=Math.min(y,w)*.5*x*S;break}e.scale=r.engine.createVector3(P,A,I);let U=p("--opacity",NaN);return h.applyVisualProps(t,e,U),{scale:u*S}}};var H=class{constructor(t,e,r,i){this.camera=t;this.viewportWidth=e;this.viewportHeight=r;this.engine=i;this.strategies=new Map;this.strategies.set("box",new k),this.strategies.set("sphere",new k),this.strategies.set("plane",new k),this.strategies.set("cylinder",new k),this.strategies.set("model",new k),this.strategies.set("group",new Z),this.strategies.set("pointLight",new F),this.strategies.set("ambientLight",new F),this.strategies.set("directionalLight",new F),this.strategies.set("spotLight",new F),this.strategies.set("hemisphereLight",new F)}syncElement(t,e,r){let i=this.strategies.get(e.type);return i?i.sync(t,e,{camera:this.camera,viewportWidth:this.viewportWidth,viewportHeight:this.viewportHeight,engine:this.engine},r):(console.warn(`[String3D Sync] No strategy for type "${e.type}"`),null)}updateViewportSize(t,e){this.viewportWidth=t,this.viewportHeight=e}};var ye=`
115
- let wasm = null;
116
- let wasmReady = false;
117
-
118
- function degToRad(deg) {
119
- return (deg * Math.PI) / 180;
120
- }
121
-
122
- function computeTransform(item, camera) {
123
- const centerX = item.rectLeft + item.rectWidth / 2;
124
- const centerY = item.rectTop + item.rectHeight / 2;
125
-
126
- let posX = 0;
127
- let posY = 0;
128
- let posZ = item.translateZ;
129
-
130
- if (camera.mode === "orthographic") {
131
- posX = centerX - camera.width / 2;
132
- posY = -(centerY - camera.height / 2);
133
- } else {
134
- const fov = degToRad(camera.fov);
135
- const distance = Math.abs(item.translateZ - camera.cameraZ);
136
- const height = 2 * Math.tan(fov / 2) * distance;
137
- const width = height * camera.aspect;
138
- const normalizedX = centerX / camera.width;
139
- const normalizedY = centerY / camera.height;
140
- posX = (normalizedX - 0.5) * width;
141
- posY = -(normalizedY - 0.5) * height;
142
- }
143
-
144
- const rotX = -degToRad(item.rotateX);
145
- const rotY = degToRad(item.rotateY);
146
- const rotZ = -degToRad(item.rotateZ);
147
-
148
- let scaleX = 1;
149
- let scaleY = 1;
150
- let scaleZ = 1;
151
-
152
- if (item.type === "group") {
153
- scaleX = item.scale;
154
- scaleY = item.scale;
155
- scaleZ = item.scale;
156
- } else {
157
- const targetWidth = item.rectWidth * item.scale;
158
- const targetHeight = item.rectHeight * item.scale;
159
- const parentScale = item.parentScale || 1;
160
- const cssScaleZ = item.scaleZ || 1;
161
-
162
- if (item.type === "box" || item.type === "sphere") {
163
- const uniformSize = Math.min(targetWidth, targetHeight);
164
- scaleX = uniformSize * parentScale;
165
- scaleY = uniformSize * parentScale;
166
- scaleZ = uniformSize * cssScaleZ * parentScale;
167
- } else if (item.type === "model") {
168
- const sizeX = item.modelSizeX || 0;
169
- const sizeY = item.modelSizeY || 0;
170
- const fitMode = (item.fitMode || "contain").toLowerCase().trim();
171
- const modelScale = Number.isFinite(item.modelScale) ? item.modelScale : 1;
172
-
173
- if (sizeX > 0 && sizeY > 0) {
174
- const scaleToWidth = targetWidth / sizeX;
175
- const scaleToHeight = targetHeight / sizeY;
176
- const uniformScale = fitMode === "cover"
177
- ? Math.max(scaleToWidth, scaleToHeight)
178
- : Math.min(scaleToWidth, scaleToHeight);
179
- scaleX = uniformScale * modelScale * parentScale;
180
- scaleY = uniformScale * modelScale * parentScale;
181
- scaleZ = uniformScale * modelScale * cssScaleZ * parentScale;
182
- } else {
183
- const fallbackSize = Math.min(targetWidth, targetHeight);
184
- scaleX = fallbackSize * modelScale * parentScale;
185
- scaleY = fallbackSize * modelScale * parentScale;
186
- scaleZ = fallbackSize * modelScale * cssScaleZ * parentScale;
187
- }
188
- } else if (item.type === "cylinder") {
189
- const cylRadius = targetWidth;
190
- scaleX = cylRadius * parentScale;
191
- scaleY = targetHeight * parentScale;
192
- scaleZ = cylRadius * cssScaleZ * parentScale;
193
- } else {
194
- scaleX = targetWidth * parentScale;
195
- scaleY = targetHeight * parentScale;
196
- scaleZ = Math.min(targetWidth, targetHeight) * 0.5 * cssScaleZ * parentScale;
197
- }
198
- }
199
-
200
- return {
201
- id: item.id,
202
- posX,
203
- posY,
204
- posZ,
205
- rotX,
206
- rotY,
207
- rotZ,
208
- scaleX,
209
- scaleY,
210
- scaleZ,
211
- };
114
+ `}};var Ee=class{constructor(e,t){this.filterPipeline=null;this.filterCache=new Map;this.frameId=0;this.lastFrameTime=performance.now();this.avgFrameMs=16.7;this.qualityScale=1;this.lastQualityChange=0;this.filterLayer=1;this.engine=t,this._container=e;let{width:i,height:r}=e.getBoundingClientRect();this._width=i,this._height=r,this._renderer=t.createRenderer({antialias:!0,alpha:!0,logarithmicDepthBuffer:!0});let s=this._renderer;typeof s.setClearColor=="function"&&s.setClearColor(0,0),this._renderer.setPixelRatio(window.devicePixelRatio),this._renderer.setSize(i,r),this._renderer.shadowMap&&(this._renderer.shadowMap.enabled=!0)}attach(){this._container.appendChild(this._renderer.domElement)}render(e,t,i=[]){if(i.length===0){this._renderer.render(e.getScene(),t.camera);return}let r=this.ensureFilterPipeline();if(!r?.isSupported()){this._renderer.render(e.getScene(),t.camera);return}this.frameId+=1,this.updateQuality(i.length,r);let s=e.getAllObjects(),n=new Map;s.forEach(h=>{let d=h.object;"visible"in d&&n.set(h.object,d.visible)});let o=new Set;i.forEach(h=>{this.collectSubtreeObjects(h.object,o)}),s.forEach(h=>{o.has(h.object)&&this.setVisible(h.object,!1)});let a=this._renderer,l=a.autoClear;a.autoClear=!0,a.setRenderTarget&&a.setRenderTarget(null),a.clear&&a.clear(!0,!0,!0),this._renderer.render(e.getScene(),t.camera),a.autoClear=!1,s.forEach(h=>{let d=n.get(h.object);typeof d<"u"&&this.setVisible(h.object,d)});let c=s.filter(h=>h.type.endsWith("Light")),u=this.supportsLayers(t.camera,s);i.forEach(h=>{let d=this.filterCache.get(h.object.id);if(!h.dirty&&d&&d.effectsKey===h.effectsKey&&d.qualityScale===this.qualityScale){d.lastUsedFrame=this.frameId,r.renderToScreen(d.target);return}let g=this.injectEffectContext(h.object.el,h.effects),f=new Set;this.collectSubtreeObjects(h.object,f);let S=[],y=null;if(u){let F=h.object.getSubtreeObjects();S=this.applyLayerMask(F,c,this.filterLayer),y=this.setCameraLayer(t.camera,this.filterLayer)}else s.forEach(F=>{if(n.get(F.object)===!1){this.setVisible(F.object,!1);return}if(F.type.endsWith("Light")){this.setVisible(F.object,!0);return}this.setVisible(F.object,f.has(F.object))});let b=r.acquireTarget();a.setRenderTarget&&a.setRenderTarget(b),a.clear&&a.clear(!0,!0,!0),this._renderer.render(e.getScene(),t.camera);let v=r.applyFilters(b,g,this.qualityScale);a.setRenderTarget&&a.setRenderTarget(null),r.renderToScreen(v),u&&(this.restoreLayerMask(S),y!==null&&this.restoreCameraLayer(t.camera,y)),v!==b&&r.releaseTarget(b);let E={target:v,effectsKey:h.effectsKey,lastUsedFrame:this.frameId,qualityScale:this.qualityScale},I=this.filterCache.get(h.object.id);I&&I.target!==v&&r.releaseTarget(I.target),this.filterCache.set(h.object.id,E)}),u||s.forEach(h=>{let d=n.get(h.object);typeof d<"u"&&this.setVisible(h.object,d)}),a.autoClear=l,this.evictCache()}resize(e){let{width:t,height:i}=this._container.getBoundingClientRect();this._width=t,this._height=i,this._renderer.setSize(t,i),e.resize(t,i),this.filterPipeline?.resize(t,i),this.invalidateFilterCache()}get width(){return this._width}get height(){return this._height}get renderer(){return this._renderer}destroy(){this._renderer.dispose(),this.filterPipeline?.dispose(),this.filterCache.clear()}ensureFilterPipeline(){return this.canCreateFilterPipeline()?(this.filterPipeline||(this.filterPipeline=new je(this.engine,this._renderer,this._width,this._height),this.filterPipeline.setScale(this.qualityScale)),this.filterPipeline):null}canCreateFilterPipeline(){return typeof this.engine.createRenderTarget=="function"&&typeof this.engine.createShaderMaterial=="function"&&typeof this._renderer.setRenderTarget=="function"}collectSubtreeObjects(e,t){t.add(e.object),e.children.forEach(i=>this.collectSubtreeObjects(i,t))}setVisible(e,t){let i=e;"visible"in i&&(i.visible=t)}getFilterCenter(e){if(!e||!this._width||!this._height)return[.5,.5];let t=e.__layoutCache,i=t?t.rect:e.getBoundingClientRect(),r=(i.left+i.width/2)/this._width,s=1-(i.top+i.height/2)/this._height,n=o=>Math.max(0,Math.min(1,o));return[n(r),n(s)]}injectEffectContext(e,t){if(!t.some(n=>n.type==="custom"))return t;let i=this.getFilterCenter(e),r=!1,s=t.map(n=>{if(n.type!=="custom"||n.uniforms&&"uCenter"in n.uniforms)return n;let o={...n.uniforms||{},uCenter:i};return r=!0,{...n,uniforms:o}});return r?s:t}updateQuality(e,t){let i=performance.now(),r=Math.max(.1,i-this.lastFrameTime);this.lastFrameTime=i,this.avgFrameMs=this.avgFrameMs*.9+r*.1;let s=1e3/this.avgFrameMs,n=Math.max(.75,1-Math.min(.4,e*.03)),o=n;s<48&&(o=Math.max(.75,n-.1)),s<40&&(o=Math.max(.75,n-.2)),s>58&&(o=Math.min(1,n+.05)),Math.abs(o-this.qualityScale)>=.05&&i-this.lastQualityChange>300&&(this.qualityScale=o,this.lastQualityChange=i,t.setScale(this.qualityScale),this.invalidateFilterCache())}invalidateFilterCache(){this.filterPipeline&&(this.filterCache.forEach(e=>{this.filterPipeline?.releaseTarget(e.target)}),this.filterCache.clear())}evictCache(){if(!this.filterPipeline)return;let e=120;this.filterCache.forEach((t,i)=>{this.frameId-t.lastUsedFrame>e&&(this.filterPipeline?.releaseTarget(t.target),this.filterCache.delete(i))})}supportsLayers(e,t){return!e?.layers||typeof e.layers.set!="function"?!1:t.some(i=>this.hasLayers(i.object))}hasLayers(e){return e?.layers&&typeof e.layers.set=="function"}applyLayerMask(e,t,i){let r=new Map,s=(n,o)=>{let a=n;this.hasLayers(a)&&(r.has(n)||r.set(n,a.layers.mask),o==="set"?a.layers.set(i):a.layers.enable(i))};return e.forEach(n=>s(n,"set")),t.forEach(n=>s(n.object,"enable")),Array.from(r.entries()).map(([n,o])=>({object:n,mask:o}))}restoreLayerMask(e){e.forEach(t=>{let i=t.object;this.hasLayers(i)&&(i.layers.mask=t.mask)})}setCameraLayer(e,t){if(!e?.layers||typeof e.layers.set!="function")return null;let i=e.layers.mask;return e.layers.set(t),i}restoreCameraLayer(e,t){e?.layers&&(e.layers.mask=t)}};var J=class{constructor(e,t,i,r,s={}){this._uniforms={};this._children=[];this._flatObjectsCache=null;this._subtreeCache=null;this.id=e,this.type=t,this._object=i,this.engine=r,this._material=s.material,this._geometry=s.geometry,this._texture=s.texture,this._quaternion=r.createQuaternion(),this._originalSize=r.createVector3(),this._bbox=r.createBox3(),this.updateBoundingBox()}get children(){return this._children}get object(){return this._object}get material(){return this._material}get originalSize(){return this._originalSize.clone()}get boundingBox(){return this._bbox.clone()}addChild(e){this._children.push(e),this.object.add(e.object),this.invalidateFlatCache(),this.invalidateSubtreeCache()}getWorldMatrix(){return this._object.matrixWorld.clone()}getWorldPosition(){return this.engine.createVector3().setFromMatrixPosition(this._object.matrixWorld)}getOriginalBoundingBox(){if(!this._originalBoundingBox){let e=this.object.scale.clone();this.object.scale.set(1,1,1),this.object.updateMatrixWorld(!0),this._originalBoundingBox=this.engine.computeBoundingBoxRecursively(this.object),this.object.scale.copy(e),this.object.updateMatrixWorld(!0)}return this._originalBoundingBox.clone()}syncTransformFromMatrix(e){let t=this.engine.createVector3(),i=this.engine.createQuaternion(),r=this.engine.createVector3();e.decompose(t,i,r),this._object.position.copy(t),this._object.quaternion.copy(i),this._object.scale.copy(r),this._object.updateMatrix(),this._object.updateMatrixWorld()}applyWorldTransform(e,t,i){this._object.position.copy(e),this._object.quaternion.copy(t),this._object.scale.copy(i),this._object.updateMatrix(),this._object.updateMatrixWorld()}set quaternion(e){this._quaternion.copy(e),this._object.quaternion.copy(this._quaternion),this._object.updateMatrixWorld()}set position(e){this._object.position.copy(e)}set scale(e){this._object.scale.copy(e)}set rotation(e){this._object.rotation.copy(e)}set opacity(e){let t=this._object;t.material&&"opacity"in t.material&&(t.material.opacity=e)}set metalness(e){let t=this._object;t.material&&"metalness"in t.material&&(t.material.metalness=e)}set roughness(e){let t=this._object;t.material&&"roughness"in t.material&&(t.material.roughness=e)}set texture(e){this._texture=e,this._object.isMesh&&e?.applyTexture&&e.applyTexture(this._object)}set material(e){this._material=e}set geometry(e){this._geometry=e}updateBoundingBox(){this._bbox.setFromObject(this._object),this._bbox.getSize(this._originalSize)}destroy(){this.disposeObjectResources(this._object),this._texture?.dispose?.(),this._material?.dispose(),this._geometry?.dispose(),this._subtreeCache=null}getFlatObjects(){if(this._flatObjectsCache)return this._flatObjectsCache;let e=[],t=i=>{e.push(i.object),i.children.forEach(r=>t(r))};return t(this),this._flatObjectsCache=e,e}getSubtreeObjects(){if(this._subtreeCache)return this._subtreeCache;let e=[],t=this._object;return e.push(this._object),typeof t.traverse=="function"&&t.traverse(i=>{i&&i!==this._object&&e.push(i)}),this._subtreeCache=e,e}invalidateFlatCache(){this._flatObjectsCache=null}invalidateSubtreeCache(){this._subtreeCache=null}disposeObjectResources(e){let t=e;t?.geometry?.dispose&&t.geometry.dispose();let i=t?.material;Array.isArray(i)?i.forEach(r=>r?.dispose?.()):i?.dispose&&i.dispose(),typeof t?.traverse=="function"&&t.traverse(r=>{r?.geometry?.dispose&&r.geometry.dispose();let s=r?.material;Array.isArray(s)?s.forEach(n=>n?.dispose?.()):s?.dispose&&s.dispose()})}};var Se=class{constructor(e){this.styleMap=e.computedStyleMap?.(),this.style=getComputedStyle(e)}readNumber(e,t){let i=this.styleMap?.get?.(e);if(i!=null){let s=typeof i=="object"?i.value:i,n=typeof s=="number"?s:Number.parseFloat(s);if(!Number.isNaN(n))return n}let r=Number.parseFloat(this.style.getPropertyValue(e));return Number.isNaN(r)?t:r}readString(e,t=""){let i=this.styleMap?.get?.(e),r=i&&typeof i=="object"?i.value:i;if(typeof r=="string")return this.stripQuotes(r.trim())||t;let s=this.style.getPropertyValue(e).trim();return this.stripQuotes(s)||t}stripQuotes(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}readBoolean(e,t=!1){let i=this.readString(e,"");if(!i)return t;let r=i.toLowerCase();return r==="true"||r==="1"||r==="yes"?!0:r==="false"||r==="0"||r==="no"?!1:t}};function he(p,e,t){let r=p.computedStyleMap?.()?.get?.(e);if(r!==void 0){if(typeof r=="number")return r;if(typeof r=="string"){let a=Number.parseFloat(r);if(!Number.isNaN(a))return a}if(r&&typeof r=="object"){let a=r.value;if(typeof a=="number")return a;if(typeof a=="string"){let l=Number.parseFloat(a);if(!Number.isNaN(l))return l}}}let n=getComputedStyle(p).getPropertyValue(e),o=Number.parseFloat(n);return Number.isNaN(o)?t:o}function Je(p){return p.startsWith("'")&&p.endsWith("'")||p.startsWith('"')&&p.endsWith('"')?p.slice(1,-1):p}function De(p,e,t=""){let r=p.computedStyleMap?.()?.get?.(e);if(typeof r=="string")return Je(r.trim());if(r&&typeof r=="object"){let o=r.value;if(typeof o=="string")return Je(o.trim())}let s=getComputedStyle(p).getPropertyValue(e);return(s?Je(s.trim()):"")||t}function Ne(p,e,t=!1){let i=De(p,e,"");if(!i)return t;let r=i.toLowerCase().trim();return r==="true"||r==="1"||r==="yes"?!0:r==="false"||r==="0"||r==="no"?!1:t}function ht(p){let e=p.computedStyleMap?.(),t="",i=e?.get?.("--filter");if(i!==void 0){if(typeof i=="string")t=i;else if(i&&typeof i=="object"){let r=i.value;typeof r=="string"&&(t=r)}}return t||(t=getComputedStyle(p).getPropertyValue("--filter")||""),t=t.trim(),t}var ue=class{static register(e){let t=e.name.trim().toLowerCase();if(!t)throw new Error("[String3D] Custom material name is required.");this.materials.set(t,{...e,name:t}),this.registerCssVarsForMaterial(e)}static registerCssVarsForMaterial(e){let t=globalThis.CSS;if(!t?.registerProperty)return;let i=e.uniforms||{};for(let r of Object.values(i)){let s=r.css?.trim();if(!s||!s.startsWith("--")||this.registeredCssVars.has(s))continue;let n=this.resolveCssSyntax(r.type);try{t.registerProperty({name:s,syntax:n,inherits:!1,initialValue:this.defaultCssInitialValue(r)}),this.registeredCssVars.add(s)}catch{}}}static resolveCssSyntax(e){switch(e){case"color":return"<color>";case"float":case"int":return"<number>";default:return"*"}}static defaultCssInitialValue(e){return e.type==="color"?typeof e.value=="string"?e.value:"#000000":e.type==="float"||e.type==="int"?typeof e.value=="number"?String(e.value):"0":"initial"}static get(e){return this.materials.get(e.trim().toLowerCase())}static has(e){return this.materials.has(e.trim().toLowerCase())}static list(){return Array.from(this.materials.values())}static unregister(e){return this.materials.delete(e.trim().toLowerCase())}};ue.materials=new Map,ue.registeredCssVars=new Set;function ut(p,e){if(e==null||e===""||e==="none")return p.value;let t=e.trim();switch(p.type){case"float":case"int":{let i=parseFloat(t);return isNaN(i)?p.value:i}case"vec2":{let i=t.split(/[\s,]+/).map(r=>parseFloat(r.trim()));return i.length>=2&&i.every(r=>!isNaN(r))?[i[0],i[1]]:p.value}case"vec3":{let i=t.split(/[\s,]+/).map(r=>parseFloat(r.trim()));return i.length>=3&&i.every(r=>!isNaN(r))?[i[0],i[1],i[2]]:p.value}case"vec4":{let i=t.split(/[\s,]+/).map(r=>parseFloat(r.trim()));return i.length>=4&&i.every(r=>!isNaN(r))?[i[0],i[1],i[2],i[3]]:p.value}case"color":return wt(t)??p.value;case"texture":{let i=t.match(/url\(['"]?(.*?)['"]?\)/);return i?i[1]:t||p.value}default:return p.value}}function wt(p){if(p.startsWith("#")){let t=p.slice(1);if(t.length===3){let i=parseInt(t[0]+t[0],16)/255,r=parseInt(t[1]+t[1],16)/255,s=parseInt(t[2]+t[2],16)/255;return[i,r,s]}if(t.length===6){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[i,r,s]}}let e=p.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return e?[parseInt(e[1])/255,parseInt(e[2])/255,parseInt(e[3])/255]:null}function et(p,e,t){let i={};if(p.parse){let r=p.parse(e,t);Object.assign(i,r)}if(p.uniforms)for(let[r,s]of Object.entries(p.uniforms))if(s.css){let n=t.getPropertyValue(s.css).trim();i[r]=ut(s,n)}else r in i||(i[r]=s.value);return i}function tt(p){let e=new Map;for(let i of p){let r=e.get(i.point)||[];r.push(i),e.set(i.point,r)}let t=new Map;for(let[i,r]of e){let s=r.sort((n,o)=>(n.order??0)-(o.order??0));t.set(i,s.map(n=>n.code).join(`
115
+ `))}return t}var Ce=class{constructor(e,t={}){this._objects=new Map;this._rootObjects=[];this._elementMap=new Map;this._materialInstances=new Map;this._modelLoaderCache=new Map;this.engine=e,this._modelLoader=t.modelLoader,this._modelLoaderFactory=t.modelLoaderFactory,this._scene=e.createScene()}get rootObjects(){return this._rootObjects}getScene(){return this._scene}getObject(e){return this._objects.get(e)}getAllObjects(){let e=[],t=i=>{e.push(i),i.children.forEach(r=>t(r))};return this._rootObjects.forEach(i=>t(i)),e}hasObject(e){return this._objects.has(e)}deleteObject(e){let t=this._objects.get(e);return t?(this._scene.remove(t.object),this._objects.delete(e),this._elementMap.delete(e),this._rootObjects=this._rootObjects.filter(i=>i!==t),t.destroy(),!0):!1}createFromElement(e){let t=e.getProperty("3d");if(!t)return;let i=e.htmlElement;if(!i)return;let r=s=>{if(s){let n=e.getProperty("parentId");n==null?(this._scene.add(s.object),this._rootObjects.push(s)):this._objects.get(n)?.addChild(s),this._objects.set(e.id,s),this._elementMap.set(e.id,i),s.el=i}};switch(t){case"group":this.createGroup(e,r);break;case"pointLight":this.createLight(e,"point",r);break;case"ambientLight":this.createLight(e,"ambient",r);break;case"directionalLight":this.createLight(e,"directional",r);break;case"spotLight":this.createLight(e,"spot",r);break;case"hemisphereLight":this.createLight(e,"hemisphere",r);break;case"model":this.createModel(e,r);break;case"box":this.createBox(e,r);break;case"sphere":this.createSphere(e,r);break;case"plane":this.createPlane(e,r);break;case"cylinder":this.createCylinder(e,r);break;case"particles":this.createParticles(e,r);break;case"text":this.createText(e,r);break}}createGroup(e,t){let i=this.engine.createGroup(),r=new J(e.id,"group",i,this.engine);return t(r),r}createLight(e,t,i){let r=e.htmlElement,s=r?De(r,"--light-color","#ffffff"):"#ffffff",n=s&&s!=="none"?s:"#ffffff",o=r?he(r,"--light-intensity",1):1,a;if(t==="point"){let u=r?he(r,"--light-distance",1e3):1e3,h=r?he(r,"--light-decay",0):0;a=this.engine.createPointLight(n,o,u,h)}else if(t==="directional")a=this.engine.createDirectionalLight(n,o);else if(t==="spot"){let u=r?he(r,"--light-distance",0):0,h=r?he(r,"--light-angle",Math.PI/3):Math.PI/3,d=r?he(r,"--light-penumbra",0):0,m=r?he(r,"--light-decay",1):1;a=this.engine.createSpotLight(n,o,u,h,d,m)}else if(t==="hemisphere"){let u=r?De(r,"--light-ground-color","#ffffff"):"#ffffff",h=u&&u!=="none"?u:"#ffffff";a=this.engine.createHemisphereLight(n,h,o)}else a=this.engine.createAmbientLight(n,o);if((r?Ne(r,"--shadow-cast",!1):!1)&&a.shadow){a.castShadow=!0;let u=r?he(r,"--shadow-bias",0):0,h=r?he(r,"--shadow-map-size",512):512;a.shadow.bias=u,a.shadow.mapSize.width=h,a.shadow.mapSize.height=h}let c=new J(e.id,t+"Light",a,this.engine);return i(c),c}applyShadowProps(e,t){let i=e.htmlElement,r=i?Ne(i,"--shadow-cast",!1):!1,s=i?Ne(i,"--shadow-receive",!1):!1;t.castShadow=r,t.receiveShadow=s}createBox(e,t){let i=this.engine.createBoxGeometry(1,1,1),r=this.createMaterialFromObject(e),s=this.engine.createMesh(i,r);this.applyShadowProps(e,s);let n=new J(e.id,"box",s,this.engine,{geometry:i,material:r});return t(n),n}createSphere(e,t){let i=this.getGeometryQuality(e.htmlElement),r=Math.max(3,Math.round(32*i)),s=Math.max(2,Math.round(32*i)),n=this.engine.createSphereGeometry(.5,r,s),o=this.createMaterialFromObject(e),a=this.engine.createMesh(n,o);this.applyShadowProps(e,a);let l=new J(e.id,"sphere",a,this.engine,{geometry:n,material:o});return t(l),l}createPlane(e,t){let i=this.engine.createPlaneGeometry(1,1),r=this.createMaterialFromObject(e),s=this.engine.createMesh(i,r);this.applyShadowProps(e,s);let n=new J(e.id,"plane",s,this.engine,{geometry:i,material:r});return t(n),n}createCylinder(e,t){let i=this.getGeometryQuality(e.htmlElement),r=Math.max(3,Math.round(32*i)),s=this.engine.createCylinderGeometry(.5,.5,1,r),n=this.createMaterialFromObject(e),o=this.engine.createMesh(s,n);this.applyShadowProps(e,o);let a=new J(e.id,"cylinder",o,this.engine,{geometry:s,material:n});return t(a),a}createModel(e,t){let i=e.getProperty("3d-model");if(!i)return;let r=e.getProperty("3d-model-loader")||void 0,s=this.resolveModelLoader(r);if(!s)return;let n=e.htmlElement;n&&this.applyModelTextureRemap(s,n);let o=e.getProperty("3d-model-center")??!1;s.load(i,a=>{let l=a?.scene||a?.object||a;if(!l)return;let c=n&&this.shouldOverrideModelMaterial(n)?this.createMaterialFromElement(n,e):null;typeof l.traverse=="function"&&l.traverse(h=>{h.isMesh&&(c&&(h.material=c),this.applyShadowProps(e,h))}),o&&this.centerObject(l);let u=new J(e.id,"model",l,this.engine);t(u)},void 0,void 0)}createParticles(e,t){if(!this.engine.createParticleSystem)return;let i=e.htmlElement,r={mode:"emitter",count:300,size:2,color:"#ffffff",opacity:1,spread:120,spreadX:0,spreadY:0,seed:1,emitRate:30,emitBurst:0,particleLife:2.5,particleSpeed:40,particleDirection:[0,1,0],particleGravity:[0,-30,0],particleDrag:.1,particleSizeVariation:.6,particleColorVariation:.2,particleShape:"sphere",particleModelUrl:"",particleModelLoader:"",particleModelNode:"",instanceShape:"sphere",instanceModelUrl:"",instanceModelLoader:"",instanceModelNode:"",instanceScale:1,instanceScaleVariation:.5,instanceRotationSpeed:.4,instanceJitter:.2,instanceFlow:.3,instanceDisperse:0,instanceDisperseScatter:0,instanceDisperseScatterX:0,instanceDisperseScatterY:0,instanceDisperseScatterZ:0,modelTransitionDuration:0},s=this.engine.createParticleSystem(r),n=new J(e.id,"particles",s,this.engine);t(n)}createText(e,t){if(!this.engine.createTextGeometry)return;let i=this.engine.createBoxGeometry(1,1,1),r=this.createMaterialFromObject(e),s=this.engine.createMesh(i,r);this.applyShadowProps(e,s);let n=this.engine.createGroup();n.__textMesh=s,n.add(s);let o=new J(e.id,"text",n,this.engine,{geometry:i,material:r});t(o)}getGeometryQuality(e){if(!e)return 1;let t=he(e,"--geometry-quality",1);return!Number.isFinite(t)||t<=0?1:t}resolveModelLoader(e){if(e){if(this._modelLoaderCache.has(e))return this._modelLoaderCache.get(e);if(!this._modelLoaderFactory)return;let t=this._modelLoaderFactory(this.engine,e);return this._modelLoaderCache.set(e,t),t}if(this._modelLoader)return this._modelLoader;if(this._modelLoaderFactory)return this._modelLoaderFactory(this.engine)}centerObject(e){if(!e)return;let t=this.engine.computeBoundingBoxRecursively(e),i=this.getBoxCenter(t);e.position?.set&&e.position.set(-i.x,-i.y,-i.z),e.updateMatrixWorld(!0)}getBoxCenter(e){let t=this.engine.createVector3();return t.x=(e.min.x+e.max.x)/2,t.y=(e.min.y+e.max.y)/2,t.z=(e.min.z+e.max.z)/2,t}createMaterialFromObject(e){return this.createMaterialFromElement(e.htmlElement,e)}createMaterialFromElement(e,t){let i=e?getComputedStyle(e):null,r=M=>i?i.getPropertyValue(M).trim():"",s=(M,C,j)=>{let N=r(M);return N&&N!=="none"&&N!==""?C(N):j},n=M=>parseFloat(M),o=M=>M,a=M=>{let C=M.match(/url\(['"]?(.*?)['"]?\)/);return C?C[1]:M},l=s("--material-type",M=>M.split("[")[0]||"basic","basic"),c=this.tryCreateCustomMaterial(l,e,i,t);if(c)return c;let u=s("--material-color",o,"#ffffff"),h=s("--opacity",n,1),d=s("--material-metalness",n,0),m=s("--material-roughness",n,1),g=s("--material-emissive",o,"#000000"),f={color:u,transparent:h<1,opacity:h},S=s("--texture-map",a,""),y=s("--texture-normal",a,""),b=s("--texture-roughness",a,""),v=s("--texture-metalness",a,""),E=s("--texture-ao",a,""),I=this.parseFlipY(e),F=e?De(e,"--texture-color-space",""):"",k=!!(S||y||b||v||E),D=l;return D!=="standard"&&k&&(D="standard"),D==="standard"?(S&&(f.map=this.loadTexture(S,{flipY:I,colorSpace:F})),y&&(f.normalMap=this.loadTexture(y,{flipY:I})),b&&(f.roughnessMap=this.loadTexture(b,{flipY:I})),v&&(f.metalnessMap=this.loadTexture(v,{flipY:I})),E&&(f.aoMap=this.loadTexture(E,{flipY:I})),f.metalness=d,f.roughness=m,f.emissive=g,this.engine.createMeshStandardMaterial(f)):this.engine.createMeshBasicMaterial(f)}tryCreateCustomMaterial(e,t,i,r){let s=ue.get(e);if(!s)return null;let n=this.engine.getMaterialFactory?.();if(!n||!n.supports(s))return null;let o={};t&&i&&(o=n.parseUniformsFromCSS(s,t,i));let a=n.create(s,o);return r&&this._materialInstances.set(r.id,a),a.material}updateMaterialUniforms(e,t){let i=this._materialInstances.get(e);i&&i.update(t)}getMaterialInstance(e){return this._materialInstances.get(e)}loadTexture(e,t={}){let r=this.engine.createTextureLoader().load(e);typeof t.flipY=="boolean"&&(r.flipY=t.flipY);let s=(t.colorSpace||"").toLowerCase().trim();return s&&"colorSpace"in r&&(r.colorSpace=s==="srgb"?"srgb":"linear"),r.needsUpdate=!0,r}parseFlipY(e){let t=e?De(e,"--texture-flip-y",""):"";if(t==null||t==="")return;if(typeof t=="boolean")return t;let i=String(t).toLowerCase().trim();if(i==="false"||i==="0"||i==="no")return!1;if(i==="true"||i==="1"||i==="yes")return!0}shouldOverrideModelMaterial(e){let t=getComputedStyle(e),i=s=>{let n=t.getPropertyValue(s);return n&&n!=="0"&&n!=="none"&&n!==""};return i("--material-color")||i("--texture-map")?!0:["--material-type","--material-metalness","--material-roughness","--material-emissive","--opacity","--texture-normal","--texture-roughness","--texture-metalness","--texture-ao"].some(s=>i(s))}applyModelTextureRemap(e,t){let i=(t.getAttribute("string-3d-model-texture-base")||"").trim(),r=i?i.replace(/\/?$/,"/"):"",s=t.getAttribute("string-3d-model-textures"),n=null;if(s)try{n=JSON.parse(s)}catch{}let o=e?.manager;!o||typeof o.setURLModifier!="function"||o.setURLModifier(a=>{let l=n&&a in n?n[a]:a;return!r||/^(blob:|data:|https?:|file:|\/)/i.test(l)?l:r+l.replace(/^\.?\//,"")})}destroy(){this._materialInstances.forEach(e=>e.dispose()),this._materialInstances.clear(),this._objects.forEach(e=>e.destroy()),this._objects.clear(),this._rootObjects=[]}};var ee=class{constructor(){this.cache=new WeakMap;this.meta=new WeakMap}get(e,t,i){if(!!t.dirtySet&&t.forceSync===!1&&!t.dirtySet.has(e)){let a=this.cache.get(e);if(a)return a}let s=performance.now(),n=Math.max(0,t.styleReadIntervalMs??0);if(n>0){let a=this.meta.get(e),l=this.cache.get(e);if(a&&l&&s-a.time<n)return l}let o=i(e);return this.cache.set(e,o),this.meta.set(e,{time:s}),o}clear(){this.cache=new WeakMap,this.meta=new WeakMap}};var it=Math.PI/180,ze=class ze{sync(e,t,i,r){let s=e.__layoutCache,n=s?s.rect:e.getBoundingClientRect(),o=this.readStyleBundle(e,i),a=n.left+n.width*.5,l=n.top+n.height*.5;if(i.camera.getMode()==="orthographic")t.object.position.set(a-i.viewportWidth/2,-(l-i.viewportHeight/2),o.translateZ);else{let c=i.camera.getFrustumSizeAt(o.translateZ),u=a/i.viewportWidth,h=l/i.viewportHeight;t.object.position.set((u-.5)*c.width,-(h-.5)*c.height,o.translateZ)}return t.object.scale.set(o.scale,o.scale,o.scale),t.object.rotation.x=-o.rotateX*it,t.object.rotation.y=o.rotateY*it,t.object.rotation.z=-o.rotateZ*it,t.object.rotation.order="XYZ",t.object.updateMatrixWorld(!0),{scale:o.scale}}readStyleBundle(e,t){return ze.styleCache.get(e,t,i=>{let r=new Se(i);return{translateZ:r.readNumber("--translate-z",0),scale:r.readNumber("--scale",1),rotateX:r.readNumber("--rotate-x",0),rotateY:r.readNumber("--rotate-y",0),rotateZ:r.readNumber("--rotate-z",0)}})}};ze.styleCache=new ee;var Ve=ze;var Be=class Be{sync(e,t,i,r){let s=e.__layoutCache,n=s?s.rect:e.getBoundingClientRect(),o=this.readStyleBundle(e,i,t),a=n.left+n.width*.5,l=n.top+n.height*.5;if(i.camera.getMode()==="orthographic")t.object.position.set(a-i.viewportWidth/2+o.translateX,-(l-i.viewportHeight/2)+o.translateY,o.translateZ);else{let u=i.camera.getFrustumSizeAt(o.translateZ),h=a/i.viewportWidth,d=l/i.viewportHeight;t.object.position.set((h-.5)*u.width+o.translateX,-(d-.5)*u.height+o.translateY,o.translateZ)}let c=t.object;if(o.color&&o.color!=="none"&&c.color&&typeof c.color.set=="function"&&c.color.set(o.color),c.intensity=o.intensity,typeof c.distance<"u"&&o.distance!==void 0&&(c.distance=o.distance),typeof c.decay<"u"&&o.decay!==void 0&&(c.decay=o.decay),typeof c.angle<"u"&&o.angle!==void 0&&(c.angle=o.angle),typeof c.penumbra<"u"&&o.penumbra!==void 0&&(c.penumbra=o.penumbra),o.groundColor&&o.groundColor!=="none"&&c.groundColor&&typeof c.groundColor.set=="function"&&c.groundColor.set(o.groundColor),c.castShadow!==o.castShadow&&(c.castShadow=o.castShadow),o.castShadow&&c.shadow&&(o.shadowBias!==void 0&&(c.shadow.bias=o.shadowBias),o.shadowMapSize!==void 0&&c.shadow.mapSize.width!==o.shadowMapSize&&(c.shadow.mapSize.width=o.shadowMapSize,c.shadow.mapSize.height=o.shadowMapSize)),o.targetId&&o.targetId!=="none"&&c.target){let u=document.querySelector(`[string-id="${o.targetId}"]`);if(u){let h=u.__layoutCache,d=h?h.rect:u.getBoundingClientRect(),g=new Se(u).readNumber("--translate-z",0),f=d.left+d.width*.5,S=d.top+d.height*.5,y,b,v;if(i.camera.getMode()==="orthographic")y=f-i.viewportWidth/2,b=-(S-i.viewportHeight/2),v=g;else{let E=i.camera.getFrustumSizeAt(g),I=f/i.viewportWidth,F=S/i.viewportHeight;y=(I-.5)*E.width,b=-(F-.5)*E.height,v=g}o.targetOffset&&(y+=o.targetOffset.x,b+=o.targetOffset.y,v+=o.targetOffset.z),c.target.position.set(y,b,v),c.target.updateMatrixWorld(!0)}}return null}readStyleBundle(e,t,i){return Be.styleCache.get(e,t,r=>{let s=new Se(r),n=i.object,o={translateZ:s.readNumber("--translate-z",0),translateX:s.readNumber("--translate-x",0),translateY:s.readNumber("--translate-y",0),color:s.readString("--light-color","")||void 0,intensity:s.readNumber("--light-intensity",n.intensity??1),castShadow:s.readBoolean("--shadow-cast",!1)};typeof n.distance<"u"&&(o.distance=s.readNumber("--light-distance",n.distance??0)),typeof n.decay<"u"&&(o.decay=s.readNumber("--light-decay",n.decay??1)),typeof n.angle<"u"&&(o.angle=s.readNumber("--light-angle",n.angle??Math.PI/3)),typeof n.penumbra<"u"&&(o.penumbra=s.readNumber("--light-penumbra",n.penumbra??0));let a=s.readString("--light-ground-color","");a&&(o.groundColor=a),o.castShadow&&n.shadow&&(o.shadowBias=s.readNumber("--shadow-bias",n.shadow.bias??0),o.shadowMapSize=s.readNumber("--shadow-map-size",n.shadow.mapSize.width??512));let l=s.readString("--light-target","").trim();l&&(o.targetId=l);let c=s.readString("--light-target-offset","").trim();if(c){let u=this.parseTargetOffset(c);u&&(o.targetOffset=u)}return o})}parseTargetOffset(e){let t=e.split(/[\s,]+/).map(i=>i.trim()).filter(Boolean).map(i=>Number.parseFloat(i));return t.length<3||t.some(i=>Number.isNaN(i))?null:{x:t[0],y:t[1],z:t[2]}}};Be.styleCache=new ee;var Me=Be;var rt=Math.PI/180,U=class U{static applyVisualProps(e,t,i){let r=U.lastVisualProps.get(t);if(r){if(r.opacity===i.opacity&&r.color===i.color&&r.metalness===i.metalness&&r.roughness===i.roughness&&r.emissive===i.emissive&&r.castShadow===i.castShadow&&r.receiveShadow===i.receiveShadow)return;r.opacity=i.opacity,r.color=i.color,r.metalness=i.metalness,r.roughness=i.roughness,r.emissive=i.emissive,r.castShadow=i.castShadow,r.receiveShadow=i.receiveShadow}else U.lastVisualProps.set(t,{opacity:i.opacity,color:i.color,metalness:i.metalness,roughness:i.roughness,emissive:i.emissive,castShadow:i.castShadow,receiveShadow:i.receiveShadow});let s=i.castShadow??!1,n=i.receiveShadow??!1,o=typeof i.opacity=="number"?i.opacity:NaN,a=l=>{l&&(isNaN(o)||(l.opacity=o,l.transparent=o<1),i.color&&l.color&&l.color.set&&l.color.set(i.color),typeof i.metalness=="number"&&"metalness"in l&&(l.metalness=i.metalness),typeof i.roughness=="number"&&"roughness"in l&&(l.roughness=i.roughness),i.emissive&&l.emissive&&l.emissive.set&&l.emissive.set(i.emissive))};if(t.object.traverse)t.object.traverse(l=>{l.isMesh&&(l.castShadow!==s&&(l.castShadow=s),l.receiveShadow!==n&&(l.receiveShadow=n),(Array.isArray(l.material)?l.material:[l.material]).forEach(a))});else if(t.object.isMesh){let l=t.object;l.castShadow!==s&&(l.castShadow=s),l.receiveShadow!==n&&(l.receiveShadow=n),(Array.isArray(l.material)?l.material:[l.material]).forEach(a)}}sync(e,t,i,r){let{rect:s,width:n,height:o}=this.readLayout(e,i),a=this.readStyleBundle(e,i),{translateZ:l,cssScale:c,rotateX:u,rotateY:h,rotateZ:d,cssScaleZ:m,opacity:g,color:f,metalness:S,roughness:y,emissive:b,castShadow:v,receiveShadow:E,geometryQuality:I}=a,F=s.left+s.width*.5,k=s.top+s.height*.5;if(i.camera.getMode()==="orthographic")t.object.position.set(F-i.viewportWidth/2,-(k-i.viewportHeight/2),l);else{let H=i.camera.getFrustumSizeAt(l),z=F/i.viewportWidth,w=k/i.viewportHeight;t.object.position.set((z-.5)*H.width,-(w-.5)*H.height,l)}t.object.rotation.x=-u*rt,t.object.rotation.y=h*rt,t.object.rotation.z=-d*rt,t.object.rotation.order="XYZ";let D=n*c,M=o*c,C=r?.scale||1,j=m*C,N=D<M?D:M,V,_,W;switch(t.type){case"box":case"sphere":{let H=N*C;V=_=H,W=H*m;break}case"model":{let H=t.getOriginalBoundingBox();U.tempVector3||(U.tempVector3=i.engine.createVector3());let z=H.getSize(U.tempVector3),w=e.getAttribute("string-3d-model-fit"),x=parseFloat(e.getAttribute("string-3d-model-scale")||"1"),O=Number.isFinite(x)?x*C:C;if(z.x>0&&z.y>0){let P=D/z.x,A=M/z.y,L=(w==="cover"?P>A?P:A:P<A?P:A)*O;V=_=L,W=L*m}else{let P=N*O;V=_=P,W=P*m}break}case"cylinder":V=D*C,_=M*C,W=D*j;break;default:V=D*C,_=M*C,W=N*.5*j;break}return t.object.scale.set(V,_,W),U.applyVisualProps(e,t,{opacity:g,color:f&&f!=="none"?f:void 0,metalness:isNaN(S)?void 0:S,roughness:isNaN(y)?void 0:y,emissive:b&&b!=="none"?b:void 0,castShadow:v,receiveShadow:E}),this.applyGeometryQuality(t,I,i),this.updateCustomUniforms(e,t,i),{scale:c*C}}applyGeometryQuality(e,t,i){let r=i.engine,s=r?.simplifyGeometry?.bind(r);if(typeof s!="function")return;let n=Number.isFinite(t)&&t>0?t:1,o=U.lastGeometryQuality.get(e);if(typeof o=="number"&&Math.abs(o-n)<.001)return;U.lastGeometryQuality.set(e,n);let a=l=>{if(!l?.geometry)return;let c=l.userData||(l.userData={});c.__originalGeometry||(c.__originalGeometry=l.geometry);let u=c.__originalGeometry;if(n>=.999){l.geometry=u;return}c.__lodCache||(c.__lodCache=new Map);let h=n.toFixed(3);if(c.__lodCache.has(h)){l.geometry=c.__lodCache.get(h);return}let d=s(u,n);d&&(c.__lodCache.set(h,d),l.geometry=d)};e.object.traverse?e.object.traverse(l=>{l?.isMesh&&a(l)}):e.object.isMesh&&a(e.object)}updateCustomUniforms(e,t,i){let r=i.engine.getMaterialFactory?.();if(!r)return;let s=getComputedStyle(e),n=o=>{let a=o?.userData?.definition;if(!a?.uniforms)return;let l=r.parseUniformsFromCSS(a,e,s);for(let[c,u]of Object.entries(l)){let h=a.uniforms?.[c];if(!h)continue;let d=r.convertUniformValue?.bind(r),m=d?d(h.type,u):u;o.userData?.shader?.uniforms?.[c]?o.userData.shader.uniforms[c].value=m:o.userData?.customUniforms?.[c]?o.userData.customUniforms[c].value=m:o.uniforms?.[c]&&(o.uniforms[c].value=m)}};if(t.object.traverse)t.object.traverse(o=>{o.isMesh&&(Array.isArray(o.material)?o.material:[o.material]).forEach(n)});else if(t.object.isMesh){let o=t.object;(Array.isArray(o.material)?o.material:[o.material]).forEach(n)}}readStyleBundle(e,t){return U.styleCache.get(e,t,i=>{let r=i.computedStyleMap?.(),s=getComputedStyle(i),n=(l,c)=>{let u=r?.get?.(l);if(u!=null){let d=typeof u=="object"&&"value"in u?u.value:u,m=typeof d=="number"?d:Number.parseFloat(String(d));if(!Number.isNaN(m))return m}let h=Number.parseFloat(s.getPropertyValue(l));return Number.isNaN(h)?c:h},o=l=>{let c=r?.get?.(l),u=c&&typeof c=="object"&&"value"in c?c.value:c;return typeof u=="string"?u.trim()||void 0:s.getPropertyValue(l).trim()||void 0},a=(l,c=!1)=>{let u=o(l);if(!u)return c;let h=u.toLowerCase();return h==="true"||h==="1"||h==="yes"?!0:h==="false"||h==="0"||h==="no"?!1:c};return{translateZ:n("--translate-z",0),cssScale:n("--scale",1),rotateX:n("--rotate-x",0),rotateY:n("--rotate-y",0),rotateZ:n("--rotate-z",0),cssScaleZ:n("--scale-z",1),opacity:n("--opacity",NaN),color:o("--material-color"),metalness:n("--material-metalness",NaN),roughness:n("--material-roughness",NaN),emissive:o("--material-emissive"),castShadow:a("--shadow-cast",!1),receiveShadow:a("--shadow-receive",!1),geometryQuality:n("--geometry-quality",1)}})}readLayout(e,t){let i=e.__layoutCache;return i||U.layoutCache.get(e,t,r=>{let s=r.getBoundingClientRect(),n=r.offsetWidth||s.width,o=r.offsetHeight||s.height;return{rect:s,width:n,height:o}})}};U.styleCache=new ee,U.layoutCache=new ee,U.tempVector3=null,U.lastVisualProps=new WeakMap,U.lastGeometryQuality=new WeakMap;var me=U;var st=Math.PI/180,T={mode:"emitter",count:300,size:2,color:"#ffffff",opacity:1,spread:120,spreadX:120,spreadY:120,seed:1,emitRate:30,emitBurst:0,particleLife:2.5,particleSpeed:40,particleDirection:[0,1,0],particleGravity:[0,-30,0],particleDrag:.1,particleSizeVariation:.6,particleColorVariation:.2,particleShape:"sphere",particleModelUrl:"",particleModelLoader:"",particleModelNode:"",instanceShape:"sphere",instanceModelUrl:"",instanceModelLoader:"",instanceModelNode:"",instanceScale:1,instanceScaleVariation:.5,instanceRotationSpeed:.4,instanceJitter:.2,instanceFlow:.3,instanceDisperse:0,instanceDisperseScatter:0,instanceDisperseScatterX:0,instanceDisperseScatterY:0,instanceDisperseScatterZ:0,modelTransitionDuration:0},B=class B{sync(e,t,i,r){let s=e.__layoutCache,n=s?s.rect:e.getBoundingClientRect(),o=this.readStyleBundle(e,i),a=n.left+n.width*.5,l=n.top+n.height*.5;if(i.camera.getMode()==="orthographic")t.object.position.set(a-i.viewportWidth/2,-(l-i.viewportHeight/2),o.translateZ);else{let S=i.camera.getFrustumSizeAt(o.translateZ),y=a/i.viewportWidth,b=l/i.viewportHeight;t.object.position.set((y-.5)*S.width,-(b-.5)*S.height,o.translateZ)}let c=r?.scale??1,u=o.scale*c;t.object.scale.set(u,u,u),t.object.rotation.x=-o.rotateX*st,t.object.rotation.y=o.rotateY*st,t.object.rotation.z=-o.rotateZ*st,t.object.rotation.order="XYZ";let h=this.buildConfig(o,n,i,r),d=B.lastConfig.get(t);(!d||!this.isSameConfig(d,h))&&(B.lastConfig.set(t,h),t.object.setConfig?.(h)),this.updateMaterialOverrides(e,t,i,o),this.updateCustomUniforms(e,t,i);let m=performance.now(),g=B.lastTime.get(t)??m,f=Math.max(0,(m-g)/1e3);return B.lastTime.set(t,m),t.object.update?.(f),{scale:r?.scale??1}}readStyleBundle(e,t){return B.styleCache.get(e,t,i=>{let r=new Se(i),n=r.readString("--particles-mode",T.mode).toLowerCase()==="instanced"?"instanced":"emitter";return{...T,translateZ:r.readNumber("--translate-z",0),scale:r.readNumber("--scale",1),rotateX:r.readNumber("--rotate-x",0),rotateY:r.readNumber("--rotate-y",0),rotateZ:r.readNumber("--rotate-z",0),particlesFit:r.readNumber("--particles-fit",0)>.5,materialType:r.readString("--material-type","basic"),mode:n,count:r.readNumber("--particles-count",T.count),size:r.readNumber("--particles-size",T.size),color:r.readString("--particles-color",T.color),opacity:r.readNumber("--particles-opacity",T.opacity),spread:r.readNumber("--particles-spread",T.spread),seed:r.readNumber("--particles-seed",T.seed),emitRate:r.readNumber("--emit-rate",T.emitRate),emitBurst:r.readNumber("--emit-burst",T.emitBurst),particleLife:r.readNumber("--particle-life",T.particleLife),particleSpeed:r.readNumber("--particle-speed",T.particleSpeed),particleDirection:this.parseVec3(r.readString("--particle-direction","0 1 0"),T.particleDirection),particleGravity:this.parseVec3(r.readString("--particle-gravity","0 -30 0"),T.particleGravity),particleDrag:r.readNumber("--particle-drag",T.particleDrag),particleSizeVariation:r.readNumber("--particle-size-variation",T.particleSizeVariation),particleColorVariation:r.readNumber("--particle-color-variation",T.particleColorVariation),particleShape:this.parseShape(r.readString("--particles-shape",T.particleShape)),particleModelUrl:r.readString("--particles-model",T.particleModelUrl),particleModelLoader:r.readString("--particles-model-loader",T.particleModelLoader),particleModelNode:r.readString("--particles-model-node",T.particleModelNode),instanceShape:this.parseDistribution(r.readString("--instance-shape",T.instanceShape)),instanceModelUrl:r.readString("--instance-model",T.instanceModelUrl),instanceModelLoader:r.readString("--instance-model-loader",T.instanceModelLoader),instanceModelNode:r.readString("--instance-model-node",T.instanceModelNode),instanceScale:r.readNumber("--instance-scale",T.instanceScale),instanceScaleVariation:r.readNumber("--instance-scale-variation",T.instanceScaleVariation),instanceRotationSpeed:r.readNumber("--instance-rotation-speed",T.instanceRotationSpeed),instanceJitter:r.readNumber("--instance-jitter",T.instanceJitter),instanceFlow:r.readNumber("--instance-flow",T.instanceFlow),instanceDisperse:r.readNumber("--instance-disperse",T.instanceDisperse),instanceDisperseScatter:r.readNumber("--instance-scatter",T.instanceDisperseScatter),instanceDisperseScatterX:r.readNumber("--instance-scatter-x",T.instanceDisperseScatterX),instanceDisperseScatterY:r.readNumber("--instance-scatter-y",T.instanceDisperseScatterY),instanceDisperseScatterZ:r.readNumber("--instance-scatter-z",T.instanceDisperseScatterZ),modelTransitionDuration:this.getTransitionDuration(i,"--instance-model")}})}getTransitionDuration(e,t){let i=getComputedStyle(e),r=this.splitTransitionList(i.transitionProperty),s=this.splitTransitionList(i.transitionDuration),n=this.findTransitionIndex(r,t);if(n===-1){let o=this.parseTransitionShorthand(i.transition),a=o.get(t)||o.get("all");return a?a.duration:0}return this.parseTime(s[n]||s[s.length-1]||"0s")}splitTransitionList(e){let t=[],i="",r=0;for(let s=0;s<e.length;s+=1){let n=e[s];n==="("&&(r+=1),n===")"&&(r=Math.max(0,r-1)),n===","&&r===0?(t.push(i.trim()),i=""):i+=n}return i.trim()&&t.push(i.trim()),t.length>0?t:["all"]}findTransitionIndex(e,t){let i=e.map(s=>s.trim().toLowerCase()),r=i.indexOf(t);return r===-1&&(r=i.indexOf("all")),r}parseTime(e){let t=e.trim().toLowerCase();if(t.endsWith("ms")){let r=Number.parseFloat(t.slice(0,-2));return Number.isFinite(r)?r/1e3:0}if(t.endsWith("s")){let r=Number.parseFloat(t.slice(0,-1));return Number.isFinite(r)?r:0}let i=Number.parseFloat(t);return Number.isFinite(i)?i:0}parseTransitionShorthand(e){let t=new Map;return this.splitTransitionList(e).forEach(r=>{if(!r)return;let s=r.trim().split(/\s+(?![^()]*\))/g),n="",o="";s.forEach(a=>{let l=a.toLowerCase();l.endsWith("ms")||l.endsWith("s")||/^[0-9.]+$/.test(l)?o||(o=l):l.startsWith("cubic-bezier")||l.startsWith("steps")||l==="linear"||l==="ease"||l==="ease-in"||l==="ease-out"||l==="ease-in-out"||n||(n=a)}),n&&t.set(n.trim().toLowerCase(),{duration:this.parseTime(o||"0s")})}),t}parseVec3(e,t){let i=e.split(/[\s,]+/).map(r=>Number.parseFloat(r)).filter(r=>!Number.isNaN(r));return i.length>=3?[i[0],i[1],i[2]]:t}parseShape(e){let t=e.trim().toLowerCase();return t==="box"?"box":t==="model"?"model":"sphere"}parseDistribution(e){return this.parseShape(e)}buildConfig(e,t,i,r){let n=r?.scale??1,o=.5,a,l,c;return e.particlesFit?(l=this.toWorld(t.width*o,e.translateZ,i),c=this.toWorld(t.height*o,e.translateZ,i),a=Math.max(l,c)):(a=this.toWorld(e.spread,e.translateZ,i),l=a,c=a),{...e,count:Math.max(0,Math.floor(e.count)),size:Math.max(.1,e.size),opacity:Math.max(0,Math.min(1,e.opacity)),spread:Math.max(0,a*n),spreadX:Math.max(0,l*n),spreadY:Math.max(0,c*n),seed:Math.max(0,Math.floor(e.seed)),emitRate:Math.max(0,e.emitRate),emitBurst:Math.max(0,e.emitBurst),particleLife:Math.max(.1,e.particleLife),particleSpeed:Math.max(0,e.particleSpeed),particleDrag:Math.max(0,Math.min(1,e.particleDrag)),particleSizeVariation:Math.max(0,e.particleSizeVariation),particleColorVariation:Math.max(0,e.particleColorVariation),instanceScale:Math.max(.1,e.instanceScale),instanceScaleVariation:Math.max(0,e.instanceScaleVariation),instanceRotationSpeed:Math.max(0,e.instanceRotationSpeed),instanceJitter:Math.max(0,e.instanceJitter),instanceFlow:Math.max(0,e.instanceFlow),instanceDisperse:Math.max(0,e.instanceDisperse),instanceDisperseScatter:Math.max(0,e.instanceDisperseScatter),instanceDisperseScatterX:Math.max(0,e.instanceDisperseScatterX),instanceDisperseScatterY:Math.max(0,e.instanceDisperseScatterY),instanceDisperseScatterZ:Math.max(0,e.instanceDisperseScatterZ)}}toWorld(e,t,i){if(i.camera.getMode()==="orthographic")return e;let s=i.camera.getFrustumSizeAt(t).width/Math.max(1,i.viewportWidth);return e*s}isSameConfig(e,t){return JSON.stringify(e)===JSON.stringify(t)}updateMaterialOverrides(e,t,i,r){let n=(r.materialType||"basic").split("[")[0].trim().toLowerCase(),o=ue.get(n),a=i.engine.getMaterialFactory?.();if(!o||!a||!a.supports(o)){if(!(B.materialInstances.has(t)||B.lastMaterialType.has(t)))return;let u=B.materialInstances.get(t);u&&(u.dispose(),B.materialInstances.delete(t)),B.lastMaterialType.delete(t),t.object.setMaterial?.(null,{points:!0,meshes:!0});return}if(B.lastMaterialType.get(t)!==n){let c=B.materialInstances.get(t);c&&c.dispose();let u=getComputedStyle(e),h=a.parseUniformsFromCSS(o,e,u),d=a.create(o,h);B.materialInstances.set(t,d),B.lastMaterialType.set(t,n);let m=d.material,g=!!m?.isShaderMaterial,f=t.object;f.setMaterial?.(m,{meshes:!0,points:!1}),f.setMaterial?.(g?m:null,{meshes:!1,points:!0})}}updateCustomUniforms(e,t,i){let r=i.engine.getMaterialFactory?.();if(!r)return;let s=getComputedStyle(e),n=o=>{let a=o?.userData?.definition;if(!a?.uniforms)return;let l=r.parseUniformsFromCSS(a,e,s);for(let[c,u]of Object.entries(l)){let h=a.uniforms?.[c];if(!h)continue;let d=r.convertUniformValue?.bind(r),m=d?d(h.type,u):u;o.userData?.shader?.uniforms?.[c]?o.userData.shader.uniforms[c].value=m:o.userData?.customUniforms?.[c]?o.userData.customUniforms[c].value=m:o.uniforms?.[c]&&(o.uniforms[c].value=m)}};t.object.traverse&&t.object.traverse(o=>{(o.isMesh||o.isPoints)&&(Array.isArray(o.material)?o.material:[o.material]).forEach(n)})}};B.styleCache=new ee,B.lastConfig=new WeakMap,B.lastTime=new WeakMap,B.lastMaterialType=new WeakMap,B.materialInstances=new WeakMap;var _e=B;var ne=class{static register(e,t){let i=e.trim();i&&this.fonts.set(i,{name:i,url:t})}static setDefault(e){let t=e.trim();t&&(this.defaultFont=t)}static get(e){return this.fonts.get(e.trim())}static list(){return Array.from(this.fonts.values())}static resolveFontFamily(e){if(!e)return this.getDefault();let t=e.split(",").map(i=>i.trim().replace(/^["']|["']$/g,"")).filter(Boolean);for(let i of t){let r=this.fonts.get(i);if(r)return r}return this.getDefault()}static getDefault(){return this.defaultFont&&this.fonts.get(this.defaultFont)||null}};ne.fonts=new Map,ne.defaultFont=null;var nt=null,Pe=null,at=null,Te=null;async function Et(){return Pe||(nt||(nt=(async()=>typeof window<"u"&&window.opentype?(Pe=window.opentype,Pe):new Promise((p,e)=>{if(typeof document>"u"){e(new Error("[FontConverter] Cannot load opentype.js in non-browser environment"));return}let t=document.createElement("script");t.src="https://cdn.jsdelivr.net/npm/opentype.js@1.3.4/dist/opentype.min.js",t.onload=()=>{Pe=window.opentype,p(Pe)},t.onerror=()=>e(new Error("[FontConverter] Failed to load opentype.js")),document.head.appendChild(t)}))()),nt)}async function Dt(){return Te||(at||(at=(async()=>typeof window<"u"&&window.Module?.decompress?(Te=window.Module,Te):new Promise((p,e)=>{if(typeof document>"u"){e(new Error("[FontConverter] Cannot load woff2 decoder in non-browser environment"));return}let t=document.createElement("script");t.src="https://cdn.jsdelivr.net/npm/wawoff2@2.0.1/build/decompress_binding.js",t.onload=()=>{let i=0,r=500,s=()=>{i++;let n=window;n.Module?.decompress?(Te=n.Module,p(Te)):i>=r?e(new Error("[FontConverter] woff2 decoder initialization timeout")):setTimeout(s,10)};s()},t.onerror=()=>{e(new Error("[FontConverter] Failed to load woff2 decoder"))},document.head.appendChild(t)}))()),at)}async function Ct(p){let e=await Dt(),t=new Uint8Array(p),i=e.decompress(t);if(i instanceof Uint8Array){let r=new ArrayBuffer(i.length);return new Uint8Array(r).set(i),r}return i.buffer}function Pt(p){return new DataView(p).getUint32(0,!1)===2001684018}var ge=class{static async load(e){let t=typeof e=="string"?e:"buffer-"+Date.now(),i=this.cache.get(t);if(i)return i;let r=this.loadingPromises.get(t);if(r)return r;let s=this.doLoad(e,t);this.loadingPromises.set(t,s);try{let n=await s;return this.cache.set(t,n),n}finally{this.loadingPromises.delete(t)}}static async doLoad(e,t){let i=await Et(),r;if(typeof e=="string")r=await(await fetch(e)).arrayBuffer();else if(e instanceof ArrayBuffer)r=e;else if(e instanceof Uint8Array)r=e.buffer;else throw new Error("[FontConverter] Invalid font source");Pt(r)&&(r=await Ct(r));let s=i.parse(r);if(!s)throw new Error("[FontConverter] Failed to parse font");return this.convertToTypeFace(s)}static convertToTypeFace(e){let t=1e3/e.unitsPerEm,i={};for(let r=0;r<e.glyphs.length;r++){let s=e.glyphs.get(r);if(!s.unicode)continue;let n=String.fromCharCode(s.unicode),o=s.getPath(0,0,e.unitsPerEm),a=this.pathToOutline(o,t),l=s.advanceWidth??s.xMax??e.unitsPerEm*.5;i[n]={ha:Math.round(l*t),x_min:s.xMin!==void 0?Math.round(s.xMin*t):0,x_max:s.xMax!==void 0?Math.round(s.xMax*t):0,o:a}}if(!i[" "]){let r=e.charToGlyph(" ");i[" "]={ha:Math.round((r?.advanceWidth||e.unitsPerEm*.25)*t),x_min:0,x_max:0,o:""}}return{glyphs:i,familyName:e.names.fontFamily?.en||e.names.fullName?.en||"Unknown",ascender:Math.round(e.ascender*t),descender:Math.round(e.descender*t),underlinePosition:Math.round((e.tables.post?.underlinePosition||-100)*t),underlineThickness:Math.round((e.tables.post?.underlineThickness||50)*t),boundingBox:{xMin:Math.round((e.tables.head?.xMin||0)*t),xMax:Math.round((e.tables.head?.xMax||1e3)*t),yMin:Math.round((e.tables.head?.yMin||-200)*t),yMax:Math.round((e.tables.head?.yMax||800)*t)},resolution:1e3,original_font_information:{format:0,copyright:e.names.copyright?.en||"",fontFamily:e.names.fontFamily?.en||"",fontSubfamily:e.names.fontSubfamily?.en||"",uniqueID:e.names.uniqueID?.en||"",fullName:e.names.fullName?.en||"",version:e.names.version?.en||"",postScriptName:e.names.postScriptName?.en||""}}}static pathToOutline(e,t){let i=[];for(let r of e.commands)switch(r.type){case"M":i.push(`m ${this.round(r.x*t)} ${this.round(r.y*t)}`);break;case"L":i.push(`l ${this.round(r.x*t)} ${this.round(r.y*t)}`);break;case"Q":i.push(`q ${this.round(r.x1*t)} ${this.round(r.y1*t)} ${this.round(r.x*t)} ${this.round(r.y*t)}`);break;case"C":i.push(`b ${this.round(r.x1*t)} ${this.round(r.y1*t)} ${this.round(r.x2*t)} ${this.round(r.y2*t)} ${this.round(r.x*t)} ${this.round(r.y*t)}`);break;case"Z":i.push("z");break}return i.join(" ")}static round(e){return Math.round(e*100)/100}static isTypefaceJson(e){let t=e.toLowerCase();return t.endsWith(".json")||t.includes("typeface")}static isFontFile(e){let t=e.toLowerCase();return t.endsWith(".ttf")||t.endsWith(".otf")||t.endsWith(".woff")||t.endsWith(".woff2")}static clearCache(){this.cache.clear()}};ge.cache=new Map,ge.loadingPromises=new Map;var He=Math.PI/180;var Tt=`
116
+ [data-string3d-text] {
117
+ -webkit-text-fill-color: transparent;
212
118
  }
213
119
 
214
- async function initWasm(url) {
215
- try {
216
- const res = await fetch(url);
217
- const bytes = await res.arrayBuffer();
218
- const mod = await WebAssembly.instantiate(bytes, {});
219
- wasm = mod.instance;
220
- wasmReady = true;
221
- } catch (error) {
222
- wasm = null;
223
- wasmReady = false;
224
- }
120
+ [data-string3d-text]::before {
121
+ content: attr(data-string3d-text);
122
+ position: absolute;
123
+ left: 0;
124
+ top: 0;
125
+ width: 100%;
126
+ height: 100%;
127
+ pointer-events: none;
128
+
129
+ color: inherit;
130
+ -webkit-text-fill-color: initial;
131
+ font: inherit;
132
+ text-transform: inherit;
133
+ letter-spacing: inherit;
134
+ line-height: inherit;
135
+ text-align: inherit;
136
+ white-space: inherit;
137
+ word-spacing: inherit;
138
+
139
+ transform: var(--string3d-transform, none);
140
+ transform-style: preserve-3d;
141
+ transform-origin: center center;
225
142
  }
226
-
227
- self.onmessage = async (event) => {
228
- const data = event.data || {};
229
- if (data.type === "init") {
230
- if (data.wasmUrl) {
231
- await initWasm(data.wasmUrl);
232
- }
233
- self.postMessage({ type: "ready", wasmReady });
234
- return;
235
- }
236
-
237
- if (data.type === "compute") {
238
- const items = data.items || [];
239
- const camera = data.camera || {};
240
- const results = new Array(items.length);
241
- for (let i = 0; i < items.length; i += 1) {
242
- results[i] = computeTransform(items[i], camera);
243
- }
244
- self.postMessage({ type: "result", frameId: data.frameId, results });
245
- }
246
- };
247
- `,B=class{constructor(t={}){this.worker=null;this.ready=!1;this.lastResult=null;this.pending=!1;if(typeof Worker>"u")return;let e=new Blob([ye],{type:"text/javascript"});this.worker=new Worker(URL.createObjectURL(e)),this.worker.onmessage=r=>{let i=r.data||{};if(i.type==="ready"){this.ready=!0;return}i.type==="result"&&(this.lastResult={frameId:typeof i.frameId=="number"?i.frameId:0,results:i.results||[]},this.pending=!1)},this.worker.postMessage({type:"init",wasmUrl:t.wasmUrl})}isReady(){return this.ready}isPending(){return this.pending}submit(t,e,r){!this.worker||!this.ready||this.pending||(this.pending=!0,this.worker.postMessage({type:"compute",frameId:r,items:t,camera:e}))}takeLastResult(){let t=this.lastResult;return this.lastResult=null,t}destroy(){this.worker?.terminate(),this.worker=null,this.ready=!1,this.pending=!1,this.lastResult=null}};var j=class j extends X{constructor(e){super(e);this.renderer=null;this.camera=null;this.scene=null;this.synchronizer=null;this.engine=null;this.canvasContainer=null;this.isLoading=new Map;this.useDirtySync=!1;this.dirtyElements=new Set;this.observedElements=new Set;this.resizeObserver=null;this.mutationObserver=null;this.lastSyncData=new WeakMap;this.transformWorker=null;this.workerHasResult=!1;this.workerObjectMap=new Map;this.domVersion=0;this.lastSubmittedVersion=0;this.scrollTicking=!1;this.onScrollBound=()=>this.handleScroll();this.filterStates=new WeakMap;this.filterWarnings=new WeakMap;this.htmlKey="3d",this.options=this.buildOptionsFromSettings(),this.attributesToMap=[...this.attributesToMap,{key:"3d",type:"string",fallback:"box"},{key:"3d-material",type:"string",fallback:"basic[#ffffff]"},{key:"3d-color",type:"string",fallback:"#ffffff"},{key:"3d-opacity",type:"number",fallback:1},{key:"3d-intensity",type:"number",fallback:1},{key:"3d-distance",type:"number",fallback:1e3},{key:"3d-decay",type:"number",fallback:0},{key:"3d-model",type:"string",fallback:""},{key:"3d-segments",type:"number",fallback:32},{key:"3d-segments-width",type:"number",fallback:32},{key:"3d-segments-height",type:"number",fallback:32},{key:"3d-model-loader",type:"string",fallback:""},{key:"3d-model-scale",type:"number",fallback:1},{key:"3d-model-center",type:"boolean",fallback:!1},{key:"3d-model-fit",type:"string",fallback:"contain"},{key:"3d-metalness",type:"number",fallback:0},{key:"3d-roughness",type:"number",fallback:1},{key:"3d-texture-flipY",type:"boolean",fallback:!0},{key:"3d-colorSpace",type:"string",fallback:""},{key:"3d-cast-shadow",type:"boolean",fallback:!1},{key:"3d-receive-shadow",type:"boolean",fallback:!1},{key:"3d-shadow-bias",type:"number",fallback:0},{key:"3d-shadow-map-size",type:"number",fallback:512},{key:"3d-angle",type:"number",fallback:Math.PI/3},{key:"3d-penumbra",type:"number",fallback:0},{key:"3d-ground-color",type:"string",fallback:"#ffffff"},{key:"3d-target",type:"string",fallback:""}]}static setProvider(e){j.provider=e}canConnect(e){let r=super.canConnect(e);return console.log("[String3D] canConnect:",e.id,"keys:",e.keys,"htmlKey:",this.htmlKey,"result:",r),r}initializeObject(e,r,i,s){super.initializeObject(e,r,i,s),r.setProperty("parentId",null);let n=i.parentElement?.closest('[string-3d="group"]');if(n){let a=n.getAttribute("string-id");a&&(r.setProperty("parentId",a),r.setProperty("parent",n))}}onResize(){this.renderer&&this.camera&&this.synchronizer&&(this.renderer.resize(this.camera),this.synchronizer.updateViewportSize(this.renderer.width,this.renderer.height),this.camera.clearScaleCache(),this.useDirtySync&&this.markAllDirty())}onInit(){if(this.options=this.buildOptionsFromSettings(),!j.provider){console.error("[String3D] No provider set. Call String3D.setProvider() before use.");return}this.engine=j.provider.getEngine(),this.canvasContainer=this.createOrGetContainer(),this.registerTypedProperties(),this.injectCSS(),this.useDirtySync=!!this.options.useDirtySync,this.useDirtySync&&(this.setupObservers(),this.setupScrollListeners()),this.renderer=new _(this.canvasContainer,this.engine),this.renderer.attach(),this.camera=new N(this.engine,"orthographic"),this.camera.setPosition(0,0,1e3),this.camera.resize(this.renderer.width,this.renderer.height);let e=this.resolveModelLoader(),r=this.resolveModelLoaderFactory();this.scene=new W(this.engine,{modelLoader:e,modelLoaderFactory:r}),this.scene.getScene().add(this.camera.camera),this.synchronizer=new H(this.camera,this.renderer.width,this.renderer.height,this.engine),this.options.useTransformWorker&&(this.transformWorker=new B({wasmUrl:this.options.transformWorkerWasmUrl})),console.info(`[String3D] Initialized with: ${j.provider.getName()}`)}onSettingsChange(){this.options=this.buildOptionsFromSettings();let e=!!this.options.useDirtySync;e&&!this.useDirtySync?(this.useDirtySync=!0,this.setupObservers(),this.setupScrollListeners(),this.observeSceneElements(),this.markAllDirty()):!e&&this.useDirtySync&&(this.useDirtySync=!1,this.removeScrollListeners(),this.resizeObserver?.disconnect(),this.mutationObserver?.disconnect(),this.dirtyElements.clear());let r=!!this.options.useTransformWorker;r&&!this.transformWorker?(this.transformWorker=new B({wasmUrl:this.options.transformWorkerWasmUrl}),this.workerHasResult=!1):!r&&this.transformWorker&&(this.transformWorker.destroy(),this.transformWorker=null,this.workerHasResult=!1)}buildOptionsFromSettings(){return{hideHTML:this.getSettingValue("hideHTML",!1),container:this.getSettingValue("container",void 0),zIndex:this.getSettingValue("zIndex",1),modelLoaderType:this.getSettingValue("modelLoaderType",void 0),modelLoader:this.getSettingValue("modelLoader",void 0),modelLoaderFactory:this.getSettingValue("modelLoaderFactory",void 0),useDirtySync:this.getSettingValue("useDirtySync",!1),useTransformWorker:this.getSettingValue("useTransformWorker",!1),transformWorkerWasmUrl:this.getSettingValue("transformWorkerWasmUrl",void 0)}}getSettingValue(e,r){return!this.settings||!(e in this.settings)?r:this.settings[e]}resolveModelLoader(){if(this.engine){if(this.options.modelLoader)return this.options.modelLoader;if(!this.options.modelLoaderFactory&&this.options.modelLoaderType)try{return this.engine.createModelLoader(this.options.modelLoaderType)}catch(e){console.warn("[String3D] Failed to create model loader:",e)}}}resolveModelLoaderFactory(){if(this.engine){if(this.options.modelLoaderFactory)return this.options.modelLoaderFactory;if(this.options.modelLoaderType)return(e,r)=>{let i=r||this.options.modelLoaderType;if(!i)throw new Error("[String3D] Model loader type not provided");return e.createModelLoader(i)}}}createOrGetContainer(){if(this.options.container instanceof HTMLElement)return this.applyContainerStyles(this.options.container),this.options.container;if(typeof this.options.container=="string"){let r=document.getElementById(this.options.container);if(r)return this.applyContainerStyles(r),r}let e=document.createElement("div");return e.id="string-3d-canvas",this.applyContainerStyles(e),document.body.insertBefore(e,document.body.firstChild),e}applyContainerStyles(e){Object.assign(e.style,{position:"fixed",left:"0",top:"0",width:"100vw",height:"100lvh",zIndex:String(this.options.zIndex),pointerEvents:"none"})}onObjectConnected(e){this.isLoading.has(e.id)||!this.scene||(this.isLoading.set(e.id,!0),this.scene.createFromElement(e),this.useDirtySync&&e.htmlElement&&(this.observeElement(e.htmlElement),this.markDirty(e.htmlElement)),this.options.hideHTML&&e.htmlElement&&(e.htmlElement.style.opacity="0",e.htmlElement.style.pointerEvents="none"))}onFrame(e){if(!this.renderer||!this.scene||!this.camera||!this.synchronizer)return;let r=this.transformWorker?.takeLastResult();r&&r.frameId===this.lastSubmittedVersion&&r.frameId>=this.domVersion&&(this.workerHasResult=!0,this.applyWorkerResults(r.results));let i=this.useDirtySync?this.dirtyElements:null,s=!i||i.size===0,n=this.transformWorker;if(n?.isReady()&&!n.isPending()){let l=[];if(this.workerObjectMap.clear(),this.scene.rootObjects.forEach(o=>{this.collectWorkerInputs(o,{scale:1},s,i,l)}),l.length>0){let o=this.domVersion;this.lastSubmittedVersion=o,n.submit(l,this.buildWorkerCameraData(),o)}}this.scene.rootObjects.forEach(l=>{this.syncRecursive(l.el,l,{scale:1},s,i)});let a=this.collectFilterTargets(performance.now(),s,i);this.renderer.render(this.scene,this.camera,a),this.useDirtySync&&this.dirtyElements.clear()}syncRecursive(e,r,i,s,n){if(!this.synchronizer||!e)return;let a=s||!n||n.has(e),l=i;if(a){let c=this.synchronizer.syncElement(e,r,i);c&&typeof c.scale=="number"&&(this.lastSyncData.set(r,c),l=c)}else{let c=this.lastSyncData.get(r);c&&(l=c)}let o=s||a;r.children.forEach(c=>this.syncRecursive(c.el,c,l,o,n))}injectCSS(){if(document.getElementById("string-3d-styles"))return;let e=document.createElement("style");e.id="string-3d-styles",e.textContent=`
143
+ `,R=class R{static markObjectPendingFont(e,t){let i=this.pendingFontObjects.get(e);i||(i=new Set,this.pendingFontObjects.set(e,i)),i.add(t),this.log(`Marked object ${t.id} as pending font: ${e}`)}static clearObjectPendingFont(e,t){let i=this.pendingFontObjects.get(e);i&&i.delete(t)}static invalidatePendingObjects(e){let t=this.pendingFontObjects.get(e);t&&(this.log(`Font loaded: ${e}, invalidating ${t.size} pending objects`),t.forEach(i=>{this.geometryKeys.delete(i)}),t.clear())}static injectPseudoElementStyles(){if(this.pseudoStyleInjected||typeof document>"u")return;let e=document.createElement("style");e.setAttribute("data-string3d","pseudo-text"),e.textContent=Tt,document.head.appendChild(e),this.pseudoStyleInjected=!0}static setupSelectableText(e){let t=e.textContent||"";e.dataset.string3dText!==t&&(e.dataset.string3dText=t);let i=getComputedStyle(e);i.position==="static"&&(e.style.position="relative");let r=i.getPropertyValue("--rotate-x").trim()||"0",s=i.getPropertyValue("--rotate-y").trim()||"0",n=i.getPropertyValue("--rotate-z").trim()||"0",o=i.getPropertyValue("--translate-x").trim()||"0px",a=i.getPropertyValue("--translate-y").trim()||"0px",l=i.getPropertyValue("--translate-z").trim()||"0px",c=i.getPropertyValue("--scale").trim()||"1",u=[o!=="0px"&&o!=="0"?`translateX(${o})`:"",a!=="0px"&&a!=="0"?`translateY(${a})`:"",l!=="0px"&&l!=="0"?`translateZ(${l})`:"",r!=="0"?`rotateX(${r}deg)`:"",s!=="0"?`rotateY(${s}deg)`:"",n!=="0"?`rotateZ(${n}deg)`:"",c!=="1"?`scale(${c})`:""].filter(Boolean).join(" ");e.style.setProperty("--string3d-transform",u||"none")}sync(e,t,i,r){R.injectPseudoElementStyles(),R.setupSelectableText(e);let{rect:s,width:n,height:o}=this.readLayout(e,i),a=this.readStyleBundle(e,i),{translateZ:l,cssScale:c,rotateX:u,rotateY:h,rotateZ:d,cssScaleZ:m,opacity:g,color:f,metalness:S,roughness:y,emissive:b,castShadow:v,receiveShadow:E,fontFamily:I,fontSize:F,textTransform:k,textDepth:D,textCurveSegments:M,bevelEnabled:C,bevelSize:j,bevelThickness:N,bevelOffset:V,bevelSegments:_,fontCss:W}=a,H=s.left+s.width*.5,z=s.top+s.height*.5;if(i.camera.getMode()==="orthographic")t.object.position.set(H-i.viewportWidth/2,-(z-i.viewportHeight/2),l);else{let $=i.camera.getFrustumSizeAt(l),G=H/i.viewportWidth,te=z/i.viewportHeight;t.object.position.set((G-.5)*$.width,-(te-.5)*$.height,l)}t.object.rotation.x=-u*He,t.object.rotation.y=h*He,t.object.rotation.z=-d*He,t.object.rotation.order="XYZ",t.object.rotation.z=-d*He,t.object.rotation.order="XYZ";let w=this.extractCharacterLayout(e,k),x=w.map($=>$.char).join(""),O=!!W,P=this.getTextMesh(t);if(!P)return R.log("No mesh found for text object"),{scale:c*(r?.scale||1)};if(w.length===0)return R.log("Empty text content, hiding mesh"),P.visible=!1,{scale:c*(r?.scale||1)};P.visible=!0;let A=ne.resolveFontFamily(I||"");if(!A){return R.warnedMissingFont||(R.warnedMissingFont=!0),{scale:c*(r?.scale||1)};return{scale:c*(r?.scale||1)}}if(!i.engine.loadFont||!i.engine.createTextGeometry)return R.warnedMissingLoader||(R.warnedMissingLoader=!0),{scale:c*(r?.scale||1)};let L=A.url,q=R.fontCache.get(L);if(!q){if(R.markObjectPendingFont(L,t),!R.fontPromises.has(L)){let $=i.engine.loadFont(L).then(G=>(G&&(R.fontCache.set(L,G),R.invalidatePendingObjects(L)),G));R.fontPromises.set(L,$)}return P.visible=!1,{scale:c*(r?.scale||1)}}R.clearObjectPendingFont(L,t);let Z=w.length>0?`${w.length}:${w[0].x.toFixed(1)},${w[0].y.toFixed(1)}:${w[w.length-1].x.toFixed(1)},${w[w.length-1].y.toFixed(1)}`:"empty",Y=[x,F.toFixed(3),W||"",s.width.toFixed(1),s.height.toFixed(1),Z,D.toFixed(3),M.toFixed(3),C?"1":"0",j.toFixed(3),N.toFixed(3),V.toFixed(3),_.toFixed(3)].join("|");if(R.geometryKeys.get(t)!==Y){R.log("Creating new geometry for",x.substring(0,20),"Layout:",Z);let $=R.getFontMetrics(q,F),G=$?$.ascent:F*.8,te=w.map(le=>({...le,y:le.y+G})),Q=i.engine.createTextGeometry(x,q,{size:F,height:D,curveSegments:Math.max(1,Math.round(M)),bevelEnabled:C,bevelThickness:N,bevelSize:j,bevelOffset:V,bevelSegments:Math.max(0,Math.round(_)),lineHeight:0,letterSpacing:0,align:"left",layout:te});Q&&(Q.computeBoundingBox(),P.geometry&&P.geometry.dispose?.(),P.geometry=Q,t.geometry=Q,R.geometryKeys.set(t,Y))}let X=r?.scale||1,ae=i.camera.getMode()==="orthographic"?1:i.camera.getScaleAtZ(l,i.viewportHeight),oe=c*X*ae,fe=oe*m;t.object.scale.set(oe,oe,fe);let ye=-n*.5,be=o*.5;return P.position.set(ye,be,0),me.applyVisualProps(e,t,{opacity:g,color:f&&f!=="none"?f:void 0,metalness:Number.isFinite(S)?S:void 0,roughness:Number.isFinite(y)?y:void 0,emissive:b&&b!=="none"?b:void 0,castShadow:v,receiveShadow:E}),this.updateCustomUniforms(e,t,i),{scale:oe}}extractCharacterLayout(e,t){let i=[];if(typeof document>"u"||!document.createRange)return i;let r=document.createRange(),s=e.getBoundingClientRect(),n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),o;for(;o=n.nextNode();){let a=o.textContent||"";if(!(!a.trim()&&a!==" "))for(let l=0;l<a.length;l++){let c=a[l];if(c===`
144
+ `||c==="\r"||!c.trim())continue;r.setStart(o,l),r.setEnd(o,l+1);let u=r.getClientRects();if(u.length>0){let h=u[0],d=h.left-s.left,m=h.top-s.top,g=this.applyTextTransform(c,t);i.push({char:g,x:d,y:m,width:h.width,height:h.height})}}}return i}getTextMesh(e){let t=e.object;if(t?.__textMesh)return t.__textMesh;if(t?.isMesh)return t;if(Array.isArray(t?.children)){let i=t.children.find(r=>r?.isMesh);if(i)return t.__textMesh=i,i}return null}updateCustomUniforms(e,t,i){let r=i.engine.getMaterialFactory?.();if(!r)return;let s=getComputedStyle(e),n=o=>{let a=o?.userData?.definition;if(!a?.uniforms)return;let l=r.parseUniformsFromCSS(a,e,s);for(let[c,u]of Object.entries(l)){let h=a.uniforms?.[c];if(!h)continue;let d=r.convertUniformValue?.bind(r),m=d?d(h.type,u):u;o.userData?.shader?.uniforms?.[c]?o.userData.shader.uniforms[c].value=m:o.userData?.customUniforms?.[c]?o.userData.customUniforms[c].value=m:o.uniforms?.[c]&&(o.uniforms[c].value=m)}};if(t.object.traverse)t.object.traverse(o=>{o.isMesh&&(Array.isArray(o.material)?o.material:[o.material]).forEach(n)});else{let o=this.getTextMesh(t);if(!o)return;(Array.isArray(o.material)?o.material:[o.material]).forEach(n)}}readStyleBundle(e,t){return R.styleCache.get(e,t,i=>{let r=i.computedStyleMap?.(),s=getComputedStyle(i),n=(D,M)=>{let C=r?.get?.(D);if(C!=null){let V=typeof C=="object"&&"value"in C?C.value:C,_=typeof V=="number"?V:Number.parseFloat(String(V));if(!Number.isNaN(_))return _}let j=s.getPropertyValue(D),N=Number.parseFloat(j);return Number.isNaN(N)?M:N},o=D=>{let M=r?.get?.(D),C=M&&typeof M=="object"&&"value"in M?M.value:M;return typeof C=="string"?C.trim():s.getPropertyValue(D).trim()},a=(D,M=!1)=>{let C=o(D);if(!C)return M;let j=C.toLowerCase();return j==="true"||j==="1"||j==="yes"?!0:j==="false"||j==="0"||j==="no"?!1:M},l=o("--material-color"),c=l&&l!=="none"?l:s.color.trim(),u=(()=>{let D=s.fontSize||"",M=Number.parseFloat(D);return Number.isFinite(M)?M:16})(),h=(()=>{let D=s.lineHeight||"";if(!D||D==="normal")return u*1.2;let M=Number.parseFloat(D);return Number.isFinite(M)?D.endsWith("px")?M:M*u:u*1.2})(),d=(()=>{let D=s.letterSpacing||"";if(!D||D==="normal")return 0;let M=Number.parseFloat(D);return Number.isFinite(M)?M:0})(),m=o("--text-fit")||"none",g=n("--text-depth",NaN),f=Number.isFinite(g)?g:Math.max(1,u*.2),S=n("--text-bevel-size",0),y=n("--text-bevel-thickness",0),b=n("--text-bevel-offset",0),v=n("--text-bevel-steps",0),E=(s.textAlign||"left").toLowerCase(),I=E==="center"?"center":E==="right"||E==="end"?"right":"left",F=s.font?.trim(),k=F&&F.length>0?F:[s.fontStyle||"normal",s.fontWeight||"normal",`${s.fontSize||"16px"}/${s.lineHeight||"normal"}`,s.fontFamily||"sans-serif"].join(" ");return{translateZ:n("--translate-z",0),cssScale:n("--scale",1),rotateX:n("--rotate-x",0),rotateY:n("--rotate-y",0),rotateZ:n("--rotate-z",0),cssScaleZ:n("--scale-z",1),opacity:n("--opacity",NaN),color:c,metalness:n("--material-metalness",NaN),roughness:n("--material-roughness",NaN),emissive:o("--material-emissive"),castShadow:a("--shadow-cast",!1),receiveShadow:a("--shadow-receive",!1),fontFamily:s.fontFamily||"",fontCss:k,fontSize:u,lineHeight:h,letterSpacing:d,textAlign:I,textTransform:(s.textTransform||"").toLowerCase(),textDepth:f,textCurveSegments:n("--text-curve-segments",8),bevelEnabled:S>0||y>0,bevelSize:S,bevelThickness:y,bevelOffset:b,bevelSegments:v,textFit:m==="cover"||m==="none"?m:"contain"}})}applyTextTransform(e,t){return!t||t==="none"?e:t==="uppercase"?e.toUpperCase():t==="lowercase"?e.toLowerCase():t==="capitalize"?e.replace(/\b(\p{L})/gu,i=>i.toUpperCase()):e}static getFontMetrics(e,t){let i=e?.data,r=Number(i?.resolution),s=Number(i?.ascender),n=Number(i?.descender);if(!Number.isFinite(r)||r<=0||!Number.isFinite(s)||!Number.isFinite(n))return null;let o=s/r*t,a=Math.abs(n)/r*t;return!Number.isFinite(o)||!Number.isFinite(a)?null:{ascent:o,descent:a}}readLayout(e,t){let i=e.__layoutCache;return i||R.layoutCache.get(e,t,r=>{let s=r.getBoundingClientRect();return{rect:s,width:s.width,height:s.height}})}};R.styleCache=new ee,R.layoutCache=new ee,R.geometryKeys=new WeakMap,R.fontCache=new Map,R.fontPromises=new Map,R.pendingFontObjects=new Map,R.warnedMissingFont=!1,R.warnedMissingLoader=!1,R.pseudoStyleInjected=!1;var We=R;var Fe=class{constructor(e,t,i,r){this.camera=e;this.viewportWidth=t;this.viewportHeight=i;this.engine=r;this.strategies=new Map;this.styleReadIntervalMs=0;this.layoutReadIntervalMs=0;this.strategies.set("box",new me),this.strategies.set("sphere",new me),this.strategies.set("plane",new me),this.strategies.set("cylinder",new me),this.strategies.set("model",new me),this.strategies.set("group",new Ve),this.strategies.set("pointLight",new Me),this.strategies.set("ambientLight",new Me),this.strategies.set("directionalLight",new Me),this.strategies.set("spotLight",new Me),this.strategies.set("hemisphereLight",new Me),this.strategies.set("particles",new _e),this.strategies.set("text",new We)}syncElement(e,t,i,r){let s=this.strategies.get(t.type);return s?s.sync(e,t,{camera:this.camera,viewportWidth:this.viewportWidth,viewportHeight:this.viewportHeight,engine:this.engine,dirtySet:r?.dirtySet,forceSync:r?.forceSync,styleReadIntervalMs:this.styleReadIntervalMs,layoutReadIntervalMs:this.layoutReadIntervalMs},i):null}setSyncOptions(e){this.styleReadIntervalMs=Math.max(0,e.styleReadIntervalMs??0),this.layoutReadIntervalMs=Math.max(0,e.layoutReadIntervalMs??0)}updateViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t}};var $e=class{constructor(e){this.handleScrollBound=()=>this.handleScroll();this.dirtyElements=new Set;this.observedElements=new Set;this.resizeObserver=null;this.mutationObserver=null;this.enabled=!1;this.domVersion=0;this.attributeFilter=e}enable(){this.enabled||(this.enabled=!0,this.setupObservers(),this.setupScrollListeners())}disable(){this.enabled&&(this.enabled=!1,this.removeScrollListeners(),this.resizeObserver?.disconnect(),this.mutationObserver?.disconnect(),this.dirtyElements.clear(),this.observedElements.clear())}observeElement(e){!this.enabled||this.observedElements.has(e)||(this.observedElements.add(e),this.resizeObserver?.observe(e),this.mutationObserver?.observe(e,{attributes:!0,attributeFilter:this.attributeFilter}))}observeScene(e){this.enabled&&e.forEach(t=>this.observeRecursive(t))}markDirty(e){this.enabled&&(this.dirtyElements.add(e),this.bumpVersion())}markAllDirty(){this.enabled&&(this.observedElements.forEach(e=>this.dirtyElements.add(e)),this.bumpVersion())}getDirtySet(){return this.enabled?this.dirtyElements:null}clearDirty(){this.dirtyElements.clear()}getVersion(){return this.domVersion}isEnabled(){return this.enabled}observeRecursive(e){e.el instanceof HTMLElement&&this.observeElement(e.el),e.children.forEach(t=>this.observeRecursive(t))}handleScroll(){this.markAllDirty()}setupObservers(){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(e=>{e.forEach(t=>{t.target instanceof HTMLElement&&this.markDirty(t.target)})})),typeof MutationObserver<"u"&&(this.mutationObserver=new MutationObserver(e=>{e.forEach(t=>{t.target instanceof HTMLElement&&this.markDirty(t.target)})}))}setupScrollListeners(){window.addEventListener("scroll",this.handleScrollBound,{passive:!0}),window.addEventListener("resize",this.handleScrollBound,{passive:!0}),window.visualViewport&&(window.visualViewport.addEventListener("scroll",this.handleScrollBound,{passive:!0}),window.visualViewport.addEventListener("resize",this.handleScrollBound,{passive:!0}))}removeScrollListeners(){window.removeEventListener("scroll",this.handleScrollBound),window.removeEventListener("resize",this.handleScrollBound),window.visualViewport&&(window.visualViewport.removeEventListener("scroll",this.handleScrollBound),window.visualViewport.removeEventListener("resize",this.handleScrollBound))}bumpVersion(){this.domVersion+=1}};var Ue=class{constructor(e){this.easingParser=e;this.filterStates=new WeakMap;this.filterWarnings=new WeakMap}collectTargets(e,t,i,r){let s=[],n=o=>{let a=o.el;if(a){let l=this.filterStates.get(a)?.animating===!0,c=!i||!r||r.has(a)||l,u=this.readFilterChain(a,t,c);if(u&&u.length>0){let h=!i||!r||r.has(a)||l,d=this.filterStates.get(a)?.effectsKey||this.stringifyFilterChain(u);s.push({object:o,effects:u,effectsKey:d,dirty:h});return}}o.children.forEach(l=>n(l))};return e.forEach(o=>n(o)),s}clear(){this.filterStates=new WeakMap,this.filterWarnings=new WeakMap}readFilterChain(e,t,i){let r=this.filterStates.get(e);if(!i&&r)return r.animating?this.sampleTransition(r,t):r.effects;let s=ht(e);if(!s||s==="none"){if(r){if(r.animating&&r.clearOnComplete){let g=this.sampleTransition(r,t);return r.animating?g:(this.filterStates.delete(e),null)}let{duration:h,delay:d,easing:m}=this.getFilterTransition(e);if(h<=0&&r.lastDuration>0&&(h=r.lastDuration,d=r.lastDelay,m=r.lastEasing),h>0){let g=this.makeZeroChain(r.effects);return r.from=r.effects,r.to=g,r.startTime=t+d,r.duration=h,r.easing=m,r.animating=!0,r.clearOnComplete=!0,r.lastDuration=h,r.lastDelay=d,r.lastEasing=m,this.sampleTransition(r,t)}}return this.filterStates.delete(e),null}let{effects:n,warnings:o}=this.parseFilterChain(s);if(this.warnFilterIssues(e,s,o),n.length===0)return null;let a=this.filterStates.get(e);if(!a){let{duration:h,delay:d,easing:m}=this.getFilterTransition(e);if(h>0){let g=this.makeZeroChain(n),f={raw:s,effects:n,animating:!0,from:g,to:n,startTime:t+d,duration:h,easing:m,clearOnComplete:!1,lastDuration:h,lastDelay:d,lastEasing:m};return f.effectsKey=this.stringifyFilterChain(n),this.filterStates.set(e,f),this.sampleTransition(f,t)}return this.filterStates.set(e,{raw:s,effects:n,animating:!1,from:n,to:n,startTime:0,duration:0,easing:g=>g,clearOnComplete:!1,lastDuration:0,lastDelay:0,lastEasing:g=>g,effectsKey:this.stringifyFilterChain(n)}),n}if(a.raw===s){if(a.animating){let h=this.sampleTransition(a,t);return!a.animating&&a.clearOnComplete?(this.filterStates.delete(e),null):h}return a.effects}a.pendingEffects=void 0,a.pendingRaw=void 0;let{duration:l,delay:c,easing:u}=this.getFilterTransition(e);if(l<=0&&a.lastDuration>0&&(l=a.lastDuration,c=a.lastDelay,u=a.lastEasing),l>0){let h=this.canInterpolate(a.effects,n),d=a.animating?this.getCurrentChain(a,t):a.effects;if(!h&&this.isZeroChain(n))return a.pendingRaw=s,a.pendingEffects=n,a.raw=s,a.effects=d,a.from=d,a.to=this.makeZeroChain(d),a.startTime=t+c,a.duration=l,a.easing=u,a.animating=!0,a.clearOnComplete=!1,a.lastDuration=l,a.lastDelay=c,a.lastEasing=u,a.effectsKey=this.stringifyFilterChain(n),this.sampleTransition(a,t);let m=h?d:this.makeZeroChain(n);return a.raw=s,a.effects=n,a.from=m,a.to=n,a.startTime=t+c,a.duration=l,a.easing=u,a.animating=!0,a.clearOnComplete=!1,a.lastDuration=l,a.lastDelay=c,a.lastEasing=u,a.effectsKey=this.stringifyFilterChain(n),this.sampleTransition(a,t)}return a.raw=s,a.effects=n,a.animating=!1,a.clearOnComplete=!1,a.effectsKey=this.stringifyFilterChain(n),n}warnFilterIssues(e,t,i){i.length===0||this.filterWarnings.get(e)===t||this.filterWarnings.set(e,t)}parseFilterChain(e){let t=[],i=[],r=h=>{let m=h.trim().toLowerCase().match(/^(-?\d*\.?\d+)(px)?$/);if(!m)return null;let g=Number.parseFloat(m[1]);return Number.isFinite(g)?g:null},s=h=>{let d=h.trim().toLowerCase();if(!d)return null;if(d.endsWith("%")){let g=Number.parseFloat(d.slice(0,-1));return Number.isFinite(g)?g/100:null}let m=Number.parseFloat(d);return Number.isFinite(m)?m:null},n=h=>{let d=h.trim().toLowerCase();if(!d)return null;if(d.endsWith("rad")){let f=Number.parseFloat(d.slice(0,-3));return Number.isFinite(f)?f:null}let m=d.endsWith("deg")?d.slice(0,-3):d,g=Number.parseFloat(m);return Number.isFinite(g)?g*Math.PI/180:null},o=h=>{let d=h.split(",").map(f=>f.trim()),m=r(d[0]||"");if(m===null)return null;let g=d[1]?s(d[1]):null;return{intensity:Math.max(0,m),threshold:g===null?.8:Math.max(0,Math.min(1,g))}},a=(h,d,m=!1)=>{let g=r(h);return g===null?(t.push(`[String3D] Invalid ${d} value "${h}".`),null):!m&&g<=0?(t.push(`[String3D] ${d} must be > 0.`),null):g},l=(h,d)=>{let m=s(h);return m===null?(t.push(`[String3D] Invalid ${d} value "${h}".`),null):m},c=/([a-zA-Z-]+)\(([^)]*)\)/g,u;for(;u=c.exec(e);){let h=u[1].toLowerCase(),d=(u[2]||"").trim();if(h==="blur"){let m=a(d,"blur",!0);m!==null&&i.push({type:"blur",amount:m})}else if(h==="pixel"||h==="pixelate"){let m=a(d,"pixel",!0);m!==null&&i.push({type:"pixel",size:m})}else if(h==="bloom"){let m=o(d);m?i.push({type:"bloom",...m}):t.push(`[String3D] Invalid bloom value "${d}".`)}else if(h==="brightness"){let m=l(d,"brightness");m!==null&&i.push({type:"brightness",amount:Math.max(0,m)})}else if(h==="contrast"){let m=l(d,"contrast");m!==null&&i.push({type:"contrast",amount:Math.max(0,m)})}else if(h==="saturate"){let m=l(d,"saturate");m!==null&&i.push({type:"saturate",amount:Math.max(0,m)})}else if(h==="grayscale"){let m=l(d,"grayscale");m!==null&&i.push({type:"grayscale",amount:Math.max(0,Math.min(1,m))})}else if(h==="sepia"){let m=l(d,"sepia");m!==null&&i.push({type:"sepia",amount:Math.max(0,Math.min(1,m))})}else if(h==="invert"){let m=l(d,"invert");m!==null&&i.push({type:"invert",amount:Math.max(0,Math.min(1,m))})}else if(h==="hue-rotate"){let m=n(d);m!==null?i.push({type:"hue-rotate",angle:m}):t.push(`[String3D] Invalid hue-rotate value "${d}".`)}else if(h){let m=ve.get(h);if(m){let g=m.parse?m.parse(d):{};g===null?t.push(`[String3D] Invalid custom filter "${h}" args "${d}".`):i.push({type:"custom",name:h,uniforms:g})}else t.push(`[String3D] Unknown filter "${h}".`)}}return i.length===0&&t.push("[String3D] No valid filters parsed from --filter."),{effects:i,warnings:t}}getFilterTransition(e){let t=getComputedStyle(e),i=this.splitTransitionList(t.transitionProperty),r=this.splitTransitionList(t.transitionDuration),s=this.splitTransitionList(t.transitionDelay),n=this.splitTransitionList(t.transitionTimingFunction),o=this.findTransitionIndex(i,"--filter");if(o===-1){let u=this.parseTransitionShorthand(t.transition),h=u.get("--filter")||u.get("all");return h||{duration:0,delay:0,easing:d=>d}}let a=this.parseTime(r[o]||r[r.length-1]||"0s"),l=this.parseTime(s[o]||s[s.length-1]||"0s"),c=n[o]||n[n.length-1]||"linear";return{duration:a,delay:l,easing:this.parseEasing(c)}}splitTransitionList(e){let t=[],i="",r=0;for(let s=0;s<e.length;s+=1){let n=e[s];n==="("&&(r+=1),n===")"&&(r=Math.max(0,r-1)),n===","&&r===0?(t.push(i.trim()),i=""):i+=n}return i.trim()&&t.push(i.trim()),t.length>0?t:["all"]}findTransitionIndex(e,t){let i=e.map(s=>s.trim().toLowerCase()),r=i.indexOf(t);return r===-1&&(r=i.indexOf("all")),r}parseTime(e){let t=e.trim().toLowerCase();if(t.endsWith("ms")){let r=Number.parseFloat(t.slice(0,-2));return Number.isFinite(r)?r:0}if(t.endsWith("s")){let r=Number.parseFloat(t.slice(0,-1));return Number.isFinite(r)?r*1e3:0}let i=Number.parseFloat(t);return Number.isFinite(i)?i:0}parseTransitionShorthand(e){let t=new Map;return this.splitTransitionList(e).forEach(r=>{if(!r)return;let s=r.trim().split(/\s+(?![^()]*\))/g),n="",o="",a="",l="";s.forEach(c=>{let u=c.toLowerCase();u.endsWith("ms")||u.endsWith("s")||/^[0-9.]+$/.test(u)?o?a||(a=u):o=u:u.startsWith("cubic-bezier")||u.startsWith("steps")||u==="linear"||u==="ease"||u==="ease-in"||u==="ease-out"||u==="ease-in-out"?l=c:n||(n=c)}),n&&t.set(n.trim().toLowerCase(),{duration:this.parseTime(o||"0s"),delay:this.parseTime(a||"0s"),easing:this.parseEasing(l||"linear")})}),t}parseEasing(e){let t=e.trim();if(!t)return i=>i;if(!this.easingParser)return i=>i;try{let i=this.easingParser(t);return typeof i=="function"?i:r=>r}catch{return i=>i}}canInterpolate(e,t){return e.length!==t.length?!1:e.every((i,r)=>{let s=t[r];if(i.type!==s.type)return!1;if(i.type==="custom"&&s.type==="custom"){if(i.name!==s.name)return!1;let n=Object.keys(i.uniforms||{}),o=Object.keys(s.uniforms||{});return n.length!==o.length?!1:n.every(a=>a in(s.uniforms||{})&&this.isNumeric(i.uniforms?.[a]))}return!0})}makeZeroChain(e){return e.map(t=>{switch(t.type){case"blur":return{type:"blur",amount:0};case"pixel":return{type:"pixel",size:0};case"bloom":return{type:"bloom",intensity:0,threshold:t.threshold};case"brightness":return{type:"brightness",amount:1};case"contrast":return{type:"contrast",amount:1};case"saturate":return{type:"saturate",amount:1};case"grayscale":return{type:"grayscale",amount:0};case"sepia":return{type:"sepia",amount:0};case"invert":return{type:"invert",amount:0};case"hue-rotate":return{type:"hue-rotate",angle:0};case"custom":{let i={};return Object.entries(t.uniforms||{}).forEach(([r,s])=>{i[r]=this.isNumeric(s)?0:s}),{type:"custom",name:t.name,uniforms:i}}default:return t}})}sampleTransition(e,t){if(!e.animating)return e.effects;if(t<e.startTime)return e.from;let i=t-e.startTime,r=Math.max(1,e.duration),s=Math.min(1,Math.max(0,i/r)),n=e.easing(s),o=this.interpolateChain(e.from,e.to,n);return s>=1&&(e.animating=!1,e.from=e.to,e.pendingEffects&&e.pendingRaw===e.raw?(e.effects=e.pendingEffects,e.raw=e.pendingRaw||e.raw,e.pendingEffects=void 0,e.pendingRaw=void 0):e.pendingEffects&&(e.pendingEffects=void 0,e.pendingRaw=void 0)),o}getCurrentChain(e,t){if(!e.animating)return e.effects;if(t<e.startTime)return e.from;let i=t-e.startTime,r=Math.max(1,e.duration),s=Math.min(1,Math.max(0,i/r)),n=e.easing(s);return this.interpolateChain(e.from,e.to,n)}interpolateChain(e,t,i){return this.canInterpolate(e,t)?e.map((r,s)=>this.interpolateEffect(r,t[s],i)):t}interpolateEffect(e,t,i){let r=(s,n)=>s+(n-s)*i;if(e.type==="blur"&&t.type==="blur")return{type:"blur",amount:r(e.amount,t.amount)};if(e.type==="pixel"&&t.type==="pixel")return{type:"pixel",size:r(e.size,t.size)};if(e.type==="bloom"&&t.type==="bloom")return{type:"bloom",intensity:r(e.intensity,t.intensity),threshold:r(e.threshold,t.threshold)};if(e.type==="brightness"&&t.type==="brightness")return{type:"brightness",amount:r(e.amount,t.amount)};if(e.type==="contrast"&&t.type==="contrast")return{type:"contrast",amount:r(e.amount,t.amount)};if(e.type==="saturate"&&t.type==="saturate")return{type:"saturate",amount:r(e.amount,t.amount)};if(e.type==="grayscale"&&t.type==="grayscale")return{type:"grayscale",amount:r(e.amount,t.amount)};if(e.type==="sepia"&&t.type==="sepia")return{type:"sepia",amount:r(e.amount,t.amount)};if(e.type==="invert"&&t.type==="invert")return{type:"invert",amount:r(e.amount,t.amount)};if(e.type==="hue-rotate"&&t.type==="hue-rotate")return{type:"hue-rotate",angle:r(e.angle,t.angle)};if(e.type==="custom"&&t.type==="custom"&&e.name===t.name){let s={};return Object.entries(t.uniforms||{}).forEach(([n,o])=>{let a=e.uniforms?.[n];this.isNumeric(a)&&this.isNumeric(o)?s[n]=r(a,o):s[n]=o}),{type:"custom",name:t.name,uniforms:s}}return t}stringifyFilterChain(e){return e.map(i=>{if(i.type==="blur")return`blur:${i.amount}`;if(i.type==="pixel")return`pixel:${i.size}`;if(i.type==="bloom")return`bloom:${i.intensity},${i.threshold}`;if(i.type==="brightness")return`brightness:${i.amount}`;if(i.type==="contrast")return`contrast:${i.amount}`;if(i.type==="saturate")return`saturate:${i.amount}`;if(i.type==="grayscale")return`grayscale:${i.amount}`;if(i.type==="sepia")return`sepia:${i.amount}`;if(i.type==="invert")return`invert:${i.amount}`;if(i.type==="hue-rotate")return`hue-rotate:${i.angle}`;if(i.type==="custom"){let r=Object.keys(i.uniforms||{}).sort().map(s=>`${s}=${i.uniforms[s]}`).join(",");return`custom:${i.name}:${r}`}return"unknown"}).join("|")}isNumeric(e){return typeof e=="number"&&Number.isFinite(e)}isZeroChain(e){return e.every(t=>{switch(t.type){case"blur":return t.amount<=0;case"pixel":return t.size<=0;case"bloom":return t.intensity<=0;case"brightness":return t.amount===1;case"contrast":return t.amount===1;case"saturate":return t.amount===1;case"grayscale":return t.amount===0;case"sepia":return t.amount===0;case"invert":return t.amount===0;case"hue-rotate":return t.angle===0;case"custom":return!1;default:return!1}})}};var xe=class xe extends ke{constructor(t){super(t);this.renderer=null;this.camera=null;this.scene=null;this.synchronizer=null;this.engine=null;this.canvasContainer=null;this.isLoading=new Map;this.useDirtySync=!1;this.lastSyncData=new WeakMap;this.htmlKey="3d",this.options=this.buildOptionsFromSettings(),this.dirtySyncManager=new $e(["style","class","string-3d","string-3d-model-fit","string-3d-model-scale"]),this.filterController=new Ue(i=>this.tools.easingFunction.process({easing:i})),this.attributesToMap=[...this.attributesToMap,{key:"3d",type:"string",fallback:"box"},{key:"3d-model",type:"string",fallback:""},{key:"3d-segments",type:"number",fallback:32},{key:"3d-segments-width",type:"number",fallback:32},{key:"3d-segments-height",type:"number",fallback:32},{key:"3d-model-loader",type:"string",fallback:""},{key:"3d-model-scale",type:"number",fallback:1},{key:"3d-model-center",type:"boolean",fallback:!1},{key:"3d-model-fit",type:"string",fallback:"contain"}]}static setProvider(t){xe.provider=t}static registerFont(t,i,r={}){ne.register(t,i),r.default&&ne.setDefault(t)}static setDefaultFont(t){ne.setDefault(t)}canConnect(t){return super.canConnect(t)}initializeObject(t,i,r,s){super.initializeObject(t,i,r,s),i.setProperty("parentId",null);let n=r.parentElement?.closest('[string-3d="group"]');if(n){let o=n.getAttribute("string-id");o&&(i.setProperty("parentId",o),i.setProperty("parent",n))}}onResize(){this.renderer&&this.camera&&this.synchronizer&&(this.renderer.resize(this.camera),this.synchronizer.updateViewportSize(this.renderer.width,this.renderer.height),this.camera.clearScaleCache(),this.useDirtySync&&this.dirtySyncManager.markAllDirty())}onInit(){if(this.options=this.buildOptionsFromSettings(),!xe.provider)return;this.engine=xe.provider.getEngine(),this.canvasContainer=this.createOrGetContainer(),this.registerTypedProperties(),this.injectCSS(),this.useDirtySync=!!this.options.useDirtySync,this.useDirtySync&&this.dirtySyncManager.enable(),this.renderer=new Ee(this.canvasContainer,this.engine),this.renderer.attach(),this.camera=new we(this.engine,"orthographic"),this.camera.setPosition(0,0,1e3),this.camera.resize(this.renderer.width,this.renderer.height);let t=this.resolveModelLoader(),i=this.resolveModelLoaderFactory();this.scene=new Ce(this.engine,{modelLoader:t,modelLoaderFactory:i}),this.scene.getScene().add(this.camera.camera),this.synchronizer=new Fe(this.camera,this.renderer.width,this.renderer.height,this.engine),this.synchronizer.setSyncOptions({styleReadIntervalMs:this.options.styleReadIntervalMs,layoutReadIntervalMs:this.options.layoutReadIntervalMs}),console.info(`[String3D] Initialized with: ${xe.provider.getName()}`)}onSettingsChange(){this.options=this.buildOptionsFromSettings();let t=!!this.options.useDirtySync;t&&!this.useDirtySync?(this.useDirtySync=!0,this.dirtySyncManager.enable(),this.scene&&this.dirtySyncManager.observeScene(this.scene.rootObjects),this.dirtySyncManager.markAllDirty()):!t&&this.useDirtySync&&(this.useDirtySync=!1,this.dirtySyncManager.disable()),this.synchronizer?.setSyncOptions({styleReadIntervalMs:this.options.styleReadIntervalMs,layoutReadIntervalMs:this.options.layoutReadIntervalMs})}buildOptionsFromSettings(){return{hideHTML:this.getSettingValue("hideHTML",!1),container:this.getSettingValue("container",void 0),zIndex:this.getSettingValue("zIndex",1),modelLoaderType:this.getSettingValue("modelLoaderType",void 0),modelLoader:this.getSettingValue("modelLoader",void 0),modelLoaderFactory:this.getSettingValue("modelLoaderFactory",void 0),useDirtySync:this.getSettingValue("useDirtySync",!1),styleReadIntervalMs:this.getSettingValue("styleReadIntervalMs",0),layoutReadIntervalMs:this.getSettingValue("layoutReadIntervalMs",0)}}getSettingValue(t,i){return!this.settings||!(t in this.settings)?i:this.settings[t]}resolveModelLoader(){if(this.engine){if(this.options.modelLoader)return this.options.modelLoader;if(!this.options.modelLoaderFactory&&this.options.modelLoaderType)try{return this.engine.createModelLoader(this.options.modelLoaderType)}catch{}}}resolveModelLoaderFactory(){if(this.engine){if(this.options.modelLoaderFactory)return this.options.modelLoaderFactory;if(this.options.modelLoaderType)return(t,i)=>{let r=i||this.options.modelLoaderType;if(!r)throw new Error("[String3D] Model loader type not provided");return t.createModelLoader(r)}}}createOrGetContainer(){if(this.options.container instanceof HTMLElement)return this.applyContainerStyles(this.options.container),this.options.container;if(typeof this.options.container=="string"){let i=document.getElementById(this.options.container);if(i)return this.applyContainerStyles(i),i}let t=document.createElement("div");return t.id="string-3d-canvas",this.applyContainerStyles(t),document.body.insertBefore(t,document.body.firstChild),t}applyContainerStyles(t){Object.assign(t.style,{position:"fixed",left:"0",top:"0",width:"100vw",height:"100lvh",zIndex:String(this.options.zIndex),pointerEvents:"none"})}onObjectConnected(t){this.isLoading.has(t.id)||!this.scene||(this.isLoading.set(t.id,!0),this.scene.createFromElement(t),this.useDirtySync&&t.htmlElement&&(this.dirtySyncManager.observeElement(t.htmlElement),this.dirtySyncManager.markDirty(t.htmlElement)),this.options.hideHTML&&t.htmlElement&&(t.htmlElement.style.opacity="0",t.htmlElement.style.pointerEvents="none"))}onFrame(t){if(!this.renderer||!this.scene||!this.camera||!this.synchronizer)return;let i=this.useDirtySync?this.dirtySyncManager.getDirtySet():null,r=!i||i.size===0;this.batchReadLayouts(this.scene.rootObjects,r,i),this.scene.rootObjects.forEach(n=>{this.syncRecursive(n.el,n,{scale:1},r,i)});let s=this.filterController.collectTargets(this.scene.rootObjects,performance.now(),this.useDirtySync,i);this.renderer.render(this.scene,this.camera,s),this.useDirtySync&&this.dirtySyncManager.clearDirty()}batchReadLayouts(t,i,r){let s=n=>{if(n.el&&(i||!r||r.has(n.el))){let a=n.el.getBoundingClientRect(),l=n.el.offsetWidth||a.width,c=n.el.offsetHeight||a.height;n.el.__layoutCache={rect:a,width:l,height:c}}n.children.forEach(s)};t.forEach(s)}syncRecursive(t,i,r,s,n){if(!this.synchronizer||!t)return;let o=i.type==="particles"||i.type==="text"||s||!n||n.has(t),a=r;if(o){let c=this.synchronizer.syncElement(t,i,r,{dirtySet:n,forceSync:s});c&&typeof c.scale=="number"&&(this.lastSyncData.set(i,c),a=c)}else{let c=this.lastSyncData.get(i);c&&(a=c)}let l=s||o;i.children.forEach(c=>this.syncRecursive(c.el,c,a,l,n))}injectCSS(){if(document.getElementById("string-3d-styles"))return;let t=document.createElement("style");t.id="string-3d-styles",t.textContent=`
248
145
  @property --translate-x { syntax: "<number>"; inherits: false; initial-value: 0; }
249
146
  @property --translate-y { syntax: "<number>"; inherits: false; initial-value: 0; }
250
147
  @property --translate-z { syntax: "<number>"; inherits: false; initial-value: 0; }
@@ -257,11 +154,86 @@ self.onmessage = async (event) => {
257
154
  @property --scale-z { syntax: "<number>"; inherits: false; initial-value: 1; }
258
155
  @property --opacity { syntax: "<number>"; inherits: false; initial-value: 1; }
259
156
  @property --filter { syntax: "*"; inherits: false; initial-value: none; }
157
+ @property --light-color { syntax: "<color>"; inherits: false; initial-value: #ffffff; }
158
+ @property --light-intensity { syntax: "<number>"; inherits: false; initial-value: 1; }
159
+ @property --light-distance { syntax: "<number>"; inherits: false; initial-value: 1000; }
160
+ @property --light-decay { syntax: "<number>"; inherits: false; initial-value: 0; }
161
+ @property --light-angle { syntax: "<number>"; inherits: false; initial-value: 1.0472; }
162
+ @property --light-penumbra { syntax: "<number>"; inherits: false; initial-value: 0; }
163
+ @property --light-ground-color { syntax: "<color>"; inherits: false; initial-value: #ffffff; }
164
+ @property --light-target { syntax: "*"; inherits: false; initial-value: none; }
165
+ @property --shadow-cast { syntax: "<number>"; inherits: false; initial-value: 0; }
166
+ @property --shadow-receive { syntax: "<number>"; inherits: false; initial-value: 0; }
167
+ @property --shadow-bias { syntax: "<number>"; inherits: false; initial-value: 0; }
168
+ @property --shadow-map-size { syntax: "<number>"; inherits: false; initial-value: 512; }
169
+ @property --texture-flip-y { syntax: "<number>"; inherits: false; initial-value: 1; }
170
+ @property --texture-color-space { syntax: "*"; inherits: false; initial-value: none; }
171
+ @property --particles-mode { syntax: "*"; inherits: false; initial-value: emitter; }
172
+ @property --particles-count { syntax: "<number>"; inherits: false; initial-value: 300; }
173
+ @property --particles-size { syntax: "<number>"; inherits: false; initial-value: 2; }
174
+ @property --particles-color { syntax: "<color>"; inherits: false; initial-value: #ffffff; }
175
+ @property --particles-opacity { syntax: "<number>"; inherits: false; initial-value: 1; }
176
+ @property --particles-spread { syntax: "<number>"; inherits: false; initial-value: 120; }
177
+ @property --particles-seed { syntax: "<number>"; inherits: false; initial-value: 1; }
178
+ @property --particles-shape { syntax: "*"; inherits: false; initial-value: sphere; }
179
+ @property --particles-fit { syntax: "<number>"; inherits: false; initial-value: 0; }
180
+ @property --particles-model { syntax: "*"; inherits: false; initial-value: none; }
181
+ @property --particles-model-loader { syntax: "*"; inherits: false; initial-value: none; }
182
+ @property --particles-model-node { syntax: "*"; inherits: false; initial-value: none; }
183
+ @property --instance-model { syntax: "*"; inherits: false; initial-value: none; }
184
+ @property --instance-model-loader { syntax: "*"; inherits: false; initial-value: none; }
185
+ @property --instance-model-node { syntax: "*"; inherits: false; initial-value: none; }
186
+ @property --emit-rate { syntax: "<number>"; inherits: false; initial-value: 30; }
187
+ @property --emit-burst { syntax: "<number>"; inherits: false; initial-value: 0; }
188
+ @property --particle-life { syntax: "<number>"; inherits: false; initial-value: 2.5; }
189
+ @property --particle-speed { syntax: "<number>"; inherits: false; initial-value: 40; }
190
+ @property --particle-direction { syntax: "*"; inherits: false; initial-value: 0 1 0; }
191
+ @property --particle-gravity { syntax: "*"; inherits: false; initial-value: 0 -30 0; }
192
+ @property --particle-drag { syntax: "<number>"; inherits: false; initial-value: 0.1; }
193
+ @property --particle-size-variation { syntax: "<number>"; inherits: false; initial-value: 0.6; }
194
+ @property --particle-color-variation { syntax: "<number>"; inherits: false; initial-value: 0.2; }
195
+ @property --instance-shape { syntax: "*"; inherits: false; initial-value: sphere; }
196
+ @property --instance-scale { syntax: "<number>"; inherits: false; initial-value: 1; }
197
+ @property --instance-scale-variation { syntax: "<number>"; inherits: false; initial-value: 0.5; }
198
+ @property --instance-rotation-speed { syntax: "<number>"; inherits: false; initial-value: 0.4; }
199
+ @property --instance-jitter { syntax: "<number>"; inherits: false; initial-value: 0.2; }
200
+ @property --instance-flow { syntax: "<number>"; inherits: false; initial-value: 0.3; }
201
+ @property --instance-disperse { syntax: "<number>"; inherits: false; initial-value: 0; }
202
+ @property --instance-scatter { syntax: "<number>"; inherits: false; initial-value: 0; }
203
+ @property --instance-scatter-x { syntax: "<number>"; inherits: false; initial-value: 0; }
204
+ @property --instance-scatter-y { syntax: "<number>"; inherits: false; initial-value: 0; }
205
+ @property --instance-scatter-z { syntax: "<number>"; inherits: false; initial-value: 0; }
206
+ @property --text-depth { syntax: "<number>"; inherits: false; initial-value: 8; }
207
+ @property --text-curve-segments { syntax: "<number>"; inherits: false; initial-value: 8; }
208
+ @property --text-bevel-size { syntax: "<number>"; inherits: false; initial-value: 0; }
209
+ @property --text-bevel-thickness { syntax: "<number>"; inherits: false; initial-value: 0; }
210
+ @property --text-bevel-offset { syntax: "<number>"; inherits: false; initial-value: 0; }
211
+ @property --text-bevel-steps { syntax: "<number>"; inherits: false; initial-value: 0; }
212
+ @property --text-fit { syntax: "*"; inherits: false; initial-value: contain; }
260
213
 
261
- [string-3d] {
214
+ :where([string-3d]) {
262
215
  --translate-x: 0; --translate-y: 0; --translate-z: 0;
263
216
  --rotate-x: 0; --rotate-y: 0; --rotate-z: 0;
264
- --scale: 1; --scale-x: 1; --scale-y: 1; --scale-z: 1;--opacity: 1; --filter: none;
217
+ --scale: 1; --scale-x: 1; --scale-y: 1; --scale-z: 1; --opacity: 1; --filter: none;
218
+ --light-color: #ffffff; --light-intensity: 1; --light-distance: 1000; --light-decay: 0;
219
+ --light-angle: 1.0472; --light-penumbra: 0; --light-ground-color: #ffffff; --light-target: none;
220
+ --shadow-cast: 0; --shadow-receive: 0; --shadow-bias: 0; --shadow-map-size: 512;
221
+ --texture-flip-y: 1; --texture-color-space: none;
222
+ --particles-mode: emitter; --particles-count: 300; --particles-size: 2; --particles-color: #ffffff;
223
+ --particles-opacity: 1; --particles-spread: 120; --particles-seed: 1; --particles-shape: sphere;
224
+ --particles-fit: 0;
225
+ --particles-model: none; --particles-model-loader: none; --particles-model-node: none;
226
+ --instance-model: none; --instance-model-loader: none; --instance-model-node: none;
227
+ --emit-rate: 30; --emit-burst: 0; --particle-life: 2.5; --particle-speed: 40;
228
+ --particle-direction: 0 1 0; --particle-gravity: 0 -30 0; --particle-drag: 0.1;
229
+ --particle-size-variation: 0.6; --particle-color-variation: 0.2;
230
+ --instance-shape: sphere; --instance-scale: 1; --instance-scale-variation: 0.5;
231
+ --instance-rotation-speed: 0.4; --instance-jitter: 0.2; --instance-flow: 0.3;
232
+ --instance-disperse: 0;
233
+ --instance-scatter: 0;
234
+ --instance-scatter-x: 0; --instance-scatter-y: 0; --instance-scatter-z: 0;
235
+ --text-depth: 8; --text-curve-segments: 8; --text-bevel-size: 0; --text-bevel-thickness: 0;
236
+ --text-bevel-offset: 0; --text-bevel-steps: 0; --text-fit: contain;
265
237
  transform-style: preserve-3d;
266
238
  }
267
239
 
@@ -273,5 +245,58 @@ self.onmessage = async (event) => {
273
245
  rotateZ(calc(var(--rotate-z) * 1deg))
274
246
  scale3d(calc(var(--scale) * var(--scale-x)), calc(var(--scale) * var(--scale-y)), calc(var(--scale) * var(--scale-z)));
275
247
  }
276
- `,document.head.appendChild(e)}registerTypedProperties(){let e=globalThis.CSS;if(!e?.registerProperty)return;[{name:"--translate-x",initialValue:"0"},{name:"--translate-y",initialValue:"0"},{name:"--translate-z",initialValue:"0"},{name:"--rotate-x",initialValue:"0"},{name:"--rotate-y",initialValue:"0"},{name:"--rotate-z",initialValue:"0"},{name:"--scale",initialValue:"1"},{name:"--scale-x",initialValue:"1"},{name:"--scale-y",initialValue:"1"},{name:"--scale-z",initialValue:"1"},{name:"--opacity",initialValue:"1"},{name:"--filter",initialValue:"none"}].forEach(({name:i,initialValue:s})=>{try{e.registerProperty({name:i,syntax:i==="--filter"?"*":"<number>",inherits:!1,initialValue:s})}catch{}})}setupObservers(){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(e=>{e.forEach(r=>{r.target instanceof HTMLElement&&this.markDirty(r.target)})})),typeof MutationObserver<"u"&&(this.mutationObserver=new MutationObserver(e=>{e.forEach(r=>{r.target instanceof HTMLElement&&this.markDirty(r.target)})}))}setupScrollListeners(){window.addEventListener("scroll",this.onScrollBound,{passive:!0}),window.addEventListener("resize",this.onScrollBound,{passive:!0}),window.visualViewport&&(window.visualViewport.addEventListener("scroll",this.onScrollBound,{passive:!0}),window.visualViewport.addEventListener("resize",this.onScrollBound,{passive:!0}))}removeScrollListeners(){window.removeEventListener("scroll",this.onScrollBound),window.removeEventListener("resize",this.onScrollBound),window.visualViewport&&(window.visualViewport.removeEventListener("scroll",this.onScrollBound),window.visualViewport.removeEventListener("resize",this.onScrollBound))}handleScroll(){this.useDirtySync&&this.markAllDirty()}observeElement(e){this.observedElements.has(e)||(this.observedElements.add(e),this.resizeObserver?.observe(e),this.mutationObserver?.observe(e,{attributes:!0,attributeFilter:["style","class","string-3d","string-3d-model-fit","string-3d-model-scale","string-3d-cast-shadow","string-3d-receive-shadow","string-3d-opacity","string-3d-target"]}))}observeSceneElements(){this.scene&&this.scene.rootObjects.forEach(e=>{this.observeRecursive(e)})}observeRecursive(e){e.el instanceof HTMLElement&&this.observeElement(e.el),e.children.forEach(r=>this.observeRecursive(r))}markDirty(e){this.dirtyElements.add(e),this.domVersion+=1}markAllDirty(){this.observedElements.forEach(e=>this.dirtyElements.add(e)),this.domVersion+=1}readNumberStyle(e,r,i){let n=e.computedStyleMap?.()?.get?.(r);if(n!==void 0){if(typeof n=="number")return n;if(typeof n=="string"){let c=Number.parseFloat(n);if(!Number.isNaN(c))return c}if(n&&typeof n=="object"){let c=n.value;if(typeof c=="number")return c;if(typeof c=="string"){let p=Number.parseFloat(c);if(!Number.isNaN(p))return p}}}let l=getComputedStyle(e).getPropertyValue(r),o=Number.parseFloat(l);return Number.isNaN(o)?i:o}readFilterRaw(e){let r=e.computedStyleMap?.(),i="",s=r?.get?.("--filter");if(s!==void 0){if(typeof s=="string")i=s;else if(s&&typeof s=="object"){let n=s.value;typeof n=="string"&&(i=n)}}return i||(i=getComputedStyle(e).getPropertyValue("--filter")||""),i=i.trim(),i}parseFilterChain(e){let r=[],i=[],s=u=>{let d=u.trim().toLowerCase().match(/^(-?\d*\.?\d+)(px)?$/);if(!d)return null;let f=Number.parseFloat(d[1]);return Number.isFinite(f)?f:null},n=u=>{let g=u.trim().toLowerCase();if(!g)return null;if(g.endsWith("%")){let f=Number.parseFloat(g.slice(0,-1));return Number.isFinite(f)?f/100:null}let d=Number.parseFloat(g);return Number.isFinite(d)?d:null},a=u=>{let g=u.trim().toLowerCase();if(!g)return null;if(g.endsWith("rad")){let v=Number.parseFloat(g.slice(0,-3));return Number.isFinite(v)?v:null}let d=g.endsWith("deg")?g.slice(0,-3):g,f=Number.parseFloat(d);return Number.isFinite(f)?f*Math.PI/180:null},l=u=>{let g=u.split(",").map(v=>v.trim()),d=s(g[0]||"");if(d===null)return null;let f=g[1]?n(g[1]):null;return{intensity:Math.max(0,d),threshold:f===null?.8:Math.max(0,Math.min(1,f))}},o=(u,g,d=!1)=>{let f=s(u);return f===null?(r.push(`[String3D] Invalid ${g} value "${u}".`),null):!d&&f<=0?(r.push(`[String3D] ${g} must be > 0.`),null):f},c=(u,g)=>{let d=n(u);return d===null?(r.push(`[String3D] Invalid ${g} value "${u}".`),null):d},p=/([a-zA-Z-]+)\(([^)]*)\)/g,m;for(;m=p.exec(e);){let u=m[1].toLowerCase(),g=(m[2]||"").trim();if(u==="blur"){let d=o(g,"blur",!0);d!==null&&i.push({type:"blur",amount:d})}else if(u==="pixel"||u==="pixelate"){let d=o(g,"pixel",!0);d!==null&&i.push({type:"pixel",size:d})}else if(u==="bloom"){let d=l(g);d?i.push({type:"bloom",...d}):r.push(`[String3D] Invalid bloom value "${g}".`)}else if(u==="brightness"){let d=c(g,"brightness");d!==null&&i.push({type:"brightness",amount:Math.max(0,d)})}else if(u==="contrast"){let d=c(g,"contrast");d!==null&&i.push({type:"contrast",amount:Math.max(0,d)})}else if(u==="saturate"){let d=c(g,"saturate");d!==null&&i.push({type:"saturate",amount:Math.max(0,d)})}else if(u==="grayscale"){let d=c(g,"grayscale");d!==null&&i.push({type:"grayscale",amount:Math.max(0,Math.min(1,d))})}else if(u==="sepia"){let d=c(g,"sepia");d!==null&&i.push({type:"sepia",amount:Math.max(0,Math.min(1,d))})}else if(u==="invert"){let d=c(g,"invert");d!==null&&i.push({type:"invert",amount:Math.max(0,Math.min(1,d))})}else if(u==="hue-rotate"){let d=a(g);d!==null?i.push({type:"hue-rotate",angle:d}):r.push(`[String3D] Invalid hue-rotate value "${g}".`)}else if(u){let d=R.get(u);if(d){let f=d.parse?d.parse(g):{};f===null?r.push(`[String3D] Invalid custom filter "${u}" args "${g}".`):i.push({type:"custom",name:u,uniforms:f})}else r.push(`[String3D] Unknown filter "${u}".`)}}return i.length===0&&r.push("[String3D] No valid filters parsed from --filter."),{effects:i,warnings:r}}warnFilterIssues(e,r,i){i.length===0||this.filterWarnings.get(e)===r||(i.forEach(n=>console.warn(n,e)),this.filterWarnings.set(e,r))}readFilterChain(e,r,i){let s=this.filterStates.get(e);if(!i&&s)return s.animating?this.sampleTransition(s,r):s.effects;let n=this.readFilterRaw(e);if(!n||n==="none"){if(s){if(s.animating&&s.clearOnComplete){let f=this.sampleTransition(s,r);return s.animating?f:(this.filterStates.delete(e),null)}let{duration:u,delay:g,easing:d}=this.getFilterTransition(e);if(u<=0&&s.lastDuration>0&&(u=s.lastDuration,g=s.lastDelay,d=s.lastEasing),u>0){let f=this.makeZeroChain(s.effects);return s.from=s.effects,s.to=f,s.startTime=r+g,s.duration=u,s.easing=d,s.animating=!0,s.clearOnComplete=!0,s.lastDuration=u,s.lastDelay=g,s.lastEasing=d,this.sampleTransition(s,r)}}return this.filterStates.delete(e),null}let{effects:a,warnings:l}=this.parseFilterChain(n);if(this.warnFilterIssues(e,n,l),a.length===0)return null;let o=this.filterStates.get(e);if(!o){let{duration:u,delay:g,easing:d}=this.getFilterTransition(e);if(u>0){let f=this.makeZeroChain(a),v={raw:n,effects:a,animating:!0,from:f,to:a,startTime:r+g,duration:u,easing:d,clearOnComplete:!1,lastDuration:u,lastDelay:g,lastEasing:d};return v.effectsKey=this.stringifyFilterChain(a),this.filterStates.set(e,v),this.sampleTransition(v,r)}return this.filterStates.set(e,{raw:n,effects:a,animating:!1,from:a,to:a,startTime:0,duration:0,easing:f=>f,clearOnComplete:!1,lastDuration:0,lastDelay:0,lastEasing:f=>f,effectsKey:this.stringifyFilterChain(a)}),a}if(o.raw===n){if(o.animating){let u=this.sampleTransition(o,r);return!o.animating&&o.clearOnComplete?(this.filterStates.delete(e),null):u}return o.effects}o.pendingEffects=void 0,o.pendingRaw=void 0;let{duration:c,delay:p,easing:m}=this.getFilterTransition(e);if(c<=0&&o.lastDuration>0&&(c=o.lastDuration,p=o.lastDelay,m=o.lastEasing),c>0){let u=this.canInterpolate(o.effects,a),g=o.animating?this.getCurrentChain(o,r):o.effects;if(!u&&this.isZeroChain(a))return o.pendingRaw=n,o.pendingEffects=a,o.raw=n,o.effects=g,o.from=g,o.to=this.makeZeroChain(g),o.startTime=r+p,o.duration=c,o.easing=m,o.animating=!0,o.clearOnComplete=!1,o.lastDuration=c,o.lastDelay=p,o.lastEasing=m,o.effectsKey=this.stringifyFilterChain(a),this.sampleTransition(o,r);let d=u?g:this.makeZeroChain(a);return o.raw=n,o.effects=a,o.from=d,o.to=a,o.startTime=r+p,o.duration=c,o.easing=m,o.animating=!0,o.clearOnComplete=!1,o.lastDuration=c,o.lastDelay=p,o.lastEasing=m,o.effectsKey=this.stringifyFilterChain(a),this.sampleTransition(o,r)}return o.raw=n,o.effects=a,o.animating=!1,o.clearOnComplete=!1,o.effectsKey=this.stringifyFilterChain(a),a}collectFilterTargets(e,r,i){if(!this.scene)return[];let s=[],n=a=>{let l=a.el;if(l){let o=!this.useDirtySync||!i||i.has(l)||this.filterStates.get(l)?.animating===!0,c=this.readFilterChain(l,e,o);if(c&&c.length>0){let p=!this.useDirtySync||!i||i.has(l)||this.filterStates.get(l)?.animating===!0,m=this.filterStates.get(l)?.effectsKey||this.stringifyFilterChain(c);s.push({object:a,effects:c,effectsKey:m,dirty:p});return}}a.children.forEach(o=>n(o))};return this.scene.rootObjects.forEach(a=>n(a)),s}stringifyFilterChain(e){return e.map(i=>{if(i.type==="blur")return`blur:${i.amount}`;if(i.type==="pixel")return`pixel:${i.size}`;if(i.type==="bloom")return`bloom:${i.intensity},${i.threshold}`;if(i.type==="brightness")return`brightness:${i.amount}`;if(i.type==="contrast")return`contrast:${i.amount}`;if(i.type==="saturate")return`saturate:${i.amount}`;if(i.type==="grayscale")return`grayscale:${i.amount}`;if(i.type==="sepia")return`sepia:${i.amount}`;if(i.type==="invert")return`invert:${i.amount}`;if(i.type==="hue-rotate")return`hue-rotate:${i.angle}`;if(i.type==="custom"){let s=Object.keys(i.uniforms||{}).sort().map(n=>`${n}=${i.uniforms[n]}`).join(",");return`custom:${i.name}:${s}`}return"unknown"}).join("|")}getFilterTransition(e){let r=getComputedStyle(e),i=this.splitTransitionList(r.transitionProperty),s=this.splitTransitionList(r.transitionDuration),n=this.splitTransitionList(r.transitionDelay),a=this.splitTransitionList(r.transitionTimingFunction),l=this.findTransitionIndex(i,"--filter");if(l===-1){let m=this.parseTransitionShorthand(r.transition),u=m.get("--filter")||m.get("all");return u||{duration:0,delay:0,easing:g=>g}}let o=this.parseTime(s[l]||s[s.length-1]||"0s"),c=this.parseTime(n[l]||n[n.length-1]||"0s"),p=a[l]||a[a.length-1]||"linear";return{duration:o,delay:c,easing:this.parseEasing(p)}}splitTransitionList(e){let r=[],i="",s=0;for(let n=0;n<e.length;n+=1){let a=e[n];a==="("&&(s+=1),a===")"&&(s=Math.max(0,s-1)),a===","&&s===0?(r.push(i.trim()),i=""):i+=a}return i.trim()&&r.push(i.trim()),r.length>0?r:["all"]}findTransitionIndex(e,r){let i=e.map(n=>n.trim().toLowerCase()),s=i.indexOf(r);return s===-1&&(s=i.indexOf("all")),s}parseTime(e){let r=e.trim().toLowerCase();if(r.endsWith("ms")){let s=Number.parseFloat(r.slice(0,-2));return Number.isFinite(s)?s:0}if(r.endsWith("s")){let s=Number.parseFloat(r.slice(0,-1));return Number.isFinite(s)?s*1e3:0}let i=Number.parseFloat(r);return Number.isFinite(i)?i:0}parseTransitionShorthand(e){let r=new Map;return this.splitTransitionList(e).forEach(s=>{if(!s)return;let n=s.trim().split(/\s+(?![^()]*\))/g),a="",l="",o="",c="";n.forEach(p=>{let m=p.toLowerCase();m.endsWith("ms")||m.endsWith("s")||/^[0-9.]+$/.test(m)?l?o||(o=m):l=m:m.startsWith("cubic-bezier")||m.startsWith("steps")||m==="linear"||m==="ease"||m==="ease-in"||m==="ease-out"||m==="ease-in-out"?c=p:a||(a=p)}),a&&r.set(a.trim().toLowerCase(),{duration:this.parseTime(l||"0s"),delay:this.parseTime(o||"0s"),easing:this.parseEasing(c||"linear")})}),r}parseEasing(e){let r=e.trim().toLowerCase();if(r==="linear")return i=>i;if(r==="ease")return this.cubicBezier(.25,.1,.25,1);if(r==="ease-in")return this.cubicBezier(.42,0,1,1);if(r==="ease-out")return this.cubicBezier(0,0,.58,1);if(r==="ease-in-out")return this.cubicBezier(.42,0,.58,1);if(r.startsWith("cubic-bezier")){let i=r.match(/cubic-bezier\(([^)]+)\)/);if(i){let s=i[1].split(",").map(n=>Number.parseFloat(n.trim()));if(s.length===4&&s.every(n=>Number.isFinite(n)))return this.cubicBezier(s[0],s[1],s[2],s[3])}}return i=>i}cubicBezier(e,r,i,s){let n=o=>{let c=1-o;return 3*c*c*o*e+3*c*o*o*i+o*o*o},a=o=>{let c=1-o;return 3*c*c*o*r+3*c*o*o*s+o*o*o},l=o=>{let c=o;for(let p=0;p<5;p+=1){let m=n(c)-o,u=3*(1-c)*(1-c)*e+6*(1-c)*c*(i-e)+3*c*c*(1-i);if(Math.abs(m)<1e-5||u===0)break;c-=m/u}return c};return o=>{let c=Math.min(1,Math.max(0,o)),p=l(c);return Math.min(1,Math.max(0,a(p)))}}canInterpolate(e,r){return e.length!==r.length?!1:e.every((i,s)=>{let n=r[s];if(i.type!==n.type)return!1;if(i.type==="custom"&&n.type==="custom"){if(i.name!==n.name)return!1;let a=Object.keys(i.uniforms||{}),l=Object.keys(n.uniforms||{});return a.length!==l.length?!1:a.every(o=>o in n.uniforms&&this.isNumeric(i.uniforms[o]))}return!0})}makeZeroChain(e){return e.map(r=>{switch(r.type){case"blur":return{type:"blur",amount:0};case"pixel":return{type:"pixel",size:0};case"bloom":return{type:"bloom",intensity:0,threshold:r.threshold};case"brightness":return{type:"brightness",amount:1};case"contrast":return{type:"contrast",amount:1};case"saturate":return{type:"saturate",amount:1};case"grayscale":return{type:"grayscale",amount:0};case"sepia":return{type:"sepia",amount:0};case"invert":return{type:"invert",amount:0};case"hue-rotate":return{type:"hue-rotate",angle:0};case"custom":{let i={};return Object.entries(r.uniforms||{}).forEach(([s,n])=>{i[s]=this.isNumeric(n)?0:n}),{type:"custom",name:r.name,uniforms:i}}default:return r}})}sampleTransition(e,r){if(!e.animating)return e.effects;if(r<e.startTime)return e.from;let i=r-e.startTime,s=Math.max(1,e.duration),n=Math.min(1,Math.max(0,i/s)),a=e.easing(n),l=this.interpolateChain(e.from,e.to,a);return n>=1&&(e.animating=!1,e.from=e.to,e.pendingEffects&&e.pendingRaw===e.raw?(e.effects=e.pendingEffects,e.raw=e.pendingRaw||e.raw,e.pendingEffects=void 0,e.pendingRaw=void 0):e.pendingEffects&&(e.pendingEffects=void 0,e.pendingRaw=void 0)),l}getCurrentChain(e,r){if(!e.animating)return e.effects;if(r<e.startTime)return e.from;let i=r-e.startTime,s=Math.max(1,e.duration),n=Math.min(1,Math.max(0,i/s)),a=e.easing(n);return this.interpolateChain(e.from,e.to,a)}interpolateChain(e,r,i){return this.canInterpolate(e,r)?e.map((s,n)=>this.interpolateEffect(s,r[n],i)):r}interpolateEffect(e,r,i){let s=(n,a)=>n+(a-n)*i;if(e.type==="blur"&&r.type==="blur")return{type:"blur",amount:s(e.amount,r.amount)};if(e.type==="pixel"&&r.type==="pixel")return{type:"pixel",size:s(e.size,r.size)};if(e.type==="bloom"&&r.type==="bloom")return{type:"bloom",intensity:s(e.intensity,r.intensity),threshold:s(e.threshold,r.threshold)};if(e.type==="brightness"&&r.type==="brightness")return{type:"brightness",amount:s(e.amount,r.amount)};if(e.type==="contrast"&&r.type==="contrast")return{type:"contrast",amount:s(e.amount,r.amount)};if(e.type==="saturate"&&r.type==="saturate")return{type:"saturate",amount:s(e.amount,r.amount)};if(e.type==="grayscale"&&r.type==="grayscale")return{type:"grayscale",amount:s(e.amount,r.amount)};if(e.type==="sepia"&&r.type==="sepia")return{type:"sepia",amount:s(e.amount,r.amount)};if(e.type==="invert"&&r.type==="invert")return{type:"invert",amount:s(e.amount,r.amount)};if(e.type==="hue-rotate"&&r.type==="hue-rotate")return{type:"hue-rotate",angle:s(e.angle,r.angle)};if(e.type==="custom"&&r.type==="custom"&&e.name===r.name){let n={};return Object.entries(r.uniforms||{}).forEach(([a,l])=>{let o=e.uniforms?.[a];this.isNumeric(o)&&this.isNumeric(l)?n[a]=s(o,l):n[a]=l}),{type:"custom",name:r.name,uniforms:n}}return r}isNumeric(e){return typeof e=="number"&&Number.isFinite(e)}isZeroChain(e){return e.every(r=>{switch(r.type){case"blur":return r.amount<=0;case"pixel":return r.size<=0;case"bloom":return r.intensity<=0;case"brightness":return r.amount===1;case"contrast":return r.amount===1;case"saturate":return r.amount===1;case"grayscale":return r.amount===0;case"sepia":return r.amount===0;case"invert":return r.amount===0;case"hue-rotate":return r.angle===0;case"custom":return!1;default:return!1}})}buildWorkerCameraData(){return{mode:this.camera.getMode(),width:this.renderer.width,height:this.renderer.height,cameraZ:this.camera.getPositionZ(),fov:this.camera.getPerspectiveFov(),aspect:this.renderer.width/this.renderer.height}}collectWorkerInputs(e,r,i,s,n){if(!this.synchronizer||!e.el)return;let a=e.el,l=i||!s||s.has(a),o=r;if(e.type.endsWith("Light")){l&&this.synchronizer.syncElement(a,e,r);return}if(l){let p=a.getBoundingClientRect(),m=a.offsetWidth||p.width,u=a.offsetHeight||p.height,g=this.readNumberStyle(a,"--translate-z",0),d=this.readNumberStyle(a,"--scale",1),f=this.readNumberStyle(a,"--scale-z",1),v=this.readNumberStyle(a,"--rotate-x",0),b=this.readNumberStyle(a,"--rotate-y",0),M=this.readNumberStyle(a,"--rotate-z",0),y=this.readNumberStyle(a,"--opacity",NaN);e.type!=="group"&&k.applyVisualProps(a,e,y);let w,x,S,C;if(e.type==="model"){let I=e.getOriginalBoundingBox().getSize(this.engine.createVector3());w=I.x,x=I.y;let U=parseFloat(a.getAttribute("string-3d-model-scale")||"1");S=Number.isFinite(U)?U:1,C=(a.getAttribute("string-3d-model-fit")||"contain").toLowerCase().trim()}let P=e.type==="group"?d:d*r.scale;this.lastSyncData.set(e,{scale:P}),o={scale:P},this.workerObjectMap.set(e.id,{object:e,el:a}),n.push({id:e.id,type:e.type,rectLeft:p.left,rectTop:p.top,rectWidth:m,rectHeight:u,translateZ:g,scale:d,scaleZ:f,rotateX:v,rotateY:b,rotateZ:M,parentScale:r.scale,modelSizeX:w,modelSizeY:x,modelScale:S,fitMode:C})}else{let p=this.lastSyncData.get(e);p&&(o=p)}let c=i||l;e.children.forEach(p=>{this.collectWorkerInputs(p,o,c,s,n)})}applyWorkerResults(e){this.engine&&e.forEach(r=>{let i=this.workerObjectMap.get(r.id);if(!i)return;let s=i.object;s.position=this.engine.createVector3(r.posX,r.posY,r.posZ),s.rotation=this.engine.createEuler(r.rotX,r.rotY,r.rotZ,"XYZ"),s.scale=this.engine.createVector3(r.scaleX,r.scaleY,r.scaleZ),s.type==="group"&&s.object.updateMatrixWorld(!0)})}destroy(){this.renderer?.destroy(),this.scene?.destroy(),this.isLoading.clear(),this.transformWorker?.destroy(),this.transformWorker=null,this.removeScrollListeners(),this.resizeObserver?.disconnect(),this.mutationObserver?.disconnect(),this.observedElements.clear(),this.dirtyElements.clear(),this.workerObjectMap.clear(),this.lastSyncData=new WeakMap,document.getElementById("string-3d-styles")?.remove(),this.canvasContainer?.id==="string-3d-canvas"&&this.canvasContainer.remove(),super.destroy()}};j.provider=null;var G=j;var $=class{constructor(t,e={}){this.THREE=t,this.loaders=e}createVector3(t=0,e=0,r=0){return new this.THREE.Vector3(t,e,r)}createVector2(t=0,e=0){return new this.THREE.Vector2(t,e)}createQuaternion(t=0,e=0,r=0,i=1){return new this.THREE.Quaternion(t,e,r,i)}createEuler(t=0,e=0,r=0,i="XYZ"){return new this.THREE.Euler(t,e,r,i)}createMatrix4(){return new this.THREE.Matrix4}createBox3(t,e){return new this.THREE.Box3(t,e)}createScene(){return new this.THREE.Scene}createRenderer(t){let e=new this.THREE.WebGLRenderer(t);return e.outputEncoding=this.THREE.sRGBEncoding,e}createPerspectiveCamera(t=45,e=1,r=.1,i=2e3){return new this.THREE.PerspectiveCamera(t,e,r,i)}createOrthographicCamera(t,e,r,i,s=.1,n=1e4){return new this.THREE.OrthographicCamera(t,e,r,i,s,n)}createGroup(){return new this.THREE.Group}createMesh(t,e){return new this.THREE.Mesh(t,e)}createBoxGeometry(t,e,r){return new this.THREE.BoxGeometry(t,e,r)}createSphereGeometry(t,e=32,r=32){return new this.THREE.SphereGeometry(t,e,r)}createPlaneGeometry(t,e){return new this.THREE.PlaneGeometry(t,e)}createCylinderGeometry(t,e,r,i=32){return new this.THREE.CylinderGeometry(t,e,r,i)}createMeshBasicMaterial(t){return new this.THREE.MeshBasicMaterial(t)}createMeshStandardMaterial(t){return new this.THREE.MeshStandardMaterial(t)}createShaderMaterial(t){return new this.THREE.ShaderMaterial(t)}createPointLight(t,e=1,r=0,i=2){return new this.THREE.PointLight(t,e,r,i)}createSpotLight(t,e=1,r=0,i=Math.PI/3,s=0,n=1){return new this.THREE.SpotLight(t,e,r,i,s,n)}createHemisphereLight(t,e,r=1){return new this.THREE.HemisphereLight(t,e,r)}createAmbientLight(t,e=1){return new this.THREE.AmbientLight(t,e)}createDirectionalLight(t,e=1){return new this.THREE.DirectionalLight(t,e)}createTextureLoader(){return new this.THREE.TextureLoader}createModelLoader(t){let e=this.loaders[t];if(!e)throw new Error(`[ThreeJSEngine] Model loader "${t}" not registered`);return new e}createRenderTarget(t,e,r={}){let i={minFilter:this.THREE.LinearFilter,magFilter:this.THREE.LinearFilter,format:this.THREE.RGBAFormat,depthBuffer:!0,stencilBuffer:!1};return new this.THREE.WebGLRenderTarget(t,e,{...i,...r})}degToRad(t){return this.THREE.MathUtils.degToRad(t)}radToDeg(t){return this.THREE.MathUtils.radToDeg(t)}computeBoundingBoxRecursively(t){let e=new this.THREE.Box3,r=!1;return t.traverse&&t.traverse(i=>{if(i.visible&&i.geometry){typeof i.geometry.computeBoundingBox=="function"&&i.geometry.computeBoundingBox();let s=i.geometry.boundingBox;if(s){let n=s.clone().applyMatrix4(i.matrixWorld);e.union(n),r=!0}}}),r?e:new this.THREE.Box3}},Q=class{constructor(t,e={}){this.engine=new $(t,e)}getEngine(){return this.engine}getName(){return"Three.js"}};return ue(be);})();
248
+ `,document.head.appendChild(t)}registerTypedProperties(){let t=globalThis.CSS;if(!t?.registerProperty)return;[{name:"--translate-x",initialValue:"0"},{name:"--translate-y",initialValue:"0"},{name:"--translate-z",initialValue:"0"},{name:"--rotate-x",initialValue:"0"},{name:"--rotate-y",initialValue:"0"},{name:"--rotate-z",initialValue:"0"},{name:"--scale",initialValue:"1"},{name:"--scale-x",initialValue:"1"},{name:"--scale-y",initialValue:"1"},{name:"--scale-z",initialValue:"1"},{name:"--opacity",initialValue:"1"},{name:"--filter",initialValue:"none"},{name:"--material-type",initialValue:"basic"},{name:"--material-color",initialValue:"#ffffff"},{name:"--material-metalness",initialValue:"0"},{name:"--material-roughness",initialValue:"1"},{name:"--material-emissive",initialValue:"#000000"},{name:"--rim-color",initialValue:"#00c8ff"},{name:"--rim-power",initialValue:"1.5"},{name:"--rim-strength",initialValue:"1"},{name:"--uv-strength",initialValue:"0.7"},{name:"--texture-map",initialValue:"none"},{name:"--texture-normal",initialValue:"none"},{name:"--texture-roughness",initialValue:"none"},{name:"--texture-metalness",initialValue:"none"},{name:"--texture-ao",initialValue:"none"},{name:"--light-color",initialValue:"#ffffff"},{name:"--light-intensity",initialValue:"1"},{name:"--light-distance",initialValue:"1000"},{name:"--light-decay",initialValue:"0"},{name:"--light-angle",initialValue:"1.0472"},{name:"--light-penumbra",initialValue:"0"},{name:"--light-ground-color",initialValue:"#ffffff"},{name:"--light-target",initialValue:"none"},{name:"--shadow-cast",initialValue:"0"},{name:"--shadow-receive",initialValue:"0"},{name:"--shadow-bias",initialValue:"0"},{name:"--shadow-map-size",initialValue:"512"},{name:"--texture-flip-y",initialValue:"1"},{name:"--texture-color-space",initialValue:"none"},{name:"--particles-mode",initialValue:"emitter"},{name:"--particles-count",initialValue:"300"},{name:"--particles-size",initialValue:"2"},{name:"--particles-color",initialValue:"#ffffff"},{name:"--particles-opacity",initialValue:"1"},{name:"--particles-spread",initialValue:"120"},{name:"--particles-seed",initialValue:"1"},{name:"--particles-shape",initialValue:"sphere"},{name:"--particles-fit",initialValue:"0"},{name:"--particles-model",initialValue:"none"},{name:"--particles-model-loader",initialValue:"none"},{name:"--particles-model-node",initialValue:"none"},{name:"--instance-model",initialValue:"none"},{name:"--instance-model-loader",initialValue:"none"},{name:"--instance-model-node",initialValue:"none"},{name:"--emit-rate",initialValue:"30"},{name:"--emit-burst",initialValue:"0"},{name:"--particle-life",initialValue:"2.5"},{name:"--particle-speed",initialValue:"40"},{name:"--particle-direction",initialValue:"0 1 0"},{name:"--particle-gravity",initialValue:"0 -30 0"},{name:"--particle-drag",initialValue:"0.1"},{name:"--particle-size-variation",initialValue:"0.6"},{name:"--particle-color-variation",initialValue:"0.2"},{name:"--instance-shape",initialValue:"sphere"},{name:"--instance-scale",initialValue:"1"},{name:"--instance-scale-variation",initialValue:"0.5"},{name:"--instance-rotation-speed",initialValue:"0.4"},{name:"--instance-jitter",initialValue:"0.2"},{name:"--instance-flow",initialValue:"0.3"},{name:"--instance-disperse",initialValue:"0"},{name:"--instance-scatter",initialValue:"0"},{name:"--instance-scatter-x",initialValue:"0"},{name:"--instance-scatter-y",initialValue:"0"},{name:"--instance-scatter-z",initialValue:"0"},{name:"--text-depth",initialValue:"8"},{name:"--text-curve-segments",initialValue:"8"},{name:"--text-bevel-size",initialValue:"0"},{name:"--text-bevel-thickness",initialValue:"0"},{name:"--text-bevel-offset",initialValue:"0"},{name:"--text-bevel-steps",initialValue:"0"},{name:"--text-fit",initialValue:"contain"}].forEach(({name:r,initialValue:s})=>{try{t.registerProperty({name:r,syntax:r==="--filter"||r==="--light-target"||r.startsWith("--texture-")||r==="--material-type"||r==="--particles-mode"||r==="--particles-shape"||r==="--particles-model"||r==="--particles-model-loader"||r==="--particles-model-node"||r==="--instance-model"||r==="--instance-model-loader"||r==="--instance-model-node"||r==="--particle-direction"||r==="--particle-gravity"||r==="--instance-shape"||r==="--text-fit"?"*":r.includes("color")||r.includes("emissive")?"<color>":"<number>",inherits:!1,initialValue:s})}catch{}})}destroy(){this.renderer?.destroy(),this.scene?.destroy(),this.isLoading.clear(),this.dirtySyncManager.disable(),this.filterController.clear(),this.lastSyncData=new WeakMap,document.getElementById("string-3d-styles")?.remove(),this.canvasContainer?.id==="string-3d-canvas"&&this.canvasContainer.remove(),super.destroy()}};xe.provider=null;var Ge=xe;var Le=class{constructor(e){this.textureCache=new Map;this.THREE=e,this.textureLoader=new e.TextureLoader}supports(e){return!0}create(e,t){let i=this.buildUniforms(e,t),r;return e.extends==="shader"||!e.extends&&e.vertexShader?r=this.createShaderMaterial(e,i):r=this.createExtendedMaterial(e,i),this.applyMaterialProperties(r,e),{material:r,definition:e,update:o=>{this.updateUniforms(r,e,o)},dispose:()=>{r.dispose()}}}parseUniformsFromCSS(e,t,i){return et(e,t,i)}buildUniforms(e,t){let i={};if(e.uniforms)for(let[r,s]of Object.entries(e.uniforms)){let n=t?.[r]??s.value;n=this.convertUniformValue(s.type,n),i[r]={value:n}}return i}convertUniformValue(e,t){switch(e){case"vec2":return Array.isArray(t)?new this.THREE.Vector2(t[0],t[1]):t;case"vec3":return Array.isArray(t)?new this.THREE.Vector3(t[0],t[1],t[2]):t;case"vec4":return Array.isArray(t)?new this.THREE.Vector4(t[0],t[1],t[2],t[3]):t;case"color":return Array.isArray(t)?new this.THREE.Color(t[0],t[1],t[2]):typeof t=="string"?new this.THREE.Color(t):t;case"texture":return typeof t=="string"&&t?this.loadTexture(t):t;default:return t}}loadTexture(e){if(this.textureCache.has(e))return this.textureCache.get(e);let t=this.textureLoader.load(e);return this.textureCache.set(e,t),t}createShaderMaterial(e,t){let i=new this.THREE.ShaderMaterial({uniforms:t,vertexShader:e.vertexShader||this.getDefaultVertexShader(),fragmentShader:e.fragmentShader||this.getDefaultFragmentShader(),lights:e.lights??!1,transparent:e.properties?.transparent??!1});return i.userData.customUniforms=t,i.userData.definition=e,i}createExtendedMaterial(e,t){let i=e.extends||"standard",r;switch(i){case"basic":r=this.THREE.MeshBasicMaterial;break;case"physical":r=this.THREE.MeshPhysicalMaterial;break;case"standard":default:r=this.THREE.MeshStandardMaterial;break}let s=new r({transparent:e.properties?.transparent??!1});if(e.injections&&e.injections.length>0){let n=tt(e.injections);s.onBeforeCompile=o=>{Object.assign(o.uniforms,t),o.vertexShader=this.injectVertexShader(o.vertexShader,n,t),o.fragmentShader=this.injectFragmentShader(o.fragmentShader,n,t),s.userData.shader=o}}return s.userData.customUniforms=t,s.userData.definition=e,s}injectVertexShader(e,t,i){let r=e,s=t.get("vertex_pars");s&&(r=r.replace("#include <common>",`#include <common>
249
+ ${s}`));let n=t.get("vertex_header");if(n){let l=this.generateUniformDeclarations(i);r=r.replace("void main() {",`${l}
250
+ ${n}
251
+ void main() {`)}let o=t.get("vertex_transform");o&&(r=r.replace("#include <begin_vertex>",`#include <begin_vertex>
252
+ ${o}`));let a=t.get("vertex_output");return a&&(r=r.replace("#include <project_vertex>",`${a}
253
+ #include <project_vertex>`)),r}injectFragmentShader(e,t,i){let r=e,s=t.get("fragment_pars");s&&(r=r.replace("#include <common>",`#include <common>
254
+ ${s}`));let n=t.get("fragment_header");if(n){let u=this.generateUniformDeclarations(i);r=r.replace("void main() {",`${u}
255
+ ${n}
256
+ void main() {`)}let o=t.get("fragment_color");o&&(r=r.replace("#include <color_fragment>",`#include <color_fragment>
257
+ ${o}`));let a=t.get("fragment_normal");a&&(r=r.replace("#include <normal_fragment_maps>",`#include <normal_fragment_maps>
258
+ ${a}`));let l=t.get("fragment_emissive");l&&(r=r.replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
259
+ ${l}`));let c=t.get("fragment_output");return c&&(r=r.replace("#include <dithering_fragment>",`${c}
260
+ #include <dithering_fragment>`)),r}generateUniformDeclarations(e){let t=[];for(let[i,r]of Object.entries(e)){let s=this.inferGLSLType(r.value);t.push(`uniform ${s} ${i};`)}return t.join(`
261
+ `)}inferGLSLType(e){return typeof e=="number"?"float":typeof e=="boolean"?"bool":e instanceof this.THREE.Vector2?"vec2":e instanceof this.THREE.Vector3?"vec3":e instanceof this.THREE.Vector4?"vec4":e instanceof this.THREE.Color?"vec3":e instanceof this.THREE.Matrix3?"mat3":e instanceof this.THREE.Matrix4?"mat4":e?.isTexture?"sampler2D":"float"}applyMaterialProperties(e,t){let i=t.properties;if(i){if(i.transparent!==void 0&&(e.transparent=i.transparent),i.side!==void 0)switch(i.side){case"front":e.side=this.THREE.FrontSide;break;case"back":e.side=this.THREE.BackSide;break;case"double":e.side=this.THREE.DoubleSide;break}if(i.depthWrite!==void 0&&(e.depthWrite=i.depthWrite),i.depthTest!==void 0&&(e.depthTest=i.depthTest),i.blending!==void 0)switch(i.blending){case"additive":e.blending=this.THREE.AdditiveBlending;break;case"subtractive":e.blending=this.THREE.SubtractiveBlending;break;case"multiply":e.blending=this.THREE.MultiplyBlending;break;default:e.blending=this.THREE.NormalBlending}i.wireframe!==void 0&&(e.wireframe=i.wireframe)}}updateUniforms(e,t,i){let r=e.userData?.shader,s=e.userData?.customUniforms;if(r?.uniforms)for(let[n,o]of Object.entries(i)){let a=t.uniforms?.[n];a&&r.uniforms[n]&&(r.uniforms[n].value=this.convertUniformValue(a.type,o))}else if(s)for(let[n,o]of Object.entries(i)){let a=t.uniforms?.[n];a&&s[n]&&(s[n].value=this.convertUniformValue(a.type,o))}if(e.uniforms)for(let[n,o]of Object.entries(i)){let a=t.uniforms?.[n];a&&e.uniforms[n]&&(e.uniforms[n].value=this.convertUniformValue(a.type,o))}}getDefaultVertexShader(){return`
262
+ varying vec2 vUv;
263
+ varying vec3 vNormal;
264
+ varying vec3 vPosition;
265
+
266
+ void main() {
267
+ vUv = uv;
268
+ vNormal = normalize(normalMatrix * normal);
269
+ vPosition = (modelMatrix * vec4(position, 1.0)).xyz;
270
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
271
+ }
272
+ `}getDefaultFragmentShader(){return`
273
+ varying vec2 vUv;
274
+ varying vec3 vNormal;
275
+ varying vec3 vPosition;
276
+
277
+ void main() {
278
+ gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
279
+ }
280
+ `}dispose(){this.textureCache.forEach(e=>e.dispose()),this.textureCache.clear()}};var Re=class{constructor(e,t={}){this.materialFactory=null;this.particleModelCache=new Map;this.particleModelPromiseCache=new Map;this.fontCache=new Map;this.fontPromiseCache=new Map;this.fontMetricsCache=new Map;this.THREE=e,this.loaders=t,this.materialFactory=new Le(e)}getMaterialFactory(){return this.materialFactory}createVector3(e=0,t=0,i=0){return new this.THREE.Vector3(e,t,i)}createVector2(e=0,t=0){return new this.THREE.Vector2(e,t)}createQuaternion(e=0,t=0,i=0,r=1){return new this.THREE.Quaternion(e,t,i,r)}createEuler(e=0,t=0,i=0,r="XYZ"){return new this.THREE.Euler(e,t,i,r)}createMatrix4(){return new this.THREE.Matrix4}createBox3(e,t){return new this.THREE.Box3(e,t)}createScene(){return new this.THREE.Scene}createRenderer(e){let t=new this.THREE.WebGLRenderer(e);return t.outputEncoding=this.THREE.sRGBEncoding,t}createPerspectiveCamera(e=45,t=1,i=.1,r=2e3){return new this.THREE.PerspectiveCamera(e,t,i,r)}createOrthographicCamera(e,t,i,r,s=.1,n=1e4){return new this.THREE.OrthographicCamera(e,t,i,r,s,n)}createGroup(){return new this.THREE.Group}createMesh(e,t){return new this.THREE.Mesh(e,t)}createBoxGeometry(e,t,i){return new this.THREE.BoxGeometry(e,t,i)}createSphereGeometry(e,t=32,i=32){return new this.THREE.SphereGeometry(e,t,i)}createPlaneGeometry(e,t){return new this.THREE.PlaneGeometry(e,t)}createCylinderGeometry(e,t,i,r=32){return new this.THREE.CylinderGeometry(e,t,i,r)}createMeshBasicMaterial(e){return new this.THREE.MeshBasicMaterial(e)}createMeshStandardMaterial(e){return new this.THREE.MeshStandardMaterial(e)}createShaderMaterial(e){return new this.THREE.ShaderMaterial(e)}createPointLight(e,t=1,i=0,r=2){return new this.THREE.PointLight(e,t,i,r)}createSpotLight(e,t=1,i=0,r=Math.PI/3,s=0,n=1){return new this.THREE.SpotLight(e,t,i,r,s,n)}createHemisphereLight(e,t,i=1){return new this.THREE.HemisphereLight(e,t,i)}createAmbientLight(e,t=1){return new this.THREE.AmbientLight(e,t)}createDirectionalLight(e,t=1){return new this.THREE.DirectionalLight(e,t)}createTextureLoader(){return new this.THREE.TextureLoader}createModelLoader(e){let t=this.loaders[e];if(!t)throw new Error(`[ThreeJSEngine] Model loader "${e}" not registered`);return new t}createRenderTarget(e,t,i={}){let r={minFilter:this.THREE.LinearFilter,magFilter:this.THREE.LinearFilter,format:this.THREE.RGBAFormat,depthBuffer:!0,stencilBuffer:!1};return new this.THREE.WebGLRenderTarget(e,t,{...r,...i})}loadFont(e){let t=e.trim();if(!t||t==="none")return Promise.resolve(null);if(this.fontCache.has(t))return Promise.resolve(this.fontCache.get(t));let i=this.fontPromiseCache.get(t);if(i)return i;let r=ge.isFontFile(t),s;return r?s=this.loadFontWithConverter(t):s=this.loadFontWithLoader(t),this.fontPromiseCache.set(t,s),s}async loadFontWithConverter(e){try{let t=await ge.load(e),i=this.createFontFromData(t);return this.fontCache.set(e,i),i}catch{return null}}loadFontWithLoader(e){let t=this.loaders.font||this.loaders.FontLoader;if(!t)return Promise.resolve(null);let i=new t;return new Promise(r=>{i.load(e,s=>{this.fontCache.set(e,s),r(s)},void 0,()=>{r(null)})})}createFontFromData(e){return{data:e,generateShapes:(i,r)=>this.generateShapesFromFontData(e,i,r,!1),generateNormalizedShapes:(i,r)=>this.generateShapesFromFontData(e,i,r,!0)}}generateShapesFromFontData(e,t,i,r=!1){let s=[],n=i/e.resolution,o=t[0];if(!o)return s;let a=e.glyphs[o];if(!a||!a.o)return s;let l=0;r&&(l=-this.getOutlineXMin(a.o)*n);let c=this.parseOutlineToShapes(a.o,n,l);return s.push(...c),s}getOutlineXMin(e){let t=e.split(" "),i=1/0,r=0;for(;r<t.length;)switch(t[r]){case"m":case"l":i=Math.min(i,parseFloat(t[r+1])||0),r+=3;break;case"q":i=Math.min(i,parseFloat(t[r+1])||0),i=Math.min(i,parseFloat(t[r+3])||0),r+=5;break;case"b":i=Math.min(i,parseFloat(t[r+1])||0),i=Math.min(i,parseFloat(t[r+3])||0),i=Math.min(i,parseFloat(t[r+5])||0),r+=7;break;default:r++;break}return i===1/0?0:i}getOutlineXMax(e){let t=e.split(" "),i=-1/0,r=0;for(;r<t.length;)switch(t[r]){case"m":case"l":i=Math.max(i,parseFloat(t[r+1])||0),r+=3;break;case"q":i=Math.max(i,parseFloat(t[r+1])||0),i=Math.max(i,parseFloat(t[r+3])||0),r+=5;break;case"b":i=Math.max(i,parseFloat(t[r+1])||0),i=Math.max(i,parseFloat(t[r+3])||0),i=Math.max(i,parseFloat(t[r+5])||0),r+=7;break;default:r++;break}return i===-1/0?0:i}parseOutlineToShapes(e,t,i=0){if(!e)return[];let r=new this.THREE.ShapePath,s=e.split(" "),n=0;for(;n<s.length;)switch(s[n]){case"m":{let l=parseFloat(s[n+1])*t+i,c=-parseFloat(s[n+2])*t;r.moveTo(l,c),n+=3}break;case"l":{let l=parseFloat(s[n+1])*t+i,c=-parseFloat(s[n+2])*t;r.lineTo(l,c),n+=3}break;case"q":{let l=parseFloat(s[n+3])*t+i,c=-parseFloat(s[n+4])*t;r.quadraticCurveTo(parseFloat(s[n+1])*t+i,-parseFloat(s[n+2])*t,l,c),n+=5}break;case"b":{let l=parseFloat(s[n+5])*t+i,c=-parseFloat(s[n+6])*t;r.bezierCurveTo(parseFloat(s[n+1])*t+i,-parseFloat(s[n+2])*t,parseFloat(s[n+3])*t+i,-parseFloat(s[n+4])*t,l,c),n+=7}break;case"z":typeof r.closePath=="function"?r.closePath():r.currentPath&&typeof r.currentPath.closePath=="function"&&r.currentPath.closePath(),n+=1;break;default:n++;break}return r.toShapes(!1)}reversePath(e){let t=new this.THREE.Path;if(!e.curves||e.curves.length===0)return t;let i=e.curves[e.curves.length-1],r=i.v2||i.v3||(i.getPoint?i.getPoint(1):null);r&&t.moveTo(r.x,r.y);for(let s=e.curves.length-1;s>=0;s--){let n=e.curves[s];n.isLineCurve||n.type==="LineCurve"||n.type==="LineCurve3"?t.lineTo(n.v1.x,n.v1.y):n.isQuadraticBezierCurve||n.type==="QuadraticBezierCurve"||n.type==="QuadraticBezierCurve3"?t.quadraticCurveTo(n.v1.x,n.v1.y,n.v0.x,n.v0.y):(n.isCubicBezierCurve||n.type==="CubicBezierCurve"||n.type==="CubicBezierCurve3")&&t.bezierCurveTo(n.v2.x,n.v2.y,n.v1.x,n.v1.y,n.v0.x,n.v0.y)}return t}createTextGeometry(e,t,i){if(!e||!t)return null;let r=Math.max(.001,i.size||16),s=Math.max(0,i.height||0),n=Math.max(.001,i.lineHeight||r*1.2),o=Number.isFinite(i.letterSpacing)?i.letterSpacing:0,a=i.align||"left",l=!!i.bevelEnabled,c=Math.max(0,i.bevelThickness||0),u=Math.max(0,i.bevelSize||0),h=i.bevelOffset||0,d=Math.max(0,i.bevelSegments||0),m=Math.max(1,Math.round(i.curveSegments||8)),g=String(e).split(/\r?\n/),f=[],S=t?.data,y=S?.resolution||1e3,b=S?.ascender||800,v=S?.descender||-200,E=r/y,I=b*E;if(i.layout&&i.layout.length>0?i.layout.forEach(k=>{let D=t.generateShapes(k.char,r),M=k.x,C=-k.y;D.forEach(j=>{let N=this.translateShape(j,M,C);k.scale&&k.scale!==1&&(N=this.scaleShape(N,k.scale)),f.push(N)})}):g.forEach((k,D)=>{let{shapes:M,width:C}=this.buildLineShapes(k,t,r,o),j=0;a==="center"?j=-C*.5:a==="right"&&(j=-C);let N=-D*n;M.forEach(V=>{f.push(this.translateShape(V,j,N))})}),!f.length)return null;let F=new this.THREE.ExtrudeGeometry(f,{depth:s,curveSegments:m,bevelEnabled:l,bevelThickness:c,bevelSize:u,bevelOffset:h,bevelSegments:d});return F.computeBoundingBox(),F}buildLineShapes(e,t,i,r){let s=[],n=0,o=Array.from(e);return o.forEach((a,l)=>{t.generateShapes(a,i).forEach(h=>{let d=this.translateShape(h,n,0);s.push(d)});let u=this.getGlyphAdvance(t,a,i);n+=u,r!==0&&l<o.length-1&&(n+=r)}),{shapes:s,width:n}}getGlyphAdvance(e,t,i){let r=e?.data,s=r?.glyphs||{},o=(s[t]||s[t.charCodeAt(0)]||s["?"])?.ha??r?.ha,a=r?.resolution||1e3;return typeof o=="number"?o/a*i:i*.5}translateShape(e,t,i){if(!e||!t&&!i)return e;if(typeof e.translate=="function")return e.translate(t,i),e;if(typeof e.applyMatrix4=="function"){let r=new this.THREE.Matrix4().makeTranslation(t,i,0);return e.applyMatrix4(r),e}if(typeof e.extractPoints=="function"){let{shape:r,holes:s}=e.extractPoints(12),n=a=>new this.THREE.Vector2((a.x||0)+t,(a.y||0)+i),o=new this.THREE.Shape(r.map(n));return Array.isArray(s)&&s.forEach(a=>{let l=new this.THREE.Path;l.setFromPoints(a.map(n)),o.holes.push(l)}),o}return e}scaleShape(e,t){if(t===1)return e;if(typeof e.scale=="function")return e.scale(t,t),e;if(typeof e.applyMatrix4=="function"){let i=new this.THREE.Matrix4().makeScale(t,t,1);return e.applyMatrix4(i),e}if(typeof e.extractPoints=="function"){let{shape:i,holes:r}=e.extractPoints(12),s=o=>new this.THREE.Vector2((o.x||0)*t,(o.y||0)*t),n=new this.THREE.Shape(i.map(s));return Array.isArray(r)&&r.forEach(o=>{let a=new this.THREE.Path;a.setFromPoints(o.map(s)),n.holes.push(a)}),n}return e}resolveParticleModelGeometry(e,t,i){let r=e.trim();if(!r||r==="none")return Promise.resolve(null);let s=t&&t!=="none"?t:this.loaders.gltf?"gltf":Object.keys(this.loaders)[0];if(!s)return Promise.resolve(null);let n=(i||"").trim(),o=`${s}|${r}|${n}`;if(this.particleModelCache.has(o))return Promise.resolve(this.particleModelCache.get(o));let a=this.particleModelPromiseCache.get(o);if(a)return a;let l=new Promise(c=>{let u=null;try{u=this.createModelLoader(s)}catch{c(null);return}u.load(r,h=>{let d=h?.scene||h?.object||h;if(!d){c(null);return}let m=null;if(n){if(d.getObjectByName){let f=d.getObjectByName(n);f?.isMesh&&(m=f)}!m&&d.traverse&&d.traverse(f=>{m||f?.isMesh&&f?.name===n&&(m=f)})}m||(d.isMesh?m=d:d.traverse&&d.traverse(f=>{!m&&f?.isMesh&&(m=f)}));let g=m?.geometry||null;if(!g){c(null);return}this.particleModelCache.set(o,g),c(g)},void 0,()=>{c(null)})});return this.particleModelPromiseCache.set(o,l),l}createParticleSystem(e){let t=this.THREE,i=this,r=n=>{let o=Math.max(1,n|0);return()=>(o^=o<<13,o^=o>>17,o^=o<<5,(o>>>0)%1e5/1e5)};class s extends t.Object3D{constructor(a){super();this.rng=r(e.seed);this.points=null;this.instanced=null;this.positions=new Float32Array(0);this.velocities=new Float32Array(0);this.life=new Float32Array(0);this.colors=new Float32Array(0);this.sizeFactors=new Float32Array(0);this.alive=0;this.emitRemainder=0;this.pendingBurst=0;this.basePositions=new Float32Array(0);this.baseScales=new Float32Array(0);this.baseJitter=new Float32Array(0);this.basePhase=new Float32Array(0);this.elapsed=0;this.modelGeometry=null;this.modelKey="";this.instancedUsesSharedGeometry=!1;this.distributionGeometry=null;this.distributionKey="";this.materialOverride=null;this.materialOverrideForPoints=null;this.defaultEmitterMaterial=null;this.defaultInstancedMaterial=null;this.transitionStartTime=0;this.transitionDuration=0;this.isTransitioning=!1;this.transitionFromPositions=new Float32Array(0);this.transitionToPositions=new Float32Array(0);this.pendingTransition=!1;this.pendingTransitionKey="";this.pendingDistributionLoad=!1;this.cfg={...a},this.refreshModelGeometry(),this.rebuild()}setConfig(a){let l=this.cfg;this.cfg={...a};let c=this.cfg.mode==="emitter"&&(l.emitRate!==this.cfg.emitRate||l.emitBurst!==this.cfg.emitBurst||l.particleLife!==this.cfg.particleLife||l.particleSpeed!==this.cfg.particleSpeed||!this.isVec3Equal(l.particleDirection,this.cfg.particleDirection)||!this.isVec3Equal(l.particleGravity,this.cfg.particleGravity)||l.particleDrag!==this.cfg.particleDrag||l.particleSizeVariation!==this.cfg.particleSizeVariation||l.particleColorVariation!==this.cfg.particleColorVariation||l.color!==this.cfg.color);if(l.mode!==this.cfg.mode||l.count!==this.cfg.count||l.seed!==this.cfg.seed||l.spread!==this.cfg.spread||l.particleShape!==this.cfg.particleShape||l.particleModelUrl!==this.cfg.particleModelUrl||l.particleModelLoader!==this.cfg.particleModelLoader||l.particleModelNode!==this.cfg.particleModelNode||l.instanceShape!==this.cfg.instanceShape||l.instanceModelUrl!==this.cfg.instanceModelUrl||l.instanceModelLoader!==this.cfg.instanceModelLoader||l.instanceModelNode!==this.cfg.instanceModelNode||l.instanceScale!==this.cfg.instanceScale||l.instanceScaleVariation!==this.cfg.instanceScaleVariation){let h=this.cfg.mode==="instanced"&&this.instanced&&this.cfg.modelTransitionDuration>0&&(l.particleModelUrl!==this.cfg.particleModelUrl||l.particleModelLoader!==this.cfg.particleModelLoader||l.particleModelNode!==this.cfg.particleModelNode||l.particleShape!==this.cfg.particleShape),d=this.cfg.mode==="instanced"&&this.instanced&&this.cfg.modelTransitionDuration>0&&(l.instanceModelUrl!==this.cfg.instanceModelUrl||l.instanceModelLoader!==this.cfg.instanceModelLoader||l.instanceModelNode!==this.cfg.instanceModelNode||l.instanceShape!==this.cfg.instanceShape);h||d?this.startModelTransition():(this.refreshModelGeometry(),this.refreshDistributionGeometry(),this.rebuild());return}if(c&&this.resetEmitter(),this.points){let h=this.points.material.uniforms;h&&(h.uOpacity&&(h.uOpacity.value=this.cfg.opacity),h.uSize&&(h.uSize.value=this.cfg.size),h.uSizeVar&&(h.uSizeVar.value=this.cfg.particleSizeVariation),h.uPointSize&&(h.uPointSize.value=this.cfg.size))}this.instanced&&(this.instanced.material.opacity=this.cfg.opacity,this.instanced.material.color=new t.Color(this.cfg.color)),this.pendingBurst=this.cfg.emitBurst}startModelTransition(){this.transitionFromPositions=new Float32Array(this.basePositions),this.transitionDuration=this.cfg.modelTransitionDuration;let a=this.cfg.instanceModelUrl?.trim(),l=`${this.cfg.instanceModelLoader}|${a}|${this.cfg.instanceModelNode}`;this.pendingTransition=!0,this.pendingTransitionKey=l,this.refreshModelGeometry(),this.refreshDistributionGeometryForTransition()}refreshDistributionGeometryForTransition(){if(this.cfg.instanceShape!=="model"){this.startMorphTransition();return}let a=this.cfg.instanceModelUrl?.trim();if(!a||a==="none"){this.startMorphTransition();return}let l=`${this.cfg.instanceModelLoader}|${a}|${this.cfg.instanceModelNode}`;if(this.distributionKey===l&&this.distributionGeometry){this.startMorphTransition();return}this.distributionKey=l,i.resolveParticleModelGeometry(a,this.cfg.instanceModelLoader,this.cfg.instanceModelNode).then(c=>{c&&this.distributionKey===l&&(!this.pendingTransition||this.pendingTransitionKey!==l||(this.distributionGeometry=c,this.startMorphTransition()))})}startMorphTransition(){this.pendingTransition=!1,this.pendingTransitionKey="";let a=Math.max(1,this.cfg.count);if(this.transitionToPositions=new Float32Array(a*3),this.cfg.instanceShape==="model"&&this.distributionGeometry)this.fillFromModelToArray(a,this.distributionGeometry,this.transitionToPositions);else for(let c=0;c<a;c+=1){let u=this.cfg.instanceShape==="box"?this.randomInBox(this.cfg.spread):this.randomInSphere(this.cfg.spread);this.transitionToPositions.set(u,c*3)}this.transitionStartTime=this.elapsed,this.isTransitioning=!0}cleanupOutgoing(){this.isTransitioning=!1,this.pendingTransition=!1,this.pendingTransitionKey="",this.transitionFromPositions=new Float32Array(0),this.transitionToPositions=new Float32Array(0)}updateTransition(){if(!this.isTransitioning)return;let a=this.elapsed-this.transitionStartTime,l=Math.min(1,a/this.transitionDuration),c=l<.5?2*l*l:1-Math.pow(-2*l+2,2)/2,u=Math.min(this.transitionFromPositions.length/3,this.transitionToPositions.length/3,this.basePositions.length/3);for(let h=0;h<u;h+=1){let d=h*3;this.basePositions[d]=this.transitionFromPositions[d]+(this.transitionToPositions[d]-this.transitionFromPositions[d])*c,this.basePositions[d+1]=this.transitionFromPositions[d+1]+(this.transitionToPositions[d+1]-this.transitionFromPositions[d+1])*c,this.basePositions[d+2]=this.transitionFromPositions[d+2]+(this.transitionToPositions[d+2]-this.transitionFromPositions[d+2])*c}if(l>=1){for(let h=0;h<u*3;h+=1)this.basePositions[h]=this.transitionToPositions[h];this.cleanupOutgoing()}}fillFromModelToArray(a,l,c){let u=l?.attributes?.position;if(!u?.array||u.itemSize<3){for(let x=0;x<a;x+=1){let O=this.randomInSphere(this.cfg.spread);c.set(O,x*3)}return}let h=u.array,d=u.itemSize,m=Math.floor(h.length/d);if(m<=0)return;let g=l?.index?.array,f=Math.floor(g?g.length/3:m/3);if(f<=0)return;let S=1/0,y=1/0,b=1/0,v=-1/0,E=-1/0,I=-1/0;for(let x=0;x<m;x+=1){let O=x*d,P=h[O],A=h[O+1],L=h[O+2];S=Math.min(S,P),y=Math.min(y,A),b=Math.min(b,L),v=Math.max(v,P),E=Math.max(E,A),I=Math.max(I,L)}let F=Math.max(1e-6,v-S),k=Math.max(1e-6,E-y),D=Math.max(1e-6,I-b),M=(this.cfg.spreadX>0?this.cfg.spreadX:this.cfg.spread)*2,C=(this.cfg.spreadY>0?this.cfg.spreadY:this.cfg.spread)*2,j=M>0?M/F:1,N=C>0?C/k:1,V=Math.min(j,N),_=(S+v)*.5,W=(y+E)*.5,H=(b+I)*.5,z=new Float32Array(f),w=0;for(let x=0;x<f;x+=1){let O=x*3,P=g?g[O]:O,A=g?g[O+1]:O+1,L=g?g[O+2]:O+2,q=P*d,Z=A*d,Y=L*d,K=h[q],X=h[q+1],ae=h[q+2],oe=h[Z],fe=h[Z+1],ye=h[Z+2],be=h[Y],$=h[Y+1],G=h[Y+2],te=oe-K,Q=fe-X,le=ye-ae,de=be-K,ce=$-X,ie=G-ae,re=Q*ie-le*ce,se=le*de-te*ie,pe=te*ce-Q*de,Ie=Math.sqrt(re*re+se*se+pe*pe)*.5;w+=Ie,z[x]=w}if(w<=0){for(let x=0;x<a;x+=1){let O=this.randomInSphere(this.cfg.spread);c.set(O,x*3)}return}for(let x=0;x<a;x+=1){let O=this.rng()*w,P=0,A=f-1;for(;P<A;){let Xe=Math.floor((P+A)/2);O<=z[Xe]?A=Xe:P=Xe+1}let L=P*3,q=g?g[L]:L,Z=g?g[L+1]:L+1,Y=g?g[L+2]:L+2,K=q*d,X=Z*d,ae=Y*d,oe=h[K],fe=h[K+1],ye=h[K+2],be=h[X],$=h[X+1],G=h[X+2],te=h[ae],Q=h[ae+1],le=h[ae+2],de=this.rng(),ce=this.rng(),ie=Math.sqrt(de),re=1-ie,se=ie*(1-ce),pe=ie*ce,Ie=(oe*re+be*se+te*pe-_)*V,Ye=(fe*re+$*se+Q*pe-W)*V,Oe=(ye*re+G*se+le*pe-H)*V;c[x*3]=Ie,c[x*3+1]=Ye,c[x*3+2]=Oe}}update(a){a<=0||(this.elapsed+=a,this.updateTransition(),this.cfg.mode==="emitter"?this.updateEmitter(a):this.updateInstanced(this.elapsed))}dispose(){this.cleanupOutgoing(),this.points&&(this.points.geometry.dispose(),this.points.material.dispose()),this.instanced&&(this.instancedUsesSharedGeometry||this.instanced.geometry.dispose(),this.instanced.material.dispose())}rebuild(){if(this.points&&(this.remove(this.points),this.points.geometry.dispose(),this.points.material.dispose(),this.points=null),this.instanced&&(this.remove(this.instanced),this.instancedUsesSharedGeometry||this.instanced.geometry.dispose(),this.instanced.material.dispose(),this.instanced=null),this.elapsed=0,this.cfg.mode==="emitter")this.buildEmitter();else{let a=this.cfg.instanceShape==="model",l=this.distributionGeometry!==null;if(a&&!l){this.pendingDistributionLoad=!0,this.refreshDistributionGeometry();return}this.pendingDistributionLoad=!1,this.refreshDistributionGeometry(),this.buildInstanced()}this.applyMaterialOverrides()}buildEmitter(){let a=Math.max(1,this.cfg.count);this.positions=new Float32Array(a*3),this.velocities=new Float32Array(a*3),this.life=new Float32Array(a),this.colors=new Float32Array(a*3),this.sizeFactors=new Float32Array(a);let l=1e6;for(let h=0;h<a;h+=1){let d=h*3;this.positions[d]=l,this.positions[d+1]=l,this.positions[d+2]=l}this.alive=0,this.emitRemainder=0,this.pendingBurst=this.cfg.emitBurst;let c=new t.BufferGeometry;c.setAttribute("position",new t.BufferAttribute(this.positions,3)),c.setAttribute("color",new t.BufferAttribute(this.colors,3)),c.setAttribute("sizeFactor",new t.BufferAttribute(this.sizeFactors,1));let u=new t.ShaderMaterial({transparent:this.cfg.opacity<1,depthWrite:!1,uniforms:{uOpacity:{value:this.cfg.opacity},uSize:{value:this.cfg.size},uSizeVar:{value:this.cfg.particleSizeVariation}},vertexShader:`
281
+ attribute vec3 color;
282
+ attribute float sizeFactor;
283
+ varying vec3 vColor;
284
+ uniform float uSize;
285
+ uniform float uSizeVar;
286
+ void main() {
287
+ vColor = color;
288
+ float size = uSize * mix(1.0 - uSizeVar, 1.0, sizeFactor);
289
+ gl_PointSize = size;
290
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
291
+ }
292
+ `,fragmentShader:`
293
+ varying vec3 vColor;
294
+ uniform float uOpacity;
295
+ void main() {
296
+ float dist = length(gl_PointCoord - vec2(0.5));
297
+ if (dist > 0.5) discard;
298
+ gl_FragColor = vec4(vColor, uOpacity);
299
+ }
300
+ `});this.points=new t.Points(c,u),this.defaultEmitterMaterial=u,this.add(this.points)}buildInstanced(){let a=Math.max(1,this.cfg.count),l=this.cfg.particleShape==="model"&&this.modelGeometry,c=this.cfg.particleShape==="model"&&this.modelGeometry?this.modelGeometry:this.cfg.particleShape==="box"?new t.BoxGeometry(1,1,1):new t.SphereGeometry(.5,8,8);this.instancedUsesSharedGeometry=l;let u=new t.MeshStandardMaterial({color:new t.Color(this.cfg.color),transparent:this.cfg.opacity<1,opacity:this.cfg.opacity});this.defaultInstancedMaterial=u,this.instanced=new t.InstancedMesh(c,u,a),this.basePositions=new Float32Array(a*3),this.baseScales=new Float32Array(a),this.baseJitter=new Float32Array(a*3),this.basePhase=new Float32Array(a),this.fillBasePositions(a),this.applyInstancedTransforms(0),this.add(this.instanced)}setMaterial(a,l={}){let c=l.points??!0;(l.meshes??!0)&&(this.materialOverride=a),c&&(this.materialOverrideForPoints=a),this.applyMaterialOverrides()}updateEmitter(a){let l=this.cfg.count,c=this.normalize(this.cfg.particleDirection),u=this.cfg.particleGravity,h=Math.max(0,Math.min(1,this.cfg.particleDrag)),m=this.cfg.emitRate*a+this.emitRemainder,g=Math.floor(m);this.emitRemainder=m-g;let f=!1,S=1e6;for(let y=0;y<g;y+=1)this.spawnParticle(c);for(;this.pendingBurst>0;)this.spawnParticle(c),this.pendingBurst-=1;for(let y=0;y<l;y+=1){if(this.life[y]<=0)continue;if(this.life[y]-=a,this.life[y]<=0){this.life[y]=0;let v=y*3;this.positions[v]=S,this.positions[v+1]=S,this.positions[v+2]=S,this.colors[v]=0,this.colors[v+1]=0,this.colors[v+2]=0,f=!0;continue}let b=y*3;this.velocities[b]+=u[0]*a,this.velocities[b+1]+=u[1]*a,this.velocities[b+2]+=u[2]*a,this.velocities[b]*=1-h*a,this.velocities[b+1]*=1-h*a,this.velocities[b+2]*=1-h*a,this.positions[b]+=this.velocities[b]*a,this.positions[b+1]+=this.velocities[b+1]*a,this.positions[b+2]+=this.velocities[b+2]*a}this.points&&(this.points.geometry.attributes.position.needsUpdate=!0,f&&(this.points.geometry.attributes.color.needsUpdate=!0))}spawnParticle(a){let l=this.cfg.count,c=-1;for(let f=0;f<l;f+=1)if(this.life[f]<=0){c=f;break}if(c===-1)return;let u=this.randomInSphere(this.cfg.spread),h=this.cfg.particleSpeed*(1-this.cfg.particleSizeVariation+this.rng()*this.cfg.particleSizeVariation),d=[a[0]*h+(this.rng()-.5)*h*.2,a[1]*h+(this.rng()-.5)*h*.2,a[2]*h+(this.rng()-.5)*h*.2],m=c*3;this.positions.set(u,m),this.velocities.set(d,m),this.life[c]=this.cfg.particleLife,this.sizeFactors[c]=this.rng();let g=new t.Color(this.cfg.color);this.cfg.particleColorVariation>0&&g.offsetHSL((this.rng()-.5)*this.cfg.particleColorVariation,0,0),this.colors[m]=g.r,this.colors[m+1]=g.g,this.colors[m+2]=g.b,this.points&&(this.points.geometry.attributes.color.needsUpdate=!0,this.points.geometry.attributes.sizeFactor.needsUpdate=!0)}updateInstanced(a){this.applyInstancedTransforms(a),this.instanced&&(this.instanced.instanceMatrix.needsUpdate=!0)}applyInstancedTransforms(a){if(!this.instanced)return;let l=this.cfg.count,c=this.cfg.instanceJitter,u=this.cfg.instanceFlow,h=Math.max(0,this.cfg.instanceDisperse),d=Math.max(0,this.cfg.instanceDisperseScatter),m=this.cfg.instanceDisperseScatterX>0?this.cfg.instanceDisperseScatterX:d,g=this.cfg.instanceDisperseScatterY>0?this.cfg.instanceDisperseScatterY:d,f=this.cfg.instanceDisperseScatterZ>0?this.cfg.instanceDisperseScatterZ:d,S=this.cfg.instanceRotationSpeed,y=new t.Object3D;for(let b=0;b<l;b+=1){let v=b*3,E=this.basePositions[v],I=this.basePositions[v+1],F=this.basePositions[v+2],k=this.basePhase[b],D=Math.sin((I+a*1.4)*.7+k)*u*this.cfg.spread,M=Math.cos((E-a*1.1)*.6+k)*u*this.cfg.spread,C=Math.sin((F+a*1.2)*.8+k)*u*this.cfg.spread,j=Math.sin(a*2.1+k+this.baseJitter[v]*2.5)*c,N=Math.cos(a*1.7+k+this.baseJitter[v+1]*2.5)*c,V=Math.sin(a*1.9+k+this.baseJitter[v+2]*2.5)*c,_=1+h,W=this.baseJitter[v],H=this.baseJitter[v+1],z=this.baseJitter[v+2],w=Math.sqrt(W*W+H*H+z*z)||1,x=h*this.cfg.spread,O=W/w*m*x,P=H/w*g*x,A=z/w*f*x;y.position.set(E*_+O+D+j,I*_+P+M+N,F*_+A+C+V),y.rotation.set(this.baseJitter[v]*.5,a*S+b*.1,this.baseJitter[v+2]*.5);let L=this.baseScales[b]*this.cfg.size;y.scale.set(L,L,L),y.updateMatrix(),this.instanced.setMatrixAt(b,y.matrix)}}applyMaterialOverrides(){if(this.points){let a=this.materialOverrideForPoints||this.defaultEmitterMaterial;a&&this.points.material!==a&&(this.points.material=a,this.ensurePointMaterial(a))}if(this.instanced){let a=this.materialOverride||this.defaultInstancedMaterial;a&&this.instanced.material!==a&&(this.instanced.material=a)}}ensurePointMaterial(a){a?.isShaderMaterial&&(a.uniforms||(a.uniforms={}),a.uniforms.uPointSize||(a.uniforms.uPointSize={value:this.cfg.size}),a.uniforms.uOpacity||(a.uniforms.uOpacity={value:this.cfg.opacity}),a.vertexShader.includes("gl_PointSize")||(a.vertexShader.includes("uPointSize")||(a.vertexShader=`uniform float uPointSize;
301
+ ${a.vertexShader}`),a.vertexShader=a.vertexShader.replace(/void\\s+main\\s*\\(\\)\\s*\\{/,"void main() {\\n gl_PointSize = uPointSize;"),a.needsUpdate=!0))}refreshModelGeometry(){if(this.cfg.particleShape!=="model"){this.modelGeometry=null,this.modelKey="";return}let a=this.cfg.particleModelUrl?.trim();if(!a||a==="none"){this.modelGeometry=null,this.modelKey="";return}let l=`${this.cfg.particleModelLoader}|${a}|${this.cfg.particleModelNode}`;this.modelKey===l&&this.modelGeometry||(this.modelKey=l,i.resolveParticleModelGeometry(a,this.cfg.particleModelLoader,this.cfg.particleModelNode).then(c=>{c&&this.modelKey===l&&(this.modelGeometry=c,this.cfg.mode==="instanced"&&this.cfg.particleShape==="model"&&this.rebuild())}))}refreshDistributionGeometry(){if(this.cfg.instanceShape!=="model"){this.distributionGeometry=null,this.distributionKey="";return}let a=this.cfg.instanceModelUrl?.trim();if(!a||a==="none"){this.distributionGeometry=null,this.distributionKey="";return}let l=`${this.cfg.instanceModelLoader}|${a}|${this.cfg.instanceModelNode}`;this.distributionKey===l&&this.distributionGeometry||(this.distributionKey=l,i.resolveParticleModelGeometry(a,this.cfg.instanceModelLoader,this.cfg.instanceModelNode).then(c=>{c&&this.distributionKey===l&&(this.distributionGeometry=c,this.cfg.mode==="instanced"&&this.cfg.instanceShape==="model"&&(this.pendingDistributionLoad?(this.pendingDistributionLoad=!1,this.buildInstanced(),this.applyMaterialOverrides()):this.rebuild()))}))}fillBasePositions(a){if(this.cfg.instanceShape==="model"&&this.distributionGeometry)this.fillFromModel(a,this.distributionGeometry);else for(let c=0;c<a;c+=1){let u=this.cfg.instanceShape==="box"?this.randomInBox(this.cfg.spread):this.randomInSphere(this.cfg.spread);this.basePositions.set(u,c*3)}for(let c=0;c<a;c+=1){let u=c*3;this.baseJitter[u]=this.rng()*2-1,this.baseJitter[u+1]=this.rng()*2-1,this.baseJitter[u+2]=this.rng()*2-1,this.basePhase[c]=this.rng()*Math.PI*2;let h=this.cfg.instanceScale*(1-this.cfg.instanceScaleVariation+this.rng()*this.cfg.instanceScaleVariation);this.baseScales[c]=h}}fillFromModel(a,l){let c=l?.attributes?.position;if(!c?.array||c.itemSize<3){for(let w=0;w<a;w+=1){let x=this.randomInSphere(this.cfg.spread);this.basePositions.set(x,w*3)}return}let u=c.array,h=c.itemSize,d=Math.floor(u.length/h);if(d<=0)return;let m=l?.index?.array,g=Math.floor(m?m.length/3:d/3);if(g<=0)return;let f=1/0,S=1/0,y=1/0,b=-1/0,v=-1/0,E=-1/0;for(let w=0;w<d;w+=1){let x=w*h,O=u[x],P=u[x+1],A=u[x+2];f=Math.min(f,O),S=Math.min(S,P),y=Math.min(y,A),b=Math.max(b,O),v=Math.max(v,P),E=Math.max(E,A)}let I=Math.max(1e-6,b-f),F=Math.max(1e-6,v-S),k=Math.max(1e-6,E-y),D=(this.cfg.spreadX>0?this.cfg.spreadX:this.cfg.spread)*2,M=(this.cfg.spreadY>0?this.cfg.spreadY:this.cfg.spread)*2,C=D>0?D/I:1,j=M>0?M/F:1,N=Math.min(C,j),V=(f+b)*.5,_=(S+v)*.5,W=(y+E)*.5,H=new Float32Array(g),z=0;for(let w=0;w<g;w+=1){let x=w*3,O=m?m[x]:x,P=m?m[x+1]:x+1,A=m?m[x+2]:x+2,L=O*h,q=P*h,Z=A*h,Y=u[L],K=u[L+1],X=u[L+2],ae=u[q],oe=u[q+1],fe=u[q+2],ye=u[Z],be=u[Z+1],$=u[Z+2],G=ae-Y,te=oe-K,Q=fe-X,le=ye-Y,de=be-K,ce=$-X,ie=te*ce-Q*de,re=Q*le-G*ce,se=G*de-te*le,pe=Math.sqrt(ie*ie+re*re+se*se)*.5;z+=pe,H[w]=z}if(z<=0){for(let w=0;w<a;w+=1){let x=this.randomInSphere(this.cfg.spread);this.basePositions.set(x,w*3)}return}for(let w=0;w<a;w+=1){let x=this.rng()*z,O=0,P=g-1;for(;O<P;){let Oe=Math.floor((O+P)/2);x<=H[Oe]?P=Oe:O=Oe+1}let A=O*3,L=m?m[A]:A,q=m?m[A+1]:A+1,Z=m?m[A+2]:A+2,Y=L*h,K=q*h,X=Z*h,ae=u[Y],oe=u[Y+1],fe=u[Y+2],ye=u[K],be=u[K+1],$=u[K+2],G=u[X],te=u[X+1],Q=u[X+2],le=this.rng(),de=this.rng(),ce=Math.sqrt(le),ie=1-ce,re=ce*(1-de),se=ce*de,pe=(ae*ie+ye*re+G*se-V)*N,Ie=(oe*ie+be*re+te*se-_)*N,Ye=(fe*ie+$*re+Q*se-W)*N;this.basePositions[w*3]=pe,this.basePositions[w*3+1]=Ie,this.basePositions[w*3+2]=Ye}}resetEmitter(){if(!this.points)return;let a=1e6;for(let l=0;l<this.positions.length;l+=3)this.positions[l]=a,this.positions[l+1]=a,this.positions[l+2]=a;this.velocities.fill(0),this.life.fill(0),this.colors.fill(0),this.sizeFactors.fill(0),this.alive=0,this.emitRemainder=0,this.pendingBurst=this.cfg.emitBurst,this.points.geometry.attributes.position.needsUpdate=!0,this.points.geometry.attributes.color.needsUpdate=!0,this.points.geometry.attributes.sizeFactor.needsUpdate=!0}normalize(a){let l=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2])||1;return[a[0]/l,a[1]/l,a[2]/l]}isVec3Equal(a,l){return a[0]===l[0]&&a[1]===l[1]&&a[2]===l[2]}randomInSphere(a){let l=this.rng(),c=this.rng(),u=l*Math.PI*2,h=Math.acos(2*c-1),d=Math.cbrt(this.rng())*a;return[d*Math.sin(h)*Math.cos(u),d*Math.sin(h)*Math.sin(u),d*Math.cos(h)]}randomInBox(a){let l=a*.5;return[(this.rng()*2-1)*l,(this.rng()*2-1)*l,(this.rng()*2-1)*l]}}return new s(e)}simplifyGeometry(e,t){let i=this.THREE?.SimplifyModifier;if(!i)return null;let r=e,s=r?.attributes?.position?.count;if(!Number.isFinite(s))return null;let n=Math.max(.05,Math.min(1,t)),o=Math.max(3,Math.floor(s*n));if(o>=s)return e;try{return new i().modify(r,o)}catch{return null}}degToRad(e){return this.THREE.MathUtils.degToRad(e)}radToDeg(e){return this.THREE.MathUtils.radToDeg(e)}computeBoundingBoxRecursively(e){let t=new this.THREE.Box3,i=!1;return e.traverse&&e.traverse(r=>{if(r.visible&&r.geometry){typeof r.geometry.computeBoundingBox=="function"&&r.geometry.computeBoundingBox();let s=r.geometry.boundingBox;if(s){let n=s.clone().applyMatrix4(r.matrixWorld);t.union(n),i=!0}}}),i?t:new this.THREE.Box3}},qe=class{constructor(e,t={}){this.engine=new Re(e,t)}getEngine(){return this.engine}getName(){return"Three.js"}};return yt(Ft);})();
277
302
  //# sourceMappingURL=index.js.map