mirage-engine 0.3.14 → 0.3.15
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/mirage-engine.js +655 -596
- package/dist/mirage-engine.umd.js +44 -24
- package/package.json +3 -3
|
@@ -1,12 +1,17 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`),
|
|
1
|
+
(function(I,D){typeof exports=="object"&&typeof module!="undefined"?D(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],D):(I=typeof globalThis!="undefined"?globalThis:I||self,D(I.MirageEngine={},I.THREE))})(this,function(I,D){"use strict";var ht=Object.defineProperty,dt=Object.defineProperties;var ut=Object.getOwnPropertyDescriptors;var Fe=Object.getOwnPropertySymbols;var ft=Object.prototype.hasOwnProperty,gt=Object.prototype.propertyIsEnumerable;var Ce=(I,D,B)=>D in I?ht(I,D,{enumerable:!0,configurable:!0,writable:!0,value:B}):I[D]=B,ne=(I,D)=>{for(var B in D||(D={}))ft.call(D,B)&&Ce(I,B,D[B]);if(Fe)for(var B of Fe(D))gt.call(D,B)&&Ce(I,B,D[B]);return I},_e=(I,D)=>dt(I,ut(D));var u=(I,D,B)=>(Ce(I,typeof D!="symbol"?D+"":D,B),B);var ze=(I,D,B)=>new Promise((v,ue)=>{var Z=F=>{try{_(B.next(F))}catch(Y){ue(Y)}},pe=F=>{try{_(B.throw(F))}catch(Y){ue(Y)}},_=F=>F.done?v(F.value):Promise.resolve(F.value).then(Z,pe);_((B=B.apply(I,D)).next())});function B(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const v=B(D),ue={INCLUDE_TREE:"include-tree",EXCLUDE_TREE:"exclude-tree",INCLUDE_SELF:"include-self",EXCLUDE_SELF:"exclude-self",END:"end"},Z={NAME:"data-mirage-dom",KEY:"mirageDom",VALUES:{HIDE:"hide",SHOW:"show"}},pe={TRAVELER:"traveler",NATIVE:"native",CAPTURE_1:"1",CAPTURE_2:"2",CAPTURE_3:"3",CAPTURE_4:"4",CAPTURE_5:"5",CAPTURE_6:"6",CAPTURE_7:"7",CAPTURE_8:"8",CAPTURE_9:"9",CAPTURE_10:"10"},_={NAME:"data-mirage-travel",KEY:"mirageTravel",VALUES:pe,MAX_LAYERS:Object.keys(pe).length-1},F={NAME:"data-mirage-filter",KEY:"mirageFilter",VALUES:ue},Y={NAME:"data-mirage-select",KEY:"mirageSelect",VALUES:ue},Ne={NAME:"data-mirage-shader",KEY:"mirageShader"},Te={NAME:"data-mirage-sandwich",KEY:"mirageSandwich",VALUES:{FRONT:"front"}},me=0,se=1,fe=2,Xe=4,ve=8,we=16;function Ve(n){const e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return e?{r:parseInt(e[1])/255,g:parseInt(e[2])/255,b:parseInt(e[3])/255}:{r:1,g:1,b:1}}function Ye(n){const e={};if(n.opacity&&(e.opacity=parseFloat(n.opacity)),n.backgroundColor&&n.backgroundColor!=="rgba(0, 0, 0, 0)"){const t=Ve(n.backgroundColor);e.backgroundColor=[t.r,t.g,t.b]}if(n.backgroundImage?e.backgroundImage=n.backgroundImage:n.background&&(e.backgroundImage=n.background),n.borderRadius&&(e.borderRadius=parseFloat(n.borderRadius)),n.width&&(e.width=parseFloat(n.width)),n.height&&(e.height=parseFloat(n.height)),n.transform&&n.transform!=="none"){const t=new DOMMatrix(n.transform);e.x=t.m41,e.y=t.m42,e.z=t.m43}return e}class Re{constructor(e,t){u(this,"target");u(this,"observer");u(this,"pendingDeletions",new Set);u(this,"pendingStyles",new Map);u(this,"isDomDirty",!1);u(this,"isRunning",!1);u(this,"pendingMask",me);u(this,"mutationTimer",null);u(this,"cssTimer",null);u(this,"resizeConfig");u(this,"resizeTimer",null);u(this,"isResizing",!1);u(this,"lastScrollX",0);u(this,"lastScrollY",0);u(this,"scrollTimer",null);u(this,"onBeforeRender",new Set);u(this,"onLayoutChange",new Set);u(this,"onStyleChange",new Set);u(this,"onScrollChange",new Set);u(this,"onRender",new Set);u(this,"onTransitionFinished",e=>{this.target.contains(e.target)&&this.mutationTimer===null&&(this.cssTimer&&clearTimeout(this.cssTimer),this.pendingStyles.size==0&&(this.pendingMask|=se|fe,this.cssTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.cssTimer=null},50)))});u(this,"onWindowResize",()=>{if(!this.resizeConfig.enabled){this.isDomDirty=!0;return}this.isResizing||(this.isResizing=!0,this.resizeConfig.onStart&&this.resizeConfig.onStart()),this.resizeTimer&&clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.resizeConfig.onEnd&&this.resizeConfig.onEnd(),this.isResizing=!1,this.resizeTimer=null},this.resizeConfig.delay)});u(this,"renderLoop",()=>{if(!this.isRunning)return;this.onBeforeRender.forEach(r=>r()),this.isDomDirty&&(this.isDomDirty=!1,this.onLayoutChange.forEach(r=>r(this.pendingMask,this.pendingDeletions)),this.pendingDeletions.clear(),this.pendingMask=me);const e=window.scrollX,t=window.scrollY;(e!==this.lastScrollX||t!==this.lastScrollY)&&(this.onScrollChange.forEach(r=>r(e,t)),this.lastScrollX=e,this.lastScrollY=t,this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout(()=>{this.pendingMask|=se,this.isDomDirty=!0,this.scrollTimer=null},150)),this.pendingStyles.size>0&&(this.onStyleChange.forEach(r=>r(this.pendingStyles)),this.pendingStyles.clear()),this.onRender.forEach(r=>r()),requestAnimationFrame(this.renderLoop)});var i,l;this.target=e;const r=(i=t.resizeDebounce)!=null?i:!0;r===!1?this.resizeConfig={enabled:!1,delay:0}:r===!0?this.resizeConfig={enabled:!0,delay:150}:this.resizeConfig={enabled:!0,delay:(l=r.delay)!=null?l:150,onStart:r.onStart,onEnd:r.onEnd},this.observer=new MutationObserver(s=>{let o=me;for(const a of s)if(a.type==="childList")o|=ve,a.removedNodes.length>0&&a.removedNodes.forEach(c=>{c instanceof HTMLElement&&this.pendingDeletions.add(c)});else if(a.type==="attributes")if(a.attributeName==="style"){o|=se|fe;const c=a.target,d=Ye(c.style);this.pendingStyles.set(c,d)}else a.attributeName==="class"?o|=se|fe:a.attributeName&&a.attributeName.startsWith("data-")&&(o|=se|fe,a.attributeName.startsWith("data-mirage")&&(o|=ve));else a.type==="characterData"&&(o|=we|se);if(o!==me){if(this.pendingMask|=o,o&ve){this.clearTimers(),this.isDomDirty=!0;return}this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=window.setTimeout(()=>{this.mutationTimer=null,this.isDomDirty=!0},200)}})}start(){this.isRunning||(this.isRunning=!0,this.observer.observe(this.target,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),this.target.addEventListener("transitionend",this.onTransitionFinished),this.target.addEventListener("animationend",this.onTransitionFinished),window.addEventListener("resize",this.onWindowResize),this.isDomDirty=!0,this.lastScrollX=window.scrollX,this.lastScrollY=window.scrollY,this.renderLoop())}stop(){this.isRunning=!1,this.observer.disconnect(),this.clearTimers(),this.target.removeEventListener("transitionend",this.onTransitionFinished),this.target.removeEventListener("animationend",this.onTransitionFinished),window.removeEventListener("resize",this.onWindowResize)}clearTimers(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.cssTimer&&(clearTimeout(this.cssTimer),this.cssTimer=null),this.scrollTimer&&(clearTimeout(this.scrollTimer),this.scrollTimer=null)}}const j=1,oe=2,N={BASE:0,SELECTED:1,getCaptureLayer:n=>31-n,HIDDEN:31},Le=Object.values(F.VALUES);class Me{static getBaseline(e){if(this.cache.has(e))return this.cache.get(e);const t=this.calculateBaselineFromDOM(e);return this.cache.set(e,t),t}static calculateBaselineFromDOM(e){if(typeof document=="undefined")return 0;const t=document.createElement("div"),r=document.createElement("span"),i=document.createElement("img");t.style.visibility="hidden",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.font=e,t.style.margin="0",t.style.padding="0",t.style.border="none",r.style.margin="0",r.style.padding="0",r.style.border="none",r.style.lineHeight="normal",i.width=1,i.height=1,i.style.verticalAlign="baseline",r.appendChild(document.createTextNode("Hidden Text")),t.appendChild(r),t.appendChild(i),document.body.appendChild(t);const l=i.offsetTop-r.offsetTop;return document.body.removeChild(t),l}}u(Me,"cache",new Map);class Pe extends v.MeshBasicMaterial{constructor(t,r,i,l,s=2){super({transparent:!0,side:v.FrontSide,color:16777215});u(this,"canvas");u(this,"ctx");u(this,"qualityFactor");if(this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),!this.ctx)throw new Error("[Mirage] Failed to create canvas context");this.qualityFactor=s,this.map=new v.CanvasTexture(this.canvas),this.map.colorSpace=v.LinearSRGBColorSpace,this.map.minFilter=v.LinearFilter,this.map.magFilter=v.LinearFilter,this.updateText(t,r,i,l)}wrapText(t,r){const i=t.split(`
|
|
2
|
+
`),l=[];return i.forEach(s=>{const o=s.match(/[^\s\-]+\-?|\-|\s+/g)||[];if(o.length===0){l.push("");return}let a=o[0];for(let c=1;c<o.length;c++){const d=o[c];this.ctx.measureText(a+d).width<=r+2?a+=d:(a&&l.push(a),a=d.trimStart())}a&&l.push(a)}),l}updateText(t,r,i,l,s){s!==void 0&&(this.qualityFactor=s);const a=(window.devicePixelRatio||1)*this.qualityFactor,c=i*a,d=l*a;this.canvas.width!==c||this.canvas.height!==d?(this.canvas.width=c,this.canvas.height=d):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(a,0,0,a,0,0),this.ctx.font=r.font,this.ctx.fillStyle=r.color,this.ctx.textBaseline="alphabetic",this.ctx.globalAlpha=1;const h=this.wrapText(t,i),f=r.lineHeight,g=Me.getBaseline(r.font);h.forEach((p,y)=>{const w=y*f+g;let C=0;r.textAlign==="center"?C=i/2:r.textAlign==="right"&&(C=i),this.ctx.textAlign=r.textAlign,this.ctx.fillText(p,C,w)}),this.map&&(this.map.needsUpdate=!0)}dispose(){this.map&&this.map.dispose(),super.dispose()}}function ae(n,e=0){if(typeof n=="number")return n;const t=parseFloat(n)||0;return typeof n=="string"&&n.includes("%")?t/100*e:t}function le(n){if(!n||n==="transparent")return{color:new v.Color(16777215),alpha:0};const e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(e){const t=parseInt(e[1],10),r=parseInt(e[2],10),i=parseInt(e[3],10),l=e[4]!==void 0?parseFloat(e[4]):1;return{color:new v.Color(`rgb(${t}, ${r}, ${i})`),alpha:l}}return{color:new v.Color(n),alpha:1}}function De(n){const e=[];let t="",r=0;for(let i=0;i<n.length;i++){const l=n[i];if(l==="(")r++;else if(l===")")r--;else if(l===","&&r===0){e.push(t.trim()),t="";continue}t+=l}return t&&e.push(t.trim()),e}function We(n){if(!n||typeof n!="string"||!n.includes("linear-gradient"))return null;const e=n.match(/linear-gradient\((.*)\)/);if(!e)return null;const t=e[1],r=De(t);let i=Math.PI,l=0;const s=r[0].trim();if(s.startsWith("to "))s==="to top"?i=0:s==="to right"?i=Math.PI/2:s==="to bottom"?i=Math.PI:s==="to left"?i=Math.PI*1.5:s==="to top right"||s==="to right top"?i=Math.PI/4:s==="to bottom right"||s==="to right bottom"?i=Math.PI*.75:s==="to bottom left"||s==="to left bottom"?i=Math.PI*1.25:(s==="to top left"||s==="to left top")&&(i=Math.PI*1.75),l=1;else if(s.endsWith("deg")||s.endsWith("rad")||s.endsWith("turn")){const a=parseFloat(s);s.endsWith("deg")?i=a*(Math.PI/180):s.endsWith("rad")?i=a:s.endsWith("turn")&&(i=a*Math.PI*2),l=1}const o=[];for(let a=l;a<r.length&&!(o.length>=8);a++){const c=r[a].trim(),d=c.lastIndexOf(" ");let h=c,f=null;if(d!==-1&&!c.endsWith(")")){const p=c.substring(d+1);(p.endsWith("%")||p.endsWith("px")||!isNaN(parseFloat(p)))&&(h=c.substring(0,d).trim(),f=p)}const g=le(h);o.push({color:g.color,alpha:g.alpha,rawStop:f,stop:0})}if(o.length>0){for(let c=0;c<o.length;c++)o[c].rawStop!==null&&(o[c].stop=parseFloat(o[c].rawStop)/100);o[0].rawStop===null&&(o[0].stop=0),o.length>1&&o[o.length-1].rawStop===null&&(o[o.length-1].stop=1);let a=0;for(let c=1;c<o.length;c++)if(o[c].rawStop!==null||c===o.length-1){const d=c-a;if(d>1){const h=o[a].stop,g=(o[c].stop-h)/d;for(let p=1;p<d;p++)o[a+p].stop=h+g*p}a=c}}return{angle:i,stops:o}}function He(n){if(!n||n==="none")return null;const e=De(n);if(e.length===0)return null;const t=e[0].trim(),r=/(rgba?\([^)]+\)|#[0-9a-fA-F]+|[a-zA-Z]+)/,i=t.match(r);let l="transparent",s=t;if(i&&i[1]!=="inset"){const g=i[1];(g.startsWith("rgb")||g.startsWith("#")||g==="black"||g==="white"||g==="transparent")&&(l=g,s=t.replace(g,"").trim())}s=s.replace("inset","").trim();const o=s.split(/\s+/).map(g=>parseFloat(g)||0),a=o[0]||0,c=o[1]||0,d=o[2]||0,h=o[3]||0,f=le(l);return{offsetX:a,offsetY:c,blurRadius:d,spreadRadius:h,color:f.color,alpha:f.alpha}}const Ge=`varying vec2 vUv;
|
|
3
3
|
varying vec4 vScreenPos;
|
|
4
4
|
void main() {
|
|
5
5
|
vUv = uv;
|
|
6
6
|
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
7
7
|
vScreenPos = gl_Position;
|
|
8
|
-
}
|
|
8
|
+
}`,$e=`varying vec2 vUv;
|
|
9
9
|
uniform vec2 uSize;
|
|
10
|
+
uniform vec2 uMeshSize;
|
|
11
|
+
uniform vec4 uShadowColor;
|
|
12
|
+
uniform vec2 uShadowOffset;
|
|
13
|
+
uniform float uShadowBlur;
|
|
14
|
+
uniform float uShadowSpread;
|
|
10
15
|
uniform vec4 uBorderRadius;
|
|
11
16
|
uniform float uBorderWidth;
|
|
12
17
|
uniform vec4 uBgColor;
|
|
@@ -62,11 +67,10 @@ float sdVisualBox(vec2 p, vec2 b, float r) {
|
|
|
62
67
|
return min(max(q.x, q.y), 0.0) + d;
|
|
63
68
|
}
|
|
64
69
|
|
|
65
|
-
vec4 calculateGradientLayer(vec2
|
|
70
|
+
vec4 calculateGradientLayer(vec2 p) {
|
|
66
71
|
if (uGradientCount < 2) return uGradientColors[0];
|
|
67
72
|
|
|
68
73
|
vec2 dir = vec2(sin(uGradientAngle), cos(uGradientAngle));
|
|
69
|
-
vec2 p = (uv - 0.5) * uSize;
|
|
70
74
|
float proj = dot(p, dir);
|
|
71
75
|
float L = abs(uSize.x * dir.x) + abs(uSize.y * dir.y);
|
|
72
76
|
float t = clamp((proj / L) + 0.5, 0.0, 1.0);
|
|
@@ -85,7 +89,7 @@ vec4 calculateGradientLayer(vec2 uv) {
|
|
|
85
89
|
}
|
|
86
90
|
|
|
87
91
|
void main() {
|
|
88
|
-
vec2 p = (vUv - 0.5) *
|
|
92
|
+
vec2 p = (vUv - 0.5) * uMeshSize;
|
|
89
93
|
vec2 halfSize = uSize * 0.5;
|
|
90
94
|
|
|
91
95
|
// CSS Proportional Border-Radius Clamping
|
|
@@ -106,7 +110,7 @@ void main() {
|
|
|
106
110
|
vec4 baseColor = vec4(uBgColor.rgb, uBgColor.a);
|
|
107
111
|
|
|
108
112
|
if (uGradientCount > 0) {
|
|
109
|
-
vec4 gradColor = calculateGradientLayer(
|
|
113
|
+
vec4 gradColor = calculateGradientLayer(p);
|
|
110
114
|
baseColor = blendSrcOver(gradColor, baseColor);
|
|
111
115
|
}
|
|
112
116
|
|
|
@@ -133,11 +137,26 @@ void main() {
|
|
|
133
137
|
|
|
134
138
|
// final blending (border + background) using blendSrcOver
|
|
135
139
|
vec4 borderLayer = vec4(uBorderColor.rgb, borderAlpha);
|
|
136
|
-
vec4
|
|
140
|
+
vec4 mainColor = blendSrcOver(borderLayer, baseColor);
|
|
141
|
+
mainColor.a *= bgMask;
|
|
142
|
+
|
|
143
|
+
vec4 shadowLayer = vec4(0.0);
|
|
144
|
+
if (uShadowColor.a > 0.001) {
|
|
145
|
+
vec2 shadowP = p - vec2(uShadowOffset.x, -uShadowOffset.y);
|
|
146
|
+
float shadowRadius = max(r + uShadowSpread, 0.0);
|
|
147
|
+
vec2 shadowHalfSize = max(halfSize + vec2(uShadowSpread), vec2(0.0));
|
|
148
|
+
float shadowD = sdRoundedBox(shadowP, shadowHalfSize, shadowRadius);
|
|
149
|
+
float blur = max(uShadowBlur, 1.0);
|
|
150
|
+
float shadowMask = 1.0 - smoothstep(-blur * 0.5, blur * 0.5, shadowD);
|
|
151
|
+
shadowLayer = vec4(uShadowColor.rgb, uShadowColor.a * shadowMask);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
vec4 finalColor = blendSrcOver(mainColor, shadowLayer);
|
|
155
|
+
|
|
137
156
|
// final color control (Tint, Noise)
|
|
138
157
|
#INJECT_COLOR_MODIFIER
|
|
139
158
|
|
|
140
|
-
float finalOpacity = finalColor.a *
|
|
159
|
+
float finalOpacity = finalColor.a * uOpacity;
|
|
141
160
|
if (finalOpacity < 0.001) discard;
|
|
142
161
|
|
|
143
162
|
gl_FragColor = vec4(finalColor.rgb, finalOpacity);
|
|
@@ -145,24 +164,25 @@ void main() {
|
|
|
145
164
|
|
|
146
165
|
// #include <colorspace_fragment>
|
|
147
166
|
}
|
|
148
|
-
`,
|
|
167
|
+
`,qe=`uniform sampler2D uTexture;
|
|
149
168
|
varying vec4 vScreenPos;
|
|
150
169
|
uniform vec2 uTextureRepeat;
|
|
151
|
-
uniform vec2 uTextureOffset
|
|
170
|
+
uniform vec2 uTextureOffset;`,je=`vec2 screenUv = (vScreenPos.xy / vScreenPos.w) * 0.5 + 0.5;
|
|
152
171
|
vec2 resultUv = screenUv;
|
|
153
172
|
|
|
154
|
-
`,
|
|
155
|
-
baseColor = blendSrcOver(baseColor, texColor);`,
|
|
156
|
-
`,
|
|
157
|
-
`,
|
|
158
|
-
`,
|
|
159
|
-
`,
|
|
160
|
-
`,
|
|
161
|
-
`+
|
|
162
|
-
`,h=
|
|
163
|
-
`:`vec2
|
|
164
|
-
`,g=c||o?d+h+((i==null?void 0:i.uvModifier)||""):"",v=c||o?De.baseColorChunk:"",p=(i==null?void 0:i.colorModifier)||"",m=Me.fragmentShader.replace("#INJECT_DECLARATIONS",l).replace("#INJECT_UV_MODIFIER",g).replace("#INJECT_BASE_COLOR",v).replace("#INJECT_COLOR_MODIFIER",p),E=he(s.backgroundColor),D=he(s.borderColor),M={uSize:{value:new y.Vector2(e,t)},uBgColor:{value:new y.Vector4(E.color.r,E.color.g,E.color.b,E.alpha)},uBorderColor:{value:new y.Vector4(D.color.r,D.color.g,D.color.b,D.alpha)},uBorderRadius:{value:new y.Vector4(0,0,0,0)},uBorderWidth:{value:ie(s.borderWidth)},uOpacity:{value:(C=s.opacity)!=null?C:1},uTexture:{value:null},uTextureRepeat:{value:new y.Vector2(1,1)},uTextureOffset:{value:new y.Vector2(0,0)},uGradientCount:{value:0},uGradientAngle:{value:0},uGradientColors:{value:Array.from({length:8},()=>new y.Vector4(0,0,0,0))},uGradientStops:{value:new Float32Array(8)}};Ae(M.uBorderRadius.value,s.borderRadius,Math.min(e,t)),c&&(M.uTexture.value=r);const L=new y.ShaderMaterial({uniforms:te(te({},M),a),vertexShader:Me.vertexShader,fragmentShader:m,transparent:!0,side:y.FrontSide});return s.backgroundImage&&be(L,{backgroundImage:s.backgroundImage}),L}function Ke(s,e,t,r,i){const c=ie(e.borderWidth);be(s,{width:t,height:r,borderRadius:e.borderRadius,borderWidth:c,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:i,backgroundImage:e.backgroundImage})}function be(s,e){var r,i,c;if(e.width!==void 0&&e.height!==void 0&&s.uniforms.uSize.value.set(e.width,e.height),e.borderRadius!==void 0){const n=e.width!==void 0&&e.height!==void 0?Math.min(e.width,e.height):Math.min(s.uniforms.uSize.value.x,s.uniforms.uSize.value.y);Ae(s.uniforms.uBorderRadius.value,e.borderRadius,n)}if(e.borderWidth!==void 0&&(s.uniforms.uBorderWidth.value=e.borderWidth),e.backgroundColor!==void 0)if(Array.isArray(e.backgroundColor)){const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor[0],e.backgroundColor[1],e.backgroundColor[2],n)}else if(typeof e.backgroundColor=="string"){const n=he(e.backgroundColor);s.uniforms.uBgColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor.r,e.backgroundColor.g,e.backgroundColor.b,n)}if(e.borderColor!==void 0)if(Array.isArray(e.borderColor)){const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor[0],e.borderColor[1],e.borderColor[2],n)}else if(typeof e.borderColor=="string"){const n=he(e.borderColor);s.uniforms.uBorderColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor.r,e.borderColor.g,e.borderColor.b,n)}e.opacity!==void 0&&(s.uniforms.uOpacity.value=e.opacity),e.bgOpacity!==void 0&&(s.uniforms.uBgColor.value.w=e.bgOpacity),e.borderOpacity!==void 0&&(s.uniforms.uBorderColor.value.w=e.borderOpacity),s.uniforms.uTexture&&e.texture!==void 0&&(s.uniforms.uTexture.value=e.texture);const t=e.texture!==void 0?e.texture:(r=s.uniforms.uTexture)==null?void 0:r.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const n=t.image.naturalWidth||t.image.videoWidth||t.image.width,a=t.image.naturalHeight||t.image.videoHeight||t.image.height,o=(i=e.width)!=null?i:s.uniforms.uSize.value.x,l=(c=e.height)!=null?c:s.uniforms.uSize.value.y;if(n&&a&&o&&l){const d=n/a,h=o/l;if(d>h){const g=h/d;s.uniforms.uTextureRepeat.value.set(g,1),s.uniforms.uTextureOffset.value.set((1-g)/2,0)}else{const g=d/h;s.uniforms.uTextureRepeat.value.set(1,g),s.uniforms.uTextureOffset.value.set(0,(1-g)/2)}}}else s.uniforms.uTextureRepeat&&(s.uniforms.uTextureRepeat.value.set(1,1),s.uniforms.uTextureOffset.value.set(0,0));if(e.backgroundImage!==void 0){const n=We(e.backgroundImage);if(n){s.uniforms.uGradientCount.value=n.stops.length,s.uniforms.uGradientAngle.value=n.angle;for(let a=0;a<8;a++)if(a<n.stops.length){const o=n.stops[a];s.uniforms.uGradientColors.value[a].set(o.color.r,o.color.g,o.color.b,o.alpha),s.uniforms.uGradientStops.value[a]=o.stop}else s.uniforms.uGradientColors.value[a].set(0,0,0,0),s.uniforms.uGradientStops.value[a]=1}else s.uniforms.uGradientCount.value=0}for(const n of Object.keys(e))n!=="width"&&n!=="height"&&n!=="borderRadius"&&n!=="borderWidth"&&n!=="backgroundColor"&&n!=="borderColor"&&n!=="opacity"&&n!=="bgOpacity"&&n!=="borderOpacity"&&n!=="texture"&&n!=="backgroundImage"&&s.uniforms[n]!==void 0&&(s.uniforms[n].value!==void 0&&s.uniforms[n].value!==null&&typeof s.uniforms[n].value.set=="function"?Array.isArray(e[n])?s.uniforms[n].value.set(...e[n]):e[n]!==void 0&&(e[n].copy?s.uniforms[n].value.copy(e[n]):s.uniforms[n].value=e[n]):s.uniforms[n].value=e[n])}function Ae(s,e,t=0){var o,l,d,h;if(e==null){s.set(0,0,0,0);return}if(typeof e=="number"){s.set(e,e,e,e);return}if(Array.isArray(e)){s.set(e[0],e[1],e[2],e[3]);return}const r=e.split("/")[0].trim().split(/\s+/),i=ie(r[0],t),c=ie((o=r[1])!=null?o:r[0],t),n=ie((l=r[2])!=null?l:r[0],t),a=ie((h=(d=r[3])!=null?d:r[1])!=null?h:r[0],t);s.set(i,c,n,a)}const H={create(s,e,t,r,i,c=2,n=null,a){return s==="BOX"?je(e,r,i,n,a):s==="TEXT"?new Ve(t||"",e,r,i,c):new y.MeshBasicMaterial({visible:!1})},update(s,e,t,r,i,c,n=2,a){e==="BOX"?Ke(s,t,i,c,a):e==="TEXT"&&s.updateText(r||"",t,i,c,n)},forceUpdateUniforms(s,e){be(s,e)}};class Je{constructor(e,t=!0){u(this,"observer");u(this,"textures",new WeakMap);u(this,"loadStatus",new WeakMap);u(this,"elementUrls",new WeakMap);u(this,"onUpdate");this.onUpdate=e,t&&(this.observer=new IntersectionObserver(r=>{for(const i of r){const c=i.target;i.isIntersecting?this.loadTexture(c):this.disposeTexture(c)}},{rootMargin:"300px"}))}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer?(this.observer.unobserve(e),this.observer.observe(e)):this.loadTexture(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return _e(this,null,function*(){if(this.loadStatus.get(e)||this.textures.has(e))return;const t=this.elementUrls.get(e);if(t){this.loadStatus.set(e,!0);try{let r;if(t.startsWith("data:image/svg+xml"))r=yield new Promise((c,n)=>{const a=new Image;a.onload=()=>c(a),a.onerror=n,a.src=t});else{const n=yield(yield fetch(t)).blob();r=yield createImageBitmap(n,{imageOrientation:"flipY"})}if(this.elementUrls.get(e)!==t){"close"in r&&r.close();return}const i=new y.Texture(r);r instanceof HTMLImageElement||(i.flipY=!1),i.colorSpace=y.LinearSRGBColorSpace,i.needsUpdate=!0,this.textures.set(e,i),this.onUpdate(e,i)}catch(r){console.warn("[MirageEngine] Failed to load texture:",t,r)}finally{this.elementUrls.has(e)&&this.loadStatus.set(e,!1)}}})}disposeTexture(e){const t=this.textures.get(e);t&&(t.dispose(),this.textures.delete(e),this.onUpdate(e,null)),this.loadStatus.set(e,!1)}get(e){return this.textures.get(e)}disposeAll(){this.observer&&this.observer.disconnect()}}class Qe{constructor(e,t,r,i){u(this,"canvas");u(this,"scene");u(this,"camera");u(this,"renderer");u(this,"renderTargets",[]);u(this,"renderOrder",0);u(this,"qualityFactor",2);u(this,"mode","overlay");u(this,"canvasSize","viewport");u(this,"clipArea",1);u(this,"targetLayer","base");u(this,"overscan",200);u(this,"target");u(this,"mountContainer");u(this,"registry");u(this,"targetRect");u(this,"travelersByLayer",Array.from({length:_.MAX_LAYERS},()=>new Set));u(this,"textureManager");u(this,"fixedMeshes",new Set);var a,o,l,d,h;this.target=e,this.mountContainer=r,this.registry=i,this.mode=(a=t.mode)!=null?a:"overlay",this.canvasSize=(o=t.canvasSize)!=null?o:"viewport",this.clipArea=(l=t.travelerClipArea)!=null?l:1,this.targetLayer=(d=t.layer)!=null?d:"base",this.textureManager=new Je((g,v)=>{const p=this.registry.get(g);p&&p.material instanceof y.ShaderMaterial&&H.forceUpdateUniforms(p.material,{texture:v})},this.isViewport),this.canvas=document.createElement("canvas"),this.scene=new y.Scene,this.targetRect=this.target.getBoundingClientRect();const c=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,n=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.camera=new y.OrthographicCamera(c/-2,c/2,n/2,n/-2,1,1e3),this.camera.position.z=100,this.camera.layers.set(this.getSceneLayer()),this.renderer=new y.WebGLRenderer({canvas:this.canvas,alpha:!0,antialias:!0}),y.ColorManagement.enabled=!1,this.renderer.outputColorSpace=y.LinearSRGBColorSpace,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(c,n),this.applyTextQuality((h=t.quality)!=null?h:"medium")}get isViewport(){return this.mode==="overlay"&&this.canvasSize==="viewport"}getSceneLayer(){return typeof this.targetLayer=="number"?this.targetLayer:this.targetLayer==="selected"?B.SELECTED:B.BASE}createRenderTarget(){for(let e=0;e<_.MAX_LAYERS;e++){const t=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,r=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.renderTargets.push(new y.WebGLRenderTarget(t*this.qualityFactor,r*this.qualityFactor,{minFilter:y.LinearFilter,magFilter:y.LinearFilter,format:y.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}))}}applyTextQuality(e){if(typeof e=="number"){this.qualityFactor=Math.max(.1,e);return}switch(e){case"low":this.qualityFactor=1;break;case"high":this.qualityFactor=4;break;case"medium":this.qualityFactor=2;break;default:this.qualityFactor=2;break}}mount(){this.mountContainer.prepend(this.canvas),this.canvas.style.pointerEvents=this.mode==="overlay"?"none":"auto",this.updateCanvasLayout()}updateCanvasLayout(){const e=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,t=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.mode==="duplicate"?(this.canvas.style.position="",this.canvas.style.top="",this.canvas.style.left="",this.canvas.style.display="block"):(this.canvas.style.position=this.isViewport?"fixed":"absolute",this.canvas.style.top=this.isViewport?`-${this.overscan}px`:`${this.target.offsetTop}px`,this.canvas.style.left=this.isViewport?`-${this.overscan}px`:`${this.target.offsetLeft}px`,this.canvas.style.display="block")}updateUniforms(e,t){const r=this.registry.get(e);r&&(r.traverse(i=>{i.isMesh&&i.material&&H.forceUpdateUniforms(i.material,t)}),r.userData.nativeMesh&&r.userData.nativeMesh.traverse(i=>{i.isMesh&&i.material&&H.forceUpdateUniforms(i.material,t)}))}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t);for(const r of this.renderTargets)r.setSize(e*this.qualityFactor,t*this.qualityFactor);this.camera.left=e/-2,this.camera.right=e/2,this.camera.top=t/2,this.camera.bottom=t/-2,this.camera.updateProjectionMatrix()}syncScene(e,t){const r=this.target.getBoundingClientRect(),i=this.isViewport?window.innerWidth+this.overscan*2:r.width,c=this.isViewport?window.innerHeight+this.overscan*2:r.height,n=this.isViewport?this.canvas.clientWidth:this.targetRect.width,a=this.isViewport?this.canvas.clientHeight:this.targetRect.height,o=Math.abs(i-n)>.1||Math.abs(c-a)>.1,l=this.mode==="overlay"&&(Math.abs(r.top-this.targetRect.top)>.1||Math.abs(r.left-this.targetRect.left)>.1);o?(this.targetRect=r,this.setSize(i,c),this.updateCanvasLayout()):l?(this.targetRect=r,this.updateCanvasLayout()):this.targetRect=r,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(d=>{const h=this.registry.get(d);if(h){this.scene.remove(h);for(const g of this.travelersByLayer)g.delete(h);this.fixedMeshes.delete(h),h.geometry.dispose(),h.userData.nativeMesh&&(this.scene.remove(h.userData.nativeMesh),Array.isArray(h.userData.nativeMesh.material)?h.userData.nativeMesh.material.forEach(g=>g.dispose()):h.userData.nativeMesh.material.dispose(),h.userData.nativeMesh.geometry.dispose()),h.traverse(g=>{g instanceof y.Mesh&&(g.geometry&&g.geometry.dispose(),g.material&&(Array.isArray(g.material)?g.material.forEach(v=>v.dispose()):g.material.dispose()))}),this.registry.remove(d),this.textureManager.unregister(d)}})}reconcileNode(e){var i,c;let t=this.registry.get(e.element);const r=JSON.stringify(e.shaderHooks||null);if(t&&t.userData.shaderHash!==r&&(this.scene.remove(t),t.geometry.dispose(),t.material instanceof y.Material&&t.material.dispose(),this.registry.remove(e.element),t=void 0),!t){const n=new y.PlaneGeometry(1,1),a=e.isTraveler?(i=this.renderTargets[e.captureLayer-2])==null?void 0:i.texture:this.textureManager.get(e.element),o=H.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,a,e.shaderHooks);t=new y.Mesh(n,o),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t),t.userData.baseMaterial=o,t.userData.domElement=e.element,t.userData.shaderHash=r}if((c=e.nativeStyles)!=null&&c.transform?t.userData.nativeTransform=e.nativeStyles.transform:t.userData.nativeTransform=void 0,this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler)for(let n=0;n<_.MAX_LAYERS;n++)n===e.captureLayer-2?this.travelersByLayer[n].add(t):this.travelersByLayer[n].delete(t);else for(const n of this.travelersByLayer)n.delete(t);if(e.isFixed?this.fixedMeshes.add(t):this.fixedMeshes.delete(t),e.styles.imageSrc?this.textureManager.register(e.element,e.styles.imageSrc):this.textureManager.unregister(e.element),e.type==="BOX")for(const n of e.children)this.reconcileNode(n);else e.type==="TEXT"&&(this.reconcileTextChild(t,e,!1),t.userData.nativeMesh&&e.nativeStyles&&this.reconcileTextChild(t.userData.nativeMesh,e,!0))}reconcileTextChild(e,t,r){var l;const i=t.textLines||[{text:t.textContent||"",rect:t.rect}],c=r?t.nativeStyles:t.textStyles,n=JSON.stringify(c)+t.textContent+i.map(d=>d.text).join("|"),a=(l=e.userData)==null?void 0:l.textChildStyleHash;if(t.dirtyMask&ye||n!==a){e.children.filter(p=>p.name.startsWith("TEXT_CHILD")).forEach(p=>{var E;const m=p;(E=m.material.map)==null||E.dispose(),m.geometry.dispose(),e.remove(m)});const h=t.rect,g=h.x+h.width/2,v=h.y+h.height/2;i.forEach((p,m)=>{const E=H.create("TEXT",c,p.text,p.rect.width,p.rect.height,this.qualityFactor),D=new y.PlaneGeometry(1,1),M=new y.Mesh(D,E);M.name=`TEXT_CHILD_${m}`;const L=t.rect.width===0?1:p.rect.width/t.rect.width,C=t.rect.height===0?1:p.rect.height/t.rect.height;M.scale.set(L,C,1);const S=p.rect.x+p.rect.width/2,w=p.rect.y+p.rect.height/2,V=S-g,Y=-(w-v);M.position.set(t.rect.width===0?0:V/t.rect.width,t.rect.height===0?0:Y/t.rect.height,.005),e.add(M)}),e.userData.textChildStyleHash=n}e.children.forEach(d=>{if(!d.name.startsWith("TEXT_CHILD"))return;const h=d;if(r&&t.nativeLayer!==void 0)h.layers.set(B.HIDDEN),t.visibility&$&&h.layers.enable(B.getCaptureLayer(t.nativeLayer));else{const g=t.visibility&$?B.BASE:B.HIDDEN;if(h.layers.set(g),t.visibility&re&&h.layers.enable(B.SELECTED),t.visibility&$)if(!r&&t.nativeLayer!==void 0&&t.nativeStyles!==void 0)for(let v=t.captureLayer;v<=_.MAX_LAYERS+1;v++)v!==t.nativeLayer&&h.layers.enable(B.getCaptureLayer(v));else for(let v=t.captureLayer;v<=_.MAX_LAYERS+1;v++)h.layers.enable(B.getCaptureLayer(v))}})}updateMeshProperties(e,t){var L,C,S;const{rect:r,styles:i}=t,c=this.renderer.getPixelRatio(),n=this.renderer.domElement.width/c,a=this.renderer.domElement.height/c;e.material=e.userData.baseMaterial,e.scale.set(r.width,r.height,1),e.userData.domRect={x:r.x,y:r.y,width:r.width,height:r.height};const o=.001;this.renderOrder++;const l=this.targetRect.left+window.scrollX,d=this.targetRect.top+window.scrollY;let h,g;if(this.isViewport)h=r.x-window.innerWidth/2+r.width/2,g=-r.y+window.innerHeight/2-r.height/2;else{const w=r.x-l,V=r.y-d;h=w-n/2+r.width/2,g=-V+a/2-r.height/2}e.position.set(h,g,i.zIndex+this.renderOrder*o);const v=r.x,p=r.y;e.userData.basePosition={x:h,y:g},e.userData.originalBasePosition={x:h,y:g},e.userData.baseSize={width:r.width,height:r.height},e.userData.baseDOM={x:v,y:p},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const m=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,E=window.getComputedStyle(m);let D=0,M=0;if(E.transform&&E.transform!=="none"){const w=new DOMMatrix(E.transform);D=w.m41,M=w.m42}if(e.userData.baseTransform={x:D,y:M},delete e.userData.originRatioX,delete e.userData.originRatioY,H.update(e.userData.baseMaterial,"BOX",i,"",r.width,r.height,this.qualityFactor,t.isTraveler?(L=this.renderTargets[t.captureLayer-2])==null?void 0:L.texture:this.textureManager.get(t.element)),t.nativeStyles&&t.nativeRect){if(!e.userData.nativeMesh){const W=H.create("BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(C=this.renderTargets[t.captureLayer-2])==null?void 0:C.texture:this.textureManager.get(t.element),t.shaderHooks),P=new y.Mesh(e.geometry,W);t.type==="TEXT"&&(P.name="BG_MESH"),this.scene.add(P),e.userData.nativeMesh=P}const w=e.userData.nativeMesh;let V,Y;if(this.isViewport)V=t.nativeRect.x-window.innerWidth/2+t.nativeRect.width/2,Y=-t.nativeRect.y+window.innerHeight/2-t.nativeRect.height/2;else{const W=t.nativeRect.x-l,P=t.nativeRect.y-d;V=W-n/2+t.nativeRect.width/2,Y=-P+a/2-t.nativeRect.height/2}let b=t.nativeRect.width,N=t.nativeRect.height,J=V,Q=Y;if(t.nativeStyles.transform){const W=t.nativeStyles.transform,P=W.match(/scale\(([\d.]+%?)\)/);if(P){let f=parseFloat(P[1]);P[1].includes("%")&&(f/=100),b*=f,N*=f}const se=W.match(/scaleX\(([\d.]+%?)\)/);if(se){let f=parseFloat(se[1]);se[1].includes("%")&&(f/=100),b*=f}const ne=W.match(/scaleY\(([\d.]+%?)\)/);if(ne){let f=parseFloat(ne[1]);ne[1].includes("%")&&(f/=100),N*=f}const ae=W.match(/translate\(([^,]+),\s*([^)]+)\)/);if(ae){const f=ae[1].trim(),x=ae[2].trim();let O=parseFloat(f);f.includes("%")&&(O=O/100*t.nativeRect.width);let z=parseFloat(x);x.includes("%")&&(z=z/100*t.nativeRect.height),J+=O,Q-=z}const de=W.match(/translateX\(([^)]+)\)/);if(de){const f=de[1].trim();let x=parseFloat(f);f.includes("%")&&(x=x/100*t.nativeRect.width),J+=x}const ue=W.match(/translateY\(([^)]+)\)/);if(ue){const f=ue[1].trim();let x=parseFloat(f);f.includes("%")&&(x=x/100*t.nativeRect.height),Q-=x}}w.scale.set(b,N,1),w.position.set(J,Q,t.nativeStyles.zIndex+this.renderOrder*o),H.update(w.material,"BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(S=this.renderTargets[t.captureLayer-2])==null?void 0:S.texture:this.textureManager.get(t.element))}else e.userData.nativeMesh&&(this.scene.remove(e.userData.nativeMesh),e.userData.nativeMesh.material instanceof y.Material&&e.userData.nativeMesh.material.dispose(),delete e.userData.nativeMesh)}updateMeshLayers(e,t){const r=t.visibility&$?B.BASE:B.HIDDEN;if(e.layers.set(r),t.visibility&re&&e.layers.enable(B.SELECTED),e.userData.nativeMesh&&t.nativeLayer!==void 0){const i=e.userData.nativeMesh;if(i.layers.set(B.HIDDEN),t.visibility&$){i.layers.enable(B.getCaptureLayer(t.nativeLayer));for(let c=t.captureLayer;c<=_.MAX_LAYERS+1;c++)c!==t.nativeLayer&&e.layers.enable(B.getCaptureLayer(c))}}else if(t.visibility&$)for(let i=t.captureLayer;i<=_.MAX_LAYERS+1;i++)e.layers.enable(B.getCaptureLayer(i))}captureRenderTarget(e,t,r){if(e.size===0||!r)return;const i=new y.Color,c=this.renderer.getClearAlpha();this.renderer.getClearColor(i),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(r),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(t);const n=new y.Vector3,a=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,o=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height,l=this.renderer.getPixelRatio();for(const d of e){n.setFromMatrixPosition(d.matrixWorld),n.project(this.camera);const h=(n.x+1)/2*a,g=(n.y+1)/2*o;let v=0,p=1;typeof this.clipArea=="number"?p=this.clipArea:this.clipArea.endsWith("%")?p=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(v=parseFloat(this.clipArea));const m=d.scale.x*p+.5,E=d.scale.y*p+.5,D=h-m/2,M=g-E/2,L=(D*this.qualityFactor-v)/l,C=(M*this.qualityFactor-v)/l,S=(m*this.qualityFactor+v*2)/l,w=(E*this.qualityFactor+v*2)/l;this.renderer.setScissor(L,C,S,w),this.renderer.render(this.scene,this.camera)}this.renderer.setScissorTest(!1),this.renderer.autoClear=!0,this.renderer.setRenderTarget(null),this.camera.layers.set(this.getSceneLayer()),this.renderer.setClearColor(i,c)}render(){for(let e=0;e<_.MAX_LAYERS;e++){const t=e+1;this.captureRenderTarget(this.travelersByLayer[e],B.getCaptureLayer(t),this.renderTargets[e])}this.renderer.render(this.scene,this.camera)}syncMeshesByDOM(){const e=this.targetRect.left+window.scrollX,t=this.targetRect.top+window.scrollY,r=this.renderer.getPixelRatio(),i=this.renderer.domElement.width/r,c=this.renderer.domElement.height/r;this.scene.children.forEach(n=>{const a=n;if(!a.userData||!a.userData.domElement)return;const o=a.userData.domElement;if(!o.isConnected)return;let l;if(o.nodeType===Node.TEXT_NODE){const h=document.createRange();h.selectNode(o),l=h.getBoundingClientRect()}else l=o.getBoundingClientRect();const d=a.userData.domRect;if(!d||Math.abs(l.x-d.x)>.5||Math.abs(l.y-d.y)>.5||Math.abs(l.width-d.width)>.5||Math.abs(l.height-d.height)>.5){a.userData.domRect={x:l.x,y:l.y,width:l.width,height:l.height};let h,g;if(this.isViewport)h=l.x-window.innerWidth/2+l.width/2,g=-l.y+window.innerHeight/2-l.height/2;else{const v=l.x-e,p=l.y-t;h=v-i/2+l.width/2,g=-p+c/2-l.height/2}if(a.position.setX(h),a.position.setY(g),a.scale.set(l.width,l.height,1),a.updateMatrixWorld(),a.material instanceof y.ShaderMaterial&&H.forceUpdateUniforms(a.material,{width:l.width,height:l.height}),a.userData.nativeMesh){const v=a.userData.nativeMesh;let p=l.width,m=l.height,E=h,D=g;if(a.userData.nativeTransform){const M=a.userData.nativeTransform,L=M.match(/scale\(([\d.]+%?)\)/);if(L){let b=parseFloat(L[1]);L[1].includes("%")&&(b/=100),p*=b,m*=b}const C=M.match(/scaleX\(([\d.]+%?)\)/);if(C){let b=parseFloat(C[1]);C[1].includes("%")&&(b/=100),p*=b}const S=M.match(/scaleY\(([\d.]+%?)\)/);if(S){let b=parseFloat(S[1]);S[1].includes("%")&&(b/=100),m*=b}const w=M.match(/translate\(([^,]+),\s*([^)]+)\)/);if(w){const b=w[1].trim(),N=w[2].trim();let J=parseFloat(b);b.includes("%")&&(J=J/100*l.width);let Q=parseFloat(N);N.includes("%")&&(Q=Q/100*l.height),E+=J,D-=Q}const V=M.match(/translateX\(([^)]+)\)/);if(V){const b=V[1].trim();let N=parseFloat(b);b.includes("%")&&(N=N/100*l.width),E+=N}const Y=M.match(/translateY\(([^)]+)\)/);if(Y){const b=Y[1].trim();let N=parseFloat(b);b.includes("%")&&(N=N/100*l.height),D-=N}}v.position.setX(E),v.position.setY(D),v.scale.set(p,m,1),v.updateMatrixWorld(),v.material instanceof y.ShaderMaterial&&H.forceUpdateUniforms(v.material,{width:p,height:m})}}})}}function Ze(s){const e=s.textContent||"",t=[];let r="",i=null,c=-1;const n=(l,d)=>{for(let h=0;h<l.length;h++){const g=l[h],v=document.createRange();v.setStart(s,d+h),v.setEnd(s,d+h+1);const p=v.getBoundingClientRect();if(p.width===0&&p.height===0){r+=g;continue}c===-1||Math.abs(p.top-c)>p.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=g,i={left:p.left,top:p.top,right:p.right,bottom:p.bottom},c=p.top):(r+=g,i&&(i.left=Math.min(i.left,p.left),i.top=Math.min(i.top,p.top),i.right=Math.max(i.right,p.right),i.bottom=Math.max(i.bottom,p.bottom)))}},a=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let o=0;for(const l of a){const d=document.createRange();d.setStart(s,o),d.setEnd(s,o+l.length);const h=d.getClientRects();if(h.length>1)n(l,o);else{const g=h.length===1?h[0]:d.getBoundingClientRect();if(g.width===0&&g.height===0){r+=l,o+=l.length;continue}c===-1||Math.abs(g.top-c)>g.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=l,i={left:g.left,top:g.top,right:g.right,bottom:g.bottom},c=g.top):(r+=l,i&&(i.left=Math.min(i.left,g.left),i.top=Math.min(i.top,g.top),i.right=Math.max(i.right,g.right),i.bottom=Math.max(i.bottom,g.bottom)))}o+=l.length}return r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),t.filter(l=>l.text.trim().length>0&&l.rect.width>0&&l.rect.height>0)}function ke(s){const e=parseFloat(s.fontSize);let t=parseFloat(s.lineHeight);isNaN(t)&&(t=e*1.2);let r=parseFloat(s.letterSpacing);return isNaN(r)&&(r=0),{font:`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,fontSize:s.fontSize,color:s.color,textAlign:s.textAlign||"start",textBaseline:"alphabetic",direction:s.direction||"inherit",lineHeight:t,letterSpacing:r}}function Ie(s,e=ee|le|Ne|ye|me,t,r=1,i=0,c=2,n,a){var P,se,ne,ae,de,ue;if(s.nodeType===Node.TEXT_NODE){const f=s;if(!f.textContent||!f.textContent.trim())return null;const x=f.textContent.replace(/\s+/g," ");if(x.length===0)return null;const O=Ze(f);if(O.length===0)return null;const z=f.parentElement,F=z?window.getComputedStyle(z):null;if(!F)return null;const K=Math.min(...O.map(T=>T.rect.left)),G=Math.min(...O.map(T=>T.rect.top)),Z=Math.max(...O.map(T=>T.rect.left+T.rect.width)),k=Math.max(...O.map(T=>T.rect.top+T.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:f,rect:{x:K+window.scrollX,y:G+window.scrollY,width:Z-K,height:k-G},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:z&&z.dataset[j.KEY]===j.VALUES.HIDE?1:parseFloat(F.opacity),zIndex:(isNaN(parseInt(F.zIndex))?0:parseInt(F.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:x,textLines:O.map(T=>({text:T.text.trim(),rect:{x:T.rect.left+window.scrollX,y:T.rect.top+window.scrollY,width:T.rect.width,height:T.rect.height}})),textStyles:ke(F),dirtyMask:e,visibility:t,isTraveler:!1,captureLayer:r,isFixed:F.position==="fixed",nativeLayer:n,nativeStyles:a?te(te({backgroundColor:"transparent",backgroundImage:"",opacity:z&&z.dataset[j.KEY]===j.VALUES.HIDE?1:parseFloat(F.opacity),zIndex:(isNaN(parseInt(F.zIndex))?0:parseInt(F.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},ke(F)),a):void 0,nativeRect:a?{x:K+window.scrollX,y:G+window.scrollY,width:Z-K,height:k-G}:void 0,children:[]}}if(s.nodeType!==Node.ELEMENT_NODE)return null;const o=s,l=o.dataset[U.KEY];let d=t,h=t;if(l){const f=new Set(l.split(/\s+/));for(const x of f)if(!Re.includes(x))throw new Error(`[MirageEngine] Invalid filter token: '${x}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(f.has(U.VALUES.END))return null;if(f.has(U.VALUES.INCLUDE_TREE)&&f.has(U.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(f.has(U.VALUES.INCLUDE_SELF)&&f.has(U.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");f.has(U.VALUES.INCLUDE_TREE)?d=d|$:f.has(U.VALUES.EXCLUDE_TREE)&&(d=d&~$),h=d,f.has(U.VALUES.INCLUDE_SELF)?h=h|$:f.has(U.VALUES.EXCLUDE_SELF)&&(h=h&~$)}const g=o.dataset[X.KEY];if(g){const f=new Set(g.split(/\s+/));for(const x of f)if(!Re.includes(x))throw new Error(`[MirageEngine] Invalid select token: '${x}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(f.has(X.VALUES.END))return null;if(f.has(X.VALUES.INCLUDE_TREE)&&f.has(X.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting selects: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(f.has(X.VALUES.INCLUDE_SELF)&&f.has(X.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting selects: 'include-self' and 'exclude-self' cannot be used together on the same element.");f.has(X.VALUES.INCLUDE_TREE)?d=d|re:f.has(X.VALUES.EXCLUDE_TREE)&&(d=d&~re),h=d,f.has(X.VALUES.INCLUDE_SELF)?h=h|re:f.has(X.VALUES.EXCLUDE_SELF)&&(h=h&~re)}const v=o.dataset[_.KEY];let p=!1,m=a?te({},a):{},E=n;if(v){let f=1;const x=v.indexOf("{"),O=v.lastIndexOf("}");let z=v;if(x!==-1&&O!==-1&&O>x){z=v.substring(0,x).trim();const k=v.substring(x,O+1);try{m=new Function("return "+k)()}catch(T){console.warn(`[MirageEngine] Failed to parse travel styles JSON: ${k}`)}}const F=z.split(/\s+/);let K=!1;const G=F.indexOf(_.VALUES.TRAVELER);if(G!==-1){p=!0,K=!0;const k=F[G+1];if(k&&!isNaN(parseInt(k,10)))f=parseInt(k,10);else{const T=F.find(oe=>!isNaN(parseInt(oe,10)));T&&(f=parseInt(T,10))}}const Z=F.indexOf(_.VALUES.NATIVE);if(Z!==-1){const k=F[Z+1];if(k&&!isNaN(parseInt(k,10)))E=parseInt(k,10);else if(!p){const T=F.find(oe=>!isNaN(parseInt(oe,10)));T&&(E=parseInt(T,10))}}if(K){const k=f+1;if(k<r)throw new Error(`[MirageEngine] Traveler layer (${f}) cannot be smaller than inherited capture layer (${r-1}).`);r=Math.min(k,_.MAX_LAYERS+1)}}const D=o.dataset[Be.KEY];let M;D&&(M=JSON.parse(D));const L=o.getBoundingClientRect(),C=window.getComputedStyle(o);if(L.width===0||L.height===0||C.display==="none")return null;let S=o.getAttribute("data-mid");S||(S=Math.random().toString(36).substring(2,11),o.setAttribute("data-mid",S));const w=parseInt(C.zIndex),V=(isNaN(w)?0:w)+i;let Y;if(o.tagName==="IMG")Y=o.src;else if(o.tagName.toLowerCase()==="svg"){const f=o.cloneNode(!0),x=m==null?void 0:m.color,O=m==null?void 0:m.fill,z=m==null?void 0:m.stroke,F=m==null?void 0:m.opacity,K=(T,oe)=>{const q=window.getComputedStyle(T),fe=oe,at=q.fill===q.color,ot=q.stroke===q.color,we=O||(at?x:void 0)||q.fill;we&&we!=="none"&&(fe.style.fill=we);const xe=z||(ot?x:void 0)||q.stroke;xe&&xe!=="none"&&(fe.style.stroke=xe),q.strokeWidth&&q.strokeWidth!=="0px"&&(fe.style.strokeWidth=q.strokeWidth);const Ue=x||q.color;Ue&&(fe.style.color=Ue);const Ee=F||q.opacity;Ee&&Ee!=="1"&&(fe.style.opacity=Ee);for(let ve=0;ve<T.children.length;ve++)K(T.children[ve],oe.children[ve])};K(o,f);const G=o.getBoundingClientRect(),Z=window.devicePixelRatio*c;f.hasAttribute("viewBox")||f.setAttribute("viewBox",`0 0 ${G.width} ${G.height}`),f.setAttribute("width",(G.width*Z).toString()),f.setAttribute("height",(G.height*Z).toString());let k=new XMLSerializer().serializeToString(f);k.includes("xmlns=")||(k=k.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),Y=`data:image/svg+xml;utf8,${encodeURIComponent(k)}`}else if(C.backgroundImage&&C.backgroundImage!=="none"){const f=C.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);f&&(Y=f[1])}const b={backgroundColor:C.backgroundColor,backgroundImage:C.backgroundImage,opacity:o.dataset[j.KEY]===j.VALUES.HIDE?1:parseFloat(C.opacity),zIndex:V,borderRadius:C.borderRadius,borderColor:C.borderColor,borderWidth:C.borderWidth,imageSrc:Y,isTraveler:p},N=b;let J,Q;const W=[];return o.tagName.toLowerCase()!=="svg"&&Array.from(o.childNodes).forEach(f=>{const x=f.nodeType===Node.TEXT_NODE?h:d,O=Ie(f,e,x,r,V,c,f.nodeType===Node.TEXT_NODE?E:void 0,f.nodeType===Node.TEXT_NODE&&Object.keys(m).length>0?m:void 0);O&&W.push(O)}),{id:S,type:"BOX",element:o,rect:{x:L.left+window.scrollX,y:L.top+window.scrollY,width:L.width,height:L.height},styles:N,textContent:J,textStyles:Q,dirtyMask:e,visibility:h,isTraveler:p,captureLayer:r,nativeLayer:E,nativeStyles:E!==void 0?Fe(te({},b),{backgroundColor:(P=m.backgroundColor)!=null?P:b.backgroundColor,backgroundImage:(se=m.backgroundImage)!=null?se:b.backgroundImage,opacity:(ne=m.opacity)!=null?ne:b.opacity,zIndex:m.zIndex!==void 0?m.zIndex+V:b.zIndex,borderRadius:(ae=m.borderRadius)!=null?ae:b.borderRadius,borderColor:(de=m.borderColor)!=null?de:b.borderColor,borderWidth:(ue=m.borderWidth)!=null?ue:b.borderWidth,isTraveler:b.isTraveler,transform:m.transform}):void 0,nativeRect:E!==void 0?{x:m.x!==void 0?parseFloat(m.x):L.left+window.scrollX,y:m.y!==void 0?parseFloat(m.y):L.top+window.scrollY,width:m.width!==void 0?parseFloat(m.width):L.width,height:m.height!==void 0?parseFloat(m.height):L.height}:void 0,isFixed:C.position==="fixed",children:W,shaderHooks:M}}function et(s,e){e.size!==0&&e.forEach((t,r)=>{var c,n,a,o;const i=s.get(r);!i||!i.userData.basePosition||(H.forceUpdateUniforms(i.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(n=t.borderRadius)!=null?n:(c=i.userData.baseStyles)==null?void 0:c.borderRadius}),i.userData.nativeMesh&&H.forceUpdateUniforms(i.userData.nativeMesh.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(o=t.borderRadius)!=null?o:(a=i.userData.baseStyles)==null?void 0:a.borderRadius}))})}class tt{constructor(e,t,r,i){u(this,"target");u(this,"renderer");u(this,"registry");u(this,"isTravelEnabled",!1);u(this,"tracker");this.target=e,this.renderer=t,this.registry=r,this.tracker=new Te(e,{resizeDebounce:i.resizeDebounce}),this.tracker.onLayoutChange.add((c,n)=>{document.querySelector(`[${_.NAME}~='${_.VALUES.TRAVELER}']`)!==null&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const o=Ie(this.target,c,$,1,0,this.renderer.qualityFactor);o&&this.renderer.syncScene(o,n)}),this.tracker.onStyleChange.add(c=>{et(this.registry,c)}),this.tracker.onRender.add(()=>{this.renderer.syncMeshesByDOM(),this.renderer.render()})}start(){this.tracker.start()}stop(){this.tracker.stop()}}class rt{constructor(){u(this,"store");this.store=new WeakMap}register(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}has(e){return this.store.has(e)}remove(e){this.store.delete(e)}}class it{constructor(e,t){u(this,"renderer");u(this,"syncer");u(this,"target");u(this,"registry");var i,c,n;if(this.target=e,this.registry=new rt,!document.getElementById("mirage-engine-styles")){const a=document.createElement("style");a.id="mirage-engine-styles",a.textContent=`
|
|
165
|
-
[${j.NAME}="${j.VALUES.HIDE}"] {
|
|
173
|
+
`,Ke=`vec4 texColor = texture2D(uTexture, resultUv);
|
|
174
|
+
baseColor = blendSrcOver(baseColor, texColor);`,Ae={vertexShader:Ge,fragmentShader:$e},ke={declChunk:qe,uvChunk:je,baseColorChunk:Ke};function Je(n,e,t,r=null,i){var S;const l=r!==null||!!n.imageSrc;let s="";const o={};if(i!=null&&i.uniforms)for(const[R,E]of Object.entries(i.uniforms))typeof E=="number"?(s+=`uniform float ${R};
|
|
175
|
+
`,o[R]={value:E}):Array.isArray(E)?E.length===2?(s+=`uniform vec2 ${R};
|
|
176
|
+
`,o[R]={value:new v.Vector2(...E)}):E.length===3?(s+=`uniform vec3 ${R};
|
|
177
|
+
`,o[R]={value:new v.Vector3(...E)}):E.length===4&&(s+=`uniform vec4 ${R};
|
|
178
|
+
`,o[R]={value:new v.Vector4(...E)}):(s+=`uniform float ${R};
|
|
179
|
+
`,o[R]={value:E});const a=i!==void 0,c=(l||a?ke.declChunk:"")+`
|
|
180
|
+
`+s,d=`vec2 screenUv = (vScreenPos.xy / vScreenPos.w) * 0.5 + 0.5;
|
|
181
|
+
`,h=n.isTraveler?`vec2 resultUv = screenUv;
|
|
182
|
+
`:`vec2 localUv = (p / uSize) + 0.5;
|
|
183
|
+
vec2 resultUv = localUv * uTextureRepeat + uTextureOffset;
|
|
184
|
+
`,f=l||a?d+h+((i==null?void 0:i.uvModifier)||""):"",g=l||a?ke.baseColorChunk:"",p=(i==null?void 0:i.colorModifier)||"",y=Ae.fragmentShader.replace("#INJECT_DECLARATIONS",c).replace("#INJECT_UV_MODIFIER",f).replace("#INJECT_BASE_COLOR",g).replace("#INJECT_COLOR_MODIFIER",p),w=le(n.backgroundColor),C=le(n.borderColor),O={uSize:{value:new v.Vector2(e,t)},uMeshSize:{value:new v.Vector2(e,t)},uShadowColor:{value:new v.Vector4(0,0,0,0)},uShadowOffset:{value:new v.Vector2(0,0)},uShadowBlur:{value:0},uShadowSpread:{value:0},uBgColor:{value:new v.Vector4(w.color.r,w.color.g,w.color.b,w.alpha)},uBorderColor:{value:new v.Vector4(C.color.r,C.color.g,C.color.b,C.alpha)},uBorderRadius:{value:new v.Vector4(0,0,0,0)},uBorderWidth:{value:ae(n.borderWidth)},uOpacity:{value:(S=n.opacity)!=null?S:1},uTexture:{value:null},uTextureRepeat:{value:new v.Vector2(1,1)},uTextureOffset:{value:new v.Vector2(0,0)},uGradientCount:{value:0},uGradientAngle:{value:0},uGradientColors:{value:Array.from({length:8},()=>new v.Vector4(0,0,0,0))},uGradientStops:{value:new Float32Array(8)}};Ie(O.uBorderRadius.value,n.borderRadius,Math.min(e,t)),l&&(O.uTexture.value=r);const A=new v.ShaderMaterial({uniforms:ne(ne({},O),o),vertexShader:Ae.vertexShader,fragmentShader:y,transparent:!0,side:v.FrontSide});return n.backgroundImage&&be(A,{backgroundImage:n.backgroundImage}),A}function Ze(n,e,t,r,i){const l=ae(e.borderWidth);be(n,{width:t,height:r,borderRadius:e.borderRadius,borderWidth:l,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:i,backgroundImage:e.backgroundImage,boxShadow:e.boxShadow})}function be(n,e){var r,i,l;if(e.boxShadow!==void 0){const s=He(e.boxShadow);s?(n.uniforms.uShadowColor.value.set(s.color.r,s.color.g,s.color.b,s.alpha),n.uniforms.uShadowOffset.value.set(s.offsetX,s.offsetY),n.uniforms.uShadowBlur.value=s.blurRadius,n.uniforms.uShadowSpread.value=s.spreadRadius,n.userData.shadowPadding=s.blurRadius+s.spreadRadius+Math.max(Math.abs(s.offsetX),Math.abs(s.offsetY))):(n.uniforms.uShadowColor.value.w=0,n.userData.shadowPadding=0)}if(e.width!==void 0&&e.height!==void 0&&n.uniforms.uSize.value.set(e.width,e.height),n.uniforms.uMeshSize){const s=n.userData.shadowPadding||0,o=e.width!==void 0?e.width:n.uniforms.uSize.value.x,a=e.height!==void 0?e.height:n.uniforms.uSize.value.y;n.uniforms.uMeshSize.value.set(o+s*2,a+s*2)}if(e.borderRadius!==void 0){const s=e.width!==void 0&&e.height!==void 0?Math.min(e.width,e.height):Math.min(n.uniforms.uSize.value.x,n.uniforms.uSize.value.y);Ie(n.uniforms.uBorderRadius.value,e.borderRadius,s)}if(e.borderWidth!==void 0&&(n.uniforms.uBorderWidth.value=e.borderWidth),e.backgroundColor!==void 0)if(Array.isArray(e.backgroundColor)){const s=n.uniforms.uBgColor.value.w;n.uniforms.uBgColor.value.set(e.backgroundColor[0],e.backgroundColor[1],e.backgroundColor[2],s)}else if(typeof e.backgroundColor=="string"){const s=le(e.backgroundColor);n.uniforms.uBgColor.value.set(s.color.r,s.color.g,s.color.b,s.alpha)}else{const s=n.uniforms.uBgColor.value.w;n.uniforms.uBgColor.value.set(e.backgroundColor.r,e.backgroundColor.g,e.backgroundColor.b,s)}if(e.borderColor!==void 0)if(Array.isArray(e.borderColor)){const s=n.uniforms.uBorderColor.value.w;n.uniforms.uBorderColor.value.set(e.borderColor[0],e.borderColor[1],e.borderColor[2],s)}else if(typeof e.borderColor=="string"){const s=le(e.borderColor);n.uniforms.uBorderColor.value.set(s.color.r,s.color.g,s.color.b,s.alpha)}else{const s=n.uniforms.uBorderColor.value.w;n.uniforms.uBorderColor.value.set(e.borderColor.r,e.borderColor.g,e.borderColor.b,s)}e.opacity!==void 0&&(n.uniforms.uOpacity.value=e.opacity),e.bgOpacity!==void 0&&(n.uniforms.uBgColor.value.w=e.bgOpacity),e.borderOpacity!==void 0&&(n.uniforms.uBorderColor.value.w=e.borderOpacity),n.uniforms.uTexture&&e.texture!==void 0&&(n.uniforms.uTexture.value=e.texture);const t=e.texture!==void 0?e.texture:(r=n.uniforms.uTexture)==null?void 0:r.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const s=t.image.naturalWidth||t.image.videoWidth||t.image.width,o=t.image.naturalHeight||t.image.videoHeight||t.image.height,a=(i=e.width)!=null?i:n.uniforms.uSize.value.x,c=(l=e.height)!=null?l:n.uniforms.uSize.value.y;if(s&&o&&a&&c){const d=s/o,h=a/c;if(d>h){const f=h/d;n.uniforms.uTextureRepeat.value.set(f,1),n.uniforms.uTextureOffset.value.set((1-f)/2,0)}else{const f=d/h;n.uniforms.uTextureRepeat.value.set(1,f),n.uniforms.uTextureOffset.value.set(0,(1-f)/2)}}}else n.uniforms.uTextureRepeat&&(n.uniforms.uTextureRepeat.value.set(1,1),n.uniforms.uTextureOffset.value.set(0,0));if(e.backgroundImage!==void 0){const s=We(e.backgroundImage);if(s){n.uniforms.uGradientCount.value=s.stops.length,n.uniforms.uGradientAngle.value=s.angle;for(let o=0;o<8;o++)if(o<s.stops.length){const a=s.stops[o];n.uniforms.uGradientColors.value[o].set(a.color.r,a.color.g,a.color.b,a.alpha),n.uniforms.uGradientStops.value[o]=a.stop}else n.uniforms.uGradientColors.value[o].set(0,0,0,0),n.uniforms.uGradientStops.value[o]=1}else n.uniforms.uGradientCount.value=0}for(const s of Object.keys(e))s!=="width"&&s!=="height"&&s!=="borderRadius"&&s!=="borderWidth"&&s!=="backgroundColor"&&s!=="borderColor"&&s!=="opacity"&&s!=="bgOpacity"&&s!=="borderOpacity"&&s!=="texture"&&s!=="backgroundImage"&&s!=="boxShadow"&&n.uniforms[s]!==void 0&&(n.uniforms[s].value!==void 0&&n.uniforms[s].value!==null&&typeof n.uniforms[s].value.set=="function"?Array.isArray(e[s])?n.uniforms[s].value.set(...e[s]):e[s]!==void 0&&(e[s].copy?n.uniforms[s].value.copy(e[s]):n.uniforms[s].value=e[s]):n.uniforms[s].value=e[s])}function Ie(n,e,t=0){var a,c,d,h;if(e==null){n.set(0,0,0,0);return}if(typeof e=="number"){n.set(e,e,e,e);return}if(Array.isArray(e)){n.set(e[0],e[1],e[2],e[3]);return}const r=e.split("/")[0].trim().split(/\s+/),i=ae(r[0],t),l=ae((a=r[1])!=null?a:r[0],t),s=ae((c=r[2])!=null?c:r[0],t),o=ae((h=(d=r[3])!=null?d:r[1])!=null?h:r[0],t);n.set(i,l,s,o)}const G={create(n,e,t,r,i,l=2,s=null,o){return n==="BOX"?Je(e,r,i,s,o):n==="TEXT"?new Pe(t||"",e,r,i,l):new v.MeshBasicMaterial({visible:!1})},update(n,e,t,r,i,l,s=2,o){e==="BOX"?Ze(n,t,i,l,o):e==="TEXT"&&n.updateText(r||"",t,i,l,s)},forceUpdateUniforms(n,e){be(n,e)}};class Qe{constructor(e,t=!0){u(this,"observer");u(this,"textures",new WeakMap);u(this,"loadStatus",new WeakMap);u(this,"elementUrls",new WeakMap);u(this,"onUpdate");this.onUpdate=e,t&&(this.observer=new IntersectionObserver(r=>{for(const i of r){const l=i.target;i.isIntersecting?this.loadTexture(l):this.disposeTexture(l)}},{rootMargin:"300px"}))}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer?(this.observer.unobserve(e),this.observer.observe(e)):this.loadTexture(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return ze(this,null,function*(){if(this.loadStatus.get(e)||this.textures.has(e))return;const t=this.elementUrls.get(e);if(t){this.loadStatus.set(e,!0);try{let r;if(t.startsWith("data:image/svg+xml"))r=yield new Promise((l,s)=>{const o=new Image;o.onload=()=>l(o),o.onerror=s,o.src=t});else{const s=yield(yield fetch(t)).blob();r=yield createImageBitmap(s,{imageOrientation:"flipY"})}if(this.elementUrls.get(e)!==t){"close"in r&&r.close();return}const i=new v.Texture(r);r instanceof HTMLImageElement||(i.flipY=!1),i.colorSpace=v.LinearSRGBColorSpace,i.needsUpdate=!0,this.textures.set(e,i),this.onUpdate(e,i)}catch(r){console.warn("[MirageEngine] Failed to load texture:",t,r)}finally{this.elementUrls.has(e)&&this.loadStatus.set(e,!1)}}})}disposeTexture(e){const t=this.textures.get(e);t&&(t.dispose(),this.textures.delete(e),this.onUpdate(e,null)),this.loadStatus.set(e,!1)}get(e){return this.textures.get(e)}disposeAll(){this.observer&&this.observer.disconnect()}}class et{constructor(e,t,r,i){u(this,"canvas");u(this,"scene");u(this,"camera");u(this,"renderer");u(this,"renderTargets",[]);u(this,"renderOrder",0);u(this,"qualityFactor",2);u(this,"mode","overlay");u(this,"canvasSize","viewport");u(this,"clipArea",1);u(this,"targetLayer","base");u(this,"overscan",200);u(this,"target");u(this,"mountContainer");u(this,"registry");u(this,"targetRect");u(this,"travelersByLayer",Array.from({length:_.MAX_LAYERS},()=>new Set));u(this,"textureManager");u(this,"fixedMeshes",new Set);var o,a,c,d,h;this.target=e,this.mountContainer=r,this.registry=i,this.mode=(o=t.mode)!=null?o:"overlay",this.canvasSize=(a=t.canvasSize)!=null?a:"viewport",this.clipArea=(c=t.travelerClipArea)!=null?c:1,this.targetLayer=(d=t.layer)!=null?d:"base",this.textureManager=new Qe((f,g)=>{const p=this.registry.get(f);p&&p.material instanceof v.ShaderMaterial&&G.forceUpdateUniforms(p.material,{texture:g})},this.isViewport),this.canvas=document.createElement("canvas"),this.scene=new v.Scene,this.targetRect=this.target.getBoundingClientRect();const l=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,s=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.camera=new v.OrthographicCamera(l/-2,l/2,s/2,s/-2,1,1e3),this.camera.position.z=100,this.camera.layers.set(this.getSceneLayer()),this.renderer=new v.WebGLRenderer({canvas:this.canvas,alpha:!0,antialias:!0}),v.ColorManagement.enabled=!1,this.renderer.outputColorSpace=v.LinearSRGBColorSpace,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(l,s),this.applyTextQuality((h=t.quality)!=null?h:"medium")}get isViewport(){return this.mode==="overlay"&&this.canvasSize==="viewport"}getSceneLayer(){return typeof this.targetLayer=="number"?this.targetLayer:this.targetLayer==="selected"?N.SELECTED:N.BASE}createRenderTarget(){for(let e=0;e<_.MAX_LAYERS;e++){const t=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,r=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.renderTargets.push(new v.WebGLRenderTarget(t*this.qualityFactor,r*this.qualityFactor,{minFilter:v.LinearFilter,magFilter:v.LinearFilter,format:v.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}))}}applyTextQuality(e){if(typeof e=="number"){this.qualityFactor=Math.max(.1,e);return}switch(e){case"low":this.qualityFactor=1;break;case"high":this.qualityFactor=4;break;case"medium":this.qualityFactor=2;break;default:this.qualityFactor=2;break}}mount(){this.mountContainer.prepend(this.canvas),this.canvas.style.pointerEvents=this.mode==="overlay"?"none":"auto",this.updateCanvasLayout()}updateCanvasLayout(){const e=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,t=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.mode==="duplicate"?(this.canvas.style.position="",this.canvas.style.top="",this.canvas.style.left="",this.canvas.style.display="block"):(this.canvas.style.position=this.isViewport?"fixed":"absolute",this.canvas.style.top=this.isViewport?`-${this.overscan}px`:`${this.target.offsetTop}px`,this.canvas.style.left=this.isViewport?`-${this.overscan}px`:`${this.target.offsetLeft}px`,this.canvas.style.display="block")}updateUniforms(e,t){const r=this.registry.get(e);r&&(r.traverse(i=>{i.isMesh&&i.material&&G.forceUpdateUniforms(i.material,t)}),r.userData.nativeMesh&&r.userData.nativeMesh.traverse(i=>{i.isMesh&&i.material&&G.forceUpdateUniforms(i.material,t)}))}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t);for(const r of this.renderTargets)r.setSize(e*this.qualityFactor,t*this.qualityFactor);this.camera.left=e/-2,this.camera.right=e/2,this.camera.top=t/2,this.camera.bottom=t/-2,this.camera.updateProjectionMatrix()}syncScene(e,t){const r=this.target.getBoundingClientRect(),i=this.isViewport?window.innerWidth+this.overscan*2:r.width,l=this.isViewport?window.innerHeight+this.overscan*2:r.height,s=this.isViewport?this.canvas.clientWidth:this.targetRect.width,o=this.isViewport?this.canvas.clientHeight:this.targetRect.height,a=Math.abs(i-s)>.1||Math.abs(l-o)>.1,c=this.mode==="overlay"&&(Math.abs(r.top-this.targetRect.top)>.1||Math.abs(r.left-this.targetRect.left)>.1);a?(this.targetRect=r,this.setSize(i,l),this.updateCanvasLayout()):c?(this.targetRect=r,this.updateCanvasLayout()):this.targetRect=r,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(d=>{const h=this.registry.get(d);if(h){this.scene.remove(h);for(const f of this.travelersByLayer)f.delete(h);this.fixedMeshes.delete(h),h.geometry.dispose(),h.userData.nativeMesh&&(this.scene.remove(h.userData.nativeMesh),Array.isArray(h.userData.nativeMesh.material)?h.userData.nativeMesh.material.forEach(f=>f.dispose()):h.userData.nativeMesh.material.dispose(),h.userData.nativeMesh.geometry.dispose()),h.traverse(f=>{f instanceof v.Mesh&&(f.geometry&&f.geometry.dispose(),f.material&&(Array.isArray(f.material)?f.material.forEach(g=>g.dispose()):f.material.dispose()))}),this.registry.remove(d),this.textureManager.unregister(d)}})}reconcileNode(e){var i,l;let t=this.registry.get(e.element);const r=JSON.stringify(e.shaderHooks||null);if(t&&t.userData.shaderHash!==r&&(this.scene.remove(t),t.geometry.dispose(),t.material instanceof v.Material&&t.material.dispose(),this.registry.remove(e.element),t=void 0),!t){const s=new v.PlaneGeometry(1,1),o=e.isTraveler?(i=this.renderTargets[e.captureLayer-2])==null?void 0:i.texture:this.textureManager.get(e.element),a=G.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,o,e.shaderHooks);t=new v.Mesh(s,a),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t),t.userData.baseMaterial=a,t.userData.domElement=e.element,t.userData.shaderHash=r}if((l=e.nativeStyles)!=null&&l.transform?t.userData.nativeTransform=e.nativeStyles.transform:t.userData.nativeTransform=void 0,this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler)for(let s=0;s<_.MAX_LAYERS;s++)s===e.captureLayer-2?this.travelersByLayer[s].add(t):this.travelersByLayer[s].delete(t);else for(const s of this.travelersByLayer)s.delete(t);if(e.isFixed?this.fixedMeshes.add(t):this.fixedMeshes.delete(t),e.styles.imageSrc?this.textureManager.register(e.element,e.styles.imageSrc):this.textureManager.unregister(e.element),e.type==="BOX")for(const s of e.children)this.reconcileNode(s);else e.type==="TEXT"&&(this.reconcileTextChild(t,e,!1),t.userData.nativeMesh&&e.nativeStyles&&this.reconcileTextChild(t.userData.nativeMesh,e,!0))}reconcileTextChild(e,t,r){var c;const i=t.textLines||[{text:t.textContent||"",rect:t.rect}],l=r?t.nativeStyles:t.textStyles,s=JSON.stringify(l)+t.textContent+i.map(d=>d.text).join("|"),o=(c=e.userData)==null?void 0:c.textChildStyleHash;if(t.dirtyMask&we||s!==o){e.children.filter(p=>p.name.startsWith("TEXT_CHILD")).forEach(p=>{var w;const y=p;(w=y.material.map)==null||w.dispose(),y.geometry.dispose(),e.remove(y)});const h=t.rect,f=h.x+h.width/2,g=h.y+h.height/2;i.forEach((p,y)=>{const w=G.create("TEXT",l,p.text,p.rect.width,p.rect.height,this.qualityFactor),C=new v.PlaneGeometry(1,1),O=new v.Mesh(C,w);O.name=`TEXT_CHILD_${y}`;const A=t.rect.width===0?1:p.rect.width/t.rect.width,S=t.rect.height===0?1:p.rect.height/t.rect.height;O.scale.set(A,S,1);const R=p.rect.x+p.rect.width/2,E=p.rect.y+p.rect.height/2,$=R-f,W=-(E-g);O.position.set(t.rect.width===0?0:$/t.rect.width,t.rect.height===0?0:W/t.rect.height,.005),e.add(O)}),e.userData.textChildStyleHash=s}e.children.forEach(d=>{if(!d.name.startsWith("TEXT_CHILD"))return;const h=d;if(r&&t.nativeLayer!==void 0)h.layers.set(N.HIDDEN),t.visibility&j&&h.layers.enable(N.getCaptureLayer(t.nativeLayer));else{const f=t.visibility&j?N.BASE:N.HIDDEN;if(h.layers.set(f),t.visibility&oe&&h.layers.enable(N.SELECTED),t.visibility&j)if(!r&&t.nativeLayer!==void 0&&t.nativeStyles!==void 0)for(let g=t.captureLayer;g<=_.MAX_LAYERS+1;g++)g!==t.nativeLayer&&h.layers.enable(N.getCaptureLayer(g));else for(let g=t.captureLayer;g<=_.MAX_LAYERS+1;g++)h.layers.enable(N.getCaptureLayer(g))}})}updateMeshProperties(e,t){var S,R,E,$,W;const{rect:r,styles:i}=t,l=this.renderer.getPixelRatio(),s=this.renderer.domElement.width/l,o=this.renderer.domElement.height/l;e.material=e.userData.baseMaterial;let a=((S=e.material.userData)==null?void 0:S.shadowPadding)||0;e.scale.set(r.width+a*2,r.height+a*2,1),e.userData.domRect={x:r.x,y:r.y,width:r.width,height:r.height};const c=.001;this.renderOrder++;const d=this.targetRect.left+window.scrollX,h=this.targetRect.top+window.scrollY;let f,g;if(this.isViewport)f=r.x-window.innerWidth/2+r.width/2,g=-r.y+window.innerHeight/2-r.height/2;else{const L=r.x-d,K=r.y-h;f=L-s/2+r.width/2,g=-K+o/2-r.height/2}e.position.set(f,g,i.zIndex+this.renderOrder*c);const p=r.x,y=r.y;e.userData.basePosition={x:f,y:g},e.userData.originalBasePosition={x:f,y:g},e.userData.baseSize={width:r.width,height:r.height},e.userData.baseDOM={x:p,y},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const w=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,C=window.getComputedStyle(w);let O=0,A=0;if(C.transform&&C.transform!=="none"){const L=new DOMMatrix(C.transform);O=L.m41,A=L.m42}if(e.userData.baseTransform={x:O,y:A},delete e.userData.originRatioX,delete e.userData.originRatioY,G.update(e.userData.baseMaterial,"BOX",i,"",r.width,r.height,this.qualityFactor,t.isTraveler?(R=this.renderTargets[t.captureLayer-2])==null?void 0:R.texture:this.textureManager.get(t.element)),t.nativeStyles&&t.nativeRect){if(!e.userData.nativeMesh){const H=G.create("BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(E=this.renderTargets[t.captureLayer-2])==null?void 0:E.texture:this.textureManager.get(t.element),t.shaderHooks),q=new v.Mesh(e.geometry,H);t.type==="TEXT"&&(q.name="BG_MESH"),this.scene.add(q),e.userData.nativeMesh=q}const L=e.userData.nativeMesh;let K,te;if(this.isViewport)K=t.nativeRect.x-window.innerWidth/2+t.nativeRect.width/2,te=-t.nativeRect.y+window.innerHeight/2-t.nativeRect.height/2;else{const H=t.nativeRect.x-d,q=t.nativeRect.y-h;K=H-s/2+t.nativeRect.width/2,te=-q+o/2-t.nativeRect.height/2}let re=t.nativeRect.width,M=t.nativeRect.height,X=K,Q=te;if(t.nativeStyles.transform){const H=t.nativeStyles.transform,q=H.match(/scale\(([\d.]+%?)\)/);if(q){let b=parseFloat(q[1]);q[1].includes("%")&&(b/=100),re*=b,M*=b}const ce=H.match(/scaleX\(([\d.]+%?)\)/);if(ce){let b=parseFloat(ce[1]);ce[1].includes("%")&&(b/=100),re*=b}const he=H.match(/scaleY\(([\d.]+%?)\)/);if(he){let b=parseFloat(he[1]);he[1].includes("%")&&(b/=100),M*=b}const m=H.match(/translate\(([^,]+),\s*([^)]+)\)/);if(m){const b=m[1].trim(),x=m[2].trim();let P=parseFloat(b);b.includes("%")&&(P=P/100*t.nativeRect.width);let V=parseFloat(x);x.includes("%")&&(V=V/100*t.nativeRect.height),X+=P,Q-=V}const k=H.match(/translateX\(([^)]+)\)/);if(k){const b=k[1].trim();let x=parseFloat(b);b.includes("%")&&(x=x/100*t.nativeRect.width),X+=x}const z=H.match(/translateY\(([^)]+)\)/);if(z){const b=z[1].trim();let x=parseFloat(b);b.includes("%")&&(x=x/100*t.nativeRect.height),Q-=x}}let ee=(($=L.material.userData)==null?void 0:$.shadowPadding)||0;L.scale.set(re+ee*2,M+ee*2,1),L.position.set(X,Q,t.nativeStyles.zIndex+this.renderOrder*c),G.update(L.material,"BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(W=this.renderTargets[t.captureLayer-2])==null?void 0:W.texture:this.textureManager.get(t.element))}else e.userData.nativeMesh&&(this.scene.remove(e.userData.nativeMesh),e.userData.nativeMesh.material instanceof v.Material&&e.userData.nativeMesh.material.dispose(),delete e.userData.nativeMesh)}updateMeshLayers(e,t){const r=t.visibility&j?N.BASE:N.HIDDEN;if(e.layers.set(r),t.visibility&oe&&e.layers.enable(N.SELECTED),e.userData.nativeMesh&&t.nativeLayer!==void 0){const i=e.userData.nativeMesh;if(i.layers.set(N.HIDDEN),t.visibility&j){i.layers.enable(N.getCaptureLayer(t.nativeLayer));for(let l=t.captureLayer;l<=_.MAX_LAYERS+1;l++)l!==t.nativeLayer&&e.layers.enable(N.getCaptureLayer(l))}}else if(t.visibility&j)for(let i=t.captureLayer;i<=_.MAX_LAYERS+1;i++)e.layers.enable(N.getCaptureLayer(i))}captureRenderTarget(e,t,r){if(e.size===0||!r)return;const i=new v.Color,l=this.renderer.getClearAlpha();this.renderer.getClearColor(i),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(r),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(t);const s=new v.Vector3,o=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,a=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height,c=this.renderer.getPixelRatio();for(const d of e){s.setFromMatrixPosition(d.matrixWorld),s.project(this.camera);const h=(s.x+1)/2*o,f=(s.y+1)/2*a;let g=0,p=1;typeof this.clipArea=="number"?p=this.clipArea:this.clipArea.endsWith("%")?p=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(g=parseFloat(this.clipArea));const y=d.scale.x*p+.5,w=d.scale.y*p+.5,C=h-y/2,O=f-w/2,A=(C*this.qualityFactor-g)/c,S=(O*this.qualityFactor-g)/c,R=(y*this.qualityFactor+g*2)/c,E=(w*this.qualityFactor+g*2)/c;this.renderer.setScissor(A,S,R,E),this.renderer.render(this.scene,this.camera)}this.renderer.setScissorTest(!1),this.renderer.autoClear=!0,this.renderer.setRenderTarget(null),this.camera.layers.set(this.getSceneLayer()),this.renderer.setClearColor(i,l)}render(){for(let e=0;e<_.MAX_LAYERS;e++){const t=e+1;this.captureRenderTarget(this.travelersByLayer[e],N.getCaptureLayer(t),this.renderTargets[e])}this.renderer.render(this.scene,this.camera)}syncMeshesByDOM(){const e=this.targetRect.left+window.scrollX,t=this.targetRect.top+window.scrollY,r=this.renderer.getPixelRatio(),i=this.renderer.domElement.width/r,l=this.renderer.domElement.height/r;this.scene.children.forEach(s=>{var h,f;const o=s;if(!o.userData||!o.userData.domElement)return;const a=o.userData.domElement;if(!a.isConnected)return;let c;if(a.nodeType===Node.TEXT_NODE){const g=document.createRange();g.selectNode(a),c=g.getBoundingClientRect()}else c=a.getBoundingClientRect();const d=o.userData.domRect;if(!d||Math.abs(c.x-d.x)>.5||Math.abs(c.y-d.y)>.5||Math.abs(c.width-d.width)>.5||Math.abs(c.height-d.height)>.5){o.userData.domRect={x:c.x,y:c.y,width:c.width,height:c.height};let g,p;if(this.isViewport)g=c.x-window.innerWidth/2+c.width/2,p=-c.y+window.innerHeight/2-c.height/2;else{const w=c.x-e,C=c.y-t;g=w-i/2+c.width/2,p=-C+l/2-c.height/2}o.position.setX(g),o.position.setY(p);let y=((h=o.material.userData)==null?void 0:h.shadowPadding)||0;if(o.scale.set(c.width+y*2,c.height+y*2,1),o.updateMatrixWorld(),o.material instanceof v.ShaderMaterial&&G.forceUpdateUniforms(o.material,{width:c.width,height:c.height}),o.userData.nativeMesh){const w=o.userData.nativeMesh;let C=c.width,O=c.height,A=g,S=p;if(o.userData.nativeTransform){const E=o.userData.nativeTransform,$=E.match(/scale\(([\d.]+%?)\)/);if($){let M=parseFloat($[1]);$[1].includes("%")&&(M/=100),C*=M,O*=M}const W=E.match(/scaleX\(([\d.]+%?)\)/);if(W){let M=parseFloat(W[1]);W[1].includes("%")&&(M/=100),C*=M}const L=E.match(/scaleY\(([\d.]+%?)\)/);if(L){let M=parseFloat(L[1]);L[1].includes("%")&&(M/=100),O*=M}const K=E.match(/translate\(([^,]+),\s*([^)]+)\)/);if(K){const M=K[1].trim(),X=K[2].trim();let Q=parseFloat(M);M.includes("%")&&(Q=Q/100*c.width);let ee=parseFloat(X);X.includes("%")&&(ee=ee/100*c.height),A+=Q,S-=ee}const te=E.match(/translateX\(([^)]+)\)/);if(te){const M=te[1].trim();let X=parseFloat(M);M.includes("%")&&(X=X/100*c.width),A+=X}const re=E.match(/translateY\(([^)]+)\)/);if(re){const M=re[1].trim();let X=parseFloat(M);M.includes("%")&&(X=X/100*c.height),S-=X}}let R=((f=w.material.userData)==null?void 0:f.shadowPadding)||0;w.position.setX(A),w.position.setY(S),w.scale.set(C+R*2,O+R*2,1),w.updateMatrixWorld(),w.material instanceof v.ShaderMaterial&&G.forceUpdateUniforms(w.material,{width:C,height:O})}}})}}function tt(n){const e=n.textContent||"",t=[];let r="",i=null,l=-1;const s=(c,d)=>{for(let h=0;h<c.length;h++){const f=c[h],g=document.createRange();g.setStart(n,d+h),g.setEnd(n,d+h+1);const p=g.getBoundingClientRect();if(p.width===0&&p.height===0){r+=f;continue}l===-1||Math.abs(p.top-l)>p.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=f,i={left:p.left,top:p.top,right:p.right,bottom:p.bottom},l=p.top):(r+=f,i&&(i.left=Math.min(i.left,p.left),i.top=Math.min(i.top,p.top),i.right=Math.max(i.right,p.right),i.bottom=Math.max(i.bottom,p.bottom)))}},o=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let a=0;for(const c of o){const d=document.createRange();d.setStart(n,a),d.setEnd(n,a+c.length);const h=d.getClientRects();if(h.length>1)s(c,a);else{const f=h.length===1?h[0]:d.getBoundingClientRect();if(f.width===0&&f.height===0){r+=c,a+=c.length;continue}l===-1||Math.abs(f.top-l)>f.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=c,i={left:f.left,top:f.top,right:f.right,bottom:f.bottom},l=f.top):(r+=c,i&&(i.left=Math.min(i.left,f.left),i.top=Math.min(i.top,f.top),i.right=Math.max(i.right,f.right),i.bottom=Math.max(i.bottom,f.bottom)))}a+=c.length}return r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),t.filter(c=>c.text.trim().length>0&&c.rect.width>0&&c.rect.height>0)}function Oe(n){const e=parseFloat(n.fontSize);let t=parseFloat(n.lineHeight);isNaN(t)&&(t=e*1.2);let r=parseFloat(n.letterSpacing);return isNaN(r)&&(r=0),{font:`${n.fontStyle} ${n.fontWeight} ${n.fontSize} ${n.fontFamily}`,fontSize:n.fontSize,color:n.color,textAlign:n.textAlign||"start",textBaseline:"alphabetic",direction:n.direction||"inherit",lineHeight:t,letterSpacing:r}}function Ue(n,e=se|fe|Xe|we|ve,t,r=1,i=0,l=2,s,o){var X,Q,ee,H,q,ce,he;if(n.nodeType===Node.TEXT_NODE){const m=n;if(!m.textContent||!m.textContent.trim())return null;const k=m.textContent.replace(/\s+/g," ");if(k.length===0)return null;const z=tt(m);if(z.length===0)return null;const b=m.parentElement,x=b?window.getComputedStyle(b):null;if(!x)return null;const P=Math.min(...z.map(T=>T.rect.left)),V=Math.min(...z.map(T=>T.rect.top)),ie=Math.max(...z.map(T=>T.rect.left+T.rect.width)),U=Math.max(...z.map(T=>T.rect.top+T.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:m,rect:{x:P+window.scrollX,y:V+window.scrollY,width:ie-P,height:U-V},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:b&&b.dataset[Z.KEY]===Z.VALUES.HIDE?1:parseFloat(x.opacity),zIndex:(isNaN(parseInt(x.zIndex))?0:parseInt(x.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:k,textLines:z.map(T=>({text:T.text.trim(),rect:{x:T.rect.left+window.scrollX,y:T.rect.top+window.scrollY,width:T.rect.width,height:T.rect.height}})),textStyles:Oe(x),dirtyMask:e,visibility:t,isTraveler:!1,captureLayer:r,isFixed:x.position==="fixed",nativeLayer:s,nativeStyles:o?ne(ne({backgroundColor:"transparent",backgroundImage:"",opacity:b&&b.dataset[Z.KEY]===Z.VALUES.HIDE?1:parseFloat(x.opacity),zIndex:(isNaN(parseInt(x.zIndex))?0:parseInt(x.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},Oe(x)),o):void 0,nativeRect:o?{x:P+window.scrollX,y:V+window.scrollY,width:ie-P,height:U-V}:void 0,children:[]}}if(n.nodeType!==Node.ELEMENT_NODE)return null;const a=n,c=a.dataset[F.KEY];let d=t,h=t;if(c){const m=new Set(c.split(/\s+/));for(const k of m)if(!Le.includes(k))throw new Error(`[MirageEngine] Invalid filter token: '${k}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(m.has(F.VALUES.END))return null;if(m.has(F.VALUES.INCLUDE_TREE)&&m.has(F.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(m.has(F.VALUES.INCLUDE_SELF)&&m.has(F.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");m.has(F.VALUES.INCLUDE_TREE)?d=d|j:m.has(F.VALUES.EXCLUDE_TREE)&&(d=d&~j),h=d,m.has(F.VALUES.INCLUDE_SELF)?h=h|j:m.has(F.VALUES.EXCLUDE_SELF)&&(h=h&~j)}const f=a.dataset[Y.KEY];if(f){const m=new Set(f.split(/\s+/));for(const k of m)if(!Le.includes(k))throw new Error(`[MirageEngine] Invalid select token: '${k}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(m.has(Y.VALUES.END))return null;if(m.has(Y.VALUES.INCLUDE_TREE)&&m.has(Y.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting selects: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(m.has(Y.VALUES.INCLUDE_SELF)&&m.has(Y.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting selects: 'include-self' and 'exclude-self' cannot be used together on the same element.");m.has(Y.VALUES.INCLUDE_TREE)?d=d|oe:m.has(Y.VALUES.EXCLUDE_TREE)&&(d=d&~oe),h=d,m.has(Y.VALUES.INCLUDE_SELF)?h=h|oe:m.has(Y.VALUES.EXCLUDE_SELF)&&(h=h&~oe)}const g=a.dataset[_.KEY];let p=!1,y=o?ne({},o):{},w=s;if(g){let m=1;const k=g.indexOf("{"),z=g.lastIndexOf("}");let b=g;if(k!==-1&&z!==-1&&z>k){b=g.substring(0,k).trim();const U=g.substring(k,z+1);try{y=new Function("return "+U)()}catch(T){console.warn(`[MirageEngine] Failed to parse travel styles JSON: ${U}`)}}const x=b.split(/\s+/);let P=!1;const V=x.indexOf(_.VALUES.TRAVELER);if(V!==-1){p=!0,P=!0;const U=x[V+1];if(U&&!isNaN(parseInt(U,10)))m=parseInt(U,10);else{const T=x.find(de=>!isNaN(parseInt(de,10)));T&&(m=parseInt(T,10))}}const ie=x.indexOf(_.VALUES.NATIVE);if(ie!==-1){const U=x[ie+1];if(U&&!isNaN(parseInt(U,10)))w=parseInt(U,10);else if(!p){const T=x.find(de=>!isNaN(parseInt(de,10)));T&&(w=parseInt(T,10))}}if(P){const U=m+1;if(U<r)throw new Error(`[MirageEngine] Traveler layer (${m}) cannot be smaller than inherited capture layer (${r-1}).`);r=Math.min(U,_.MAX_LAYERS+1)}}const C=a.dataset[Ne.KEY];let O;C&&(O=JSON.parse(C));const A=a.getBoundingClientRect(),S=window.getComputedStyle(a);if(A.width===0||A.height===0||S.display==="none")return null;let R=a.getAttribute("data-mid");R||(R=Math.random().toString(36).substring(2,11),a.setAttribute("data-mid",R));const E=parseInt(S.zIndex),$=(isNaN(E)?0:E)+i;let W;if(a.tagName==="IMG")W=a.src;else if(a.tagName.toLowerCase()==="svg"){const m=a.cloneNode(!0),k=y==null?void 0:y.color,z=y==null?void 0:y.fill,b=y==null?void 0:y.stroke,x=y==null?void 0:y.opacity,P=(T,de)=>{const J=window.getComputedStyle(T),ge=de,lt=J.fill===J.color,ct=J.stroke===J.color,xe=z||(lt?k:void 0)||J.fill;xe&&xe!=="none"&&(ge.style.fill=xe);const Se=b||(ct?k:void 0)||J.stroke;Se&&Se!=="none"&&(ge.style.stroke=Se),J.strokeWidth&&J.strokeWidth!=="0px"&&(ge.style.strokeWidth=J.strokeWidth);const Be=k||J.color;Be&&(ge.style.color=Be);const Ee=x||J.opacity;Ee&&Ee!=="1"&&(ge.style.opacity=Ee);for(let ye=0;ye<T.children.length;ye++)P(T.children[ye],de.children[ye])};P(a,m);const V=a.getBoundingClientRect(),ie=window.devicePixelRatio*l;m.hasAttribute("viewBox")||m.setAttribute("viewBox",`0 0 ${V.width} ${V.height}`),m.setAttribute("width",(V.width*ie).toString()),m.setAttribute("height",(V.height*ie).toString());let U=new XMLSerializer().serializeToString(m);U.includes("xmlns=")||(U=U.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),W=`data:image/svg+xml;utf8,${encodeURIComponent(U)}`}else if(S.backgroundImage&&S.backgroundImage!=="none"){const m=S.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);m&&(W=m[1])}const L={backgroundColor:S.backgroundColor,backgroundImage:S.backgroundImage,opacity:a.dataset[Z.KEY]===Z.VALUES.HIDE?1:parseFloat(S.opacity),zIndex:$,borderRadius:S.borderRadius,borderColor:S.borderColor,borderWidth:S.borderWidth,boxShadow:S.boxShadow,imageSrc:W,isTraveler:p},K=L;let te,re;const M=[];return a.tagName.toLowerCase()!=="svg"&&Array.from(a.childNodes).forEach(m=>{const k=m.nodeType===Node.TEXT_NODE?h:d,z=Ue(m,e,k,r,$,l,m.nodeType===Node.TEXT_NODE?w:void 0,m.nodeType===Node.TEXT_NODE&&Object.keys(y).length>0?y:void 0);z&&M.push(z)}),{id:R,type:"BOX",element:a,rect:{x:A.left+window.scrollX,y:A.top+window.scrollY,width:A.width,height:A.height},styles:K,textContent:te,textStyles:re,dirtyMask:e,visibility:h,isTraveler:p,captureLayer:r,nativeLayer:w,nativeStyles:w!==void 0?_e(ne({},L),{backgroundColor:(X=y.backgroundColor)!=null?X:L.backgroundColor,backgroundImage:(Q=y.backgroundImage)!=null?Q:L.backgroundImage,opacity:(ee=y.opacity)!=null?ee:L.opacity,zIndex:y.zIndex!==void 0?y.zIndex+$:L.zIndex,borderRadius:(H=y.borderRadius)!=null?H:L.borderRadius,borderColor:(q=y.borderColor)!=null?q:L.borderColor,borderWidth:(ce=y.borderWidth)!=null?ce:L.borderWidth,boxShadow:(he=y.boxShadow)!=null?he:L.boxShadow,isTraveler:L.isTraveler,transform:y.transform}):void 0,nativeRect:w!==void 0?{x:y.x!==void 0?parseFloat(y.x):A.left+window.scrollX,y:y.y!==void 0?parseFloat(y.y):A.top+window.scrollY,width:y.width!==void 0?parseFloat(y.width):A.width,height:y.height!==void 0?parseFloat(y.height):A.height}:void 0,isFixed:S.position==="fixed",children:M,shaderHooks:O}}function rt(n,e){e.size!==0&&e.forEach((t,r)=>{var l,s,o,a;const i=n.get(r);!i||!i.userData.basePosition||(G.forceUpdateUniforms(i.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(s=t.borderRadius)!=null?s:(l=i.userData.baseStyles)==null?void 0:l.borderRadius}),i.userData.nativeMesh&&G.forceUpdateUniforms(i.userData.nativeMesh.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(a=t.borderRadius)!=null?a:(o=i.userData.baseStyles)==null?void 0:o.borderRadius}))})}class it{constructor(e,t,r,i){u(this,"target");u(this,"renderer");u(this,"registry");u(this,"isTravelEnabled",!1);u(this,"tracker");this.target=e,this.renderer=t,this.registry=r,this.tracker=new Re(e,{resizeDebounce:i.resizeDebounce}),this.tracker.onLayoutChange.add((l,s)=>{document.querySelector(`[${_.NAME}~='${_.VALUES.TRAVELER}']`)!==null&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const a=Ue(this.target,l,j,1,0,this.renderer.qualityFactor);a&&this.renderer.syncScene(a,s)}),this.tracker.onStyleChange.add(l=>{rt(this.registry,l)}),this.tracker.onRender.add(()=>{this.renderer.syncMeshesByDOM(),this.renderer.render()})}start(){this.tracker.start()}stop(){this.tracker.stop()}}class st{constructor(){u(this,"store");this.store=new WeakMap}register(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}has(e){return this.store.has(e)}remove(e){this.store.delete(e)}}class nt{constructor(e,t){u(this,"renderer");u(this,"syncer");u(this,"target");u(this,"registry");var i,l,s;if(this.target=e,this.registry=new st,!document.getElementById("mirage-engine-styles")){const o=document.createElement("style");o.id="mirage-engine-styles",o.textContent=`
|
|
185
|
+
[${Z.NAME}="${Z.VALUES.HIDE}"] {
|
|
166
186
|
opacity: 0 !important;
|
|
167
187
|
}
|
|
168
|
-
`,document.head.appendChild(
|
|
188
|
+
`,document.head.appendChild(o)}let r;if(t.mode==="duplicate"?r=(l=(i=t.container)!=null?i:this.target.parentElement)!=null?l:void 0:r=(s=this.target.parentElement)!=null?s:void 0,!r)throw new Error("[Mirage] Cannot find a container (parent or option).");this.renderer=new et(this.target,t,r,this.registry),this.renderer.mount(),this.syncer=new it(this.target,this.renderer,this.registry,t)}start(){this.syncer.start()}stop(){this.syncer.stop()}dispose(){this.syncer.stop(),this.renderer.dispose()}getTracker(){return this.syncer.tracker}updateUniforms(e,t){this.renderer.updateUniforms(e,t)}getCanvas(){return this.renderer.canvas}test(){const e=this.registry.get(document.querySelector("#box2"));if(!e)return;const t={ArrowRight:!1,ArrowLeft:!1,ArrowUp:!1,ArrowDown:!1};window.addEventListener("keydown",l=>{t[l.key]!==void 0&&(t[l.key]=!0)}),window.addEventListener("keyup",l=>{t[l.key]!==void 0&&(t[l.key]=!1)});const r=2,i=()=>{requestAnimationFrame(i),t.ArrowRight&&e.position.setX(e.position.x+r),t.ArrowLeft&&e.position.setX(e.position.x-r),t.ArrowUp&&e.position.setY(e.position.y+r),t.ArrowDown&&e.position.setY(e.position.y-r)};i()}}class ot{constructor(e={}){u(this,"frontSelector");u(this,"midLayerElement");u(this,"items",[]);u(this,"isInitialized",!1);u(this,"midLayer",null);u(this,"frontLayer",null);u(this,"tracker",null);this.frontSelector=e.frontSelector||".front",this.midLayerElement=e.midLayerElement||null,this.items=[],this.isInitialized=!1,this.tracker=new Re(document.body,e.trackerConfig||{resizeDebounce:!0})}init(){var e;this.isInitialized||(this.createLayers(),this.setupMidLayer(),this.hijackFrontElements(),this.setupHooks(),(e=this.tracker)==null||e.start(),this.isInitialized=!0,console.log("🥪 sand-telepochi initialized!"))}useTracker(e){this.tracker=e,this.setupHooks()}createLayers(){this.midLayer=document.createElement("div"),this.midLayer.id="sand-layer-mid",Object.assign(this.midLayer.style,{position:"fixed",inset:"0",zIndex:"9998",pointerEvents:"none"}),this.frontLayer=document.createElement("div"),this.frontLayer.id="sand-layer-front",Object.assign(this.frontLayer.style,{position:"fixed",inset:"0",zIndex:"9999",pointerEvents:"none"}),document.body.appendChild(this.midLayer),document.body.appendChild(this.frontLayer)}setupMidLayer(){this.midLayerElement&&this.midLayer&&(this.midLayer.appendChild(this.midLayerElement),this.midLayerElement.style.pointerEvents="auto")}hijackFrontElements(){const e=document.querySelectorAll(this.frontSelector);this.frontLayer&&e.forEach(t=>{var s;const r=t.getBoundingClientRect(),i=window.getComputedStyle(t),l=document.createElement("div");l.className="sand-placeholder",Object.assign(l.style,{display:i.display==="inline"?"inline-block":i.display,width:`${r.width}px`,height:`${r.height}px`,boxSizing:"border-box",marginTop:i.marginTop,marginBottom:i.marginBottom,marginLeft:i.marginLeft,marginRight:i.marginRight,visibility:"hidden",pointerEvents:"none"}),(s=t.parentNode)==null||s.insertBefore(l,t),this.frontLayer.appendChild(t),Object.assign(t.style,{position:"fixed",margin:"0",boxSizing:"border-box",width:`${r.width}px`,height:`${r.height}px`,pointerEvents:"auto"}),this.items.push({placeholder:l,original:t})})}setupHooks(){this.tracker&&this.tracker.onBeforeRender.add(()=>{const e=this.items.map(({placeholder:t})=>t.getBoundingClientRect());this.items.forEach(({original:t},r)=>{const i=e[r];t.style.top=`${i.top}px`,t.style.left=`${i.left}px`,t.style.width=`${i.width}px`,t.style.height=`${i.height}px`})})}}class at{constructor(e,t){u(this,"_engine");u(this,"_sandwich");if(!e)throw new Error("[Mirage] Target element is required.");if(this._engine=new nt(e,t),t.sandwich!==!1){const r=typeof t.sandwich=="object"?t.sandwich:{};this._sandwich=new ot({frontSelector:r.frontSelector||`[${Te.NAME}='${Te.VALUES.FRONT}']`}),this._sandwich.useTracker(this._engine.getTracker())}}start(){this._engine.start(),this._sandwich&&this._sandwich.init()}stop(){this._engine.stop()}destroy(){this._engine.dispose()}getTracker(){return this._engine.getTracker()}getCanvas(){return this._engine.getCanvas()}updateUniforms(e,t){this._engine.updateUniforms(e,t)}test(){this._engine.test()}}I.Mirage=at,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mirage-engine",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.15",
|
|
4
4
|
"description": "An engine that mirrors HTML DOM elements to a WebGL scene in real-time.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -21,9 +21,9 @@
|
|
|
21
21
|
"dist"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@mirage-engine/
|
|
24
|
+
"@mirage-engine/core": "0.3.15",
|
|
25
25
|
"@mirage-engine/sandwich": "0.2.8",
|
|
26
|
-
"@mirage-engine/
|
|
26
|
+
"@mirage-engine/painter": "1.0.5"
|
|
27
27
|
},
|
|
28
28
|
"peerDependencies": {
|
|
29
29
|
"three": "^0.160.0"
|