@origintrail-official/dkg-node-ui 10.0.24 → 10.0.25
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-ui/assets/ActivityFeed-vyl2XdLo.js +99 -0
- package/dist-ui/assets/{AgentHub-BO9jGbJl.js → AgentHub-CYfAoOWF.js} +1 -1
- package/dist-ui/assets/AgentProfilePage-BjQm0je4.js +1 -0
- package/dist-ui/assets/{ApproveWalletsModal-C2Tu29tB.js → ApproveWalletsModal-CzWJ4KyU.js} +3 -3
- package/dist-ui/assets/{ContextGraphPrimitives-BqlTIZHy.js → ContextGraphPrimitives-ecppTns4.js} +1 -1
- package/dist-ui/assets/{ConvictionDetailView-J-DAKHtP.js → ConvictionDetailView-CuLUhbzR.js} +2 -2
- package/dist-ui/assets/MemoryLayerView-Dymg_Zf_.js +2 -0
- package/dist-ui/assets/MemoryReadStatus-D4HXCImC.js +1 -0
- package/dist-ui/assets/MemoryStackView-Bq8Fbh5W.js +1 -0
- package/dist-ui/assets/{Network-DV9K48MH.js → Network-F76S9_1V.js} +1 -1
- package/dist-ui/assets/{OnChainProvenanceCard-jxk66g53.js → OnChainProvenanceCard-CCwK3sRG.js} +1 -1
- package/dist-ui/assets/{Operations-CNB1BMYg.js → Operations-aVCBUh8u.js} +1 -1
- package/dist-ui/assets/ProjectView-Cb1PQ-jm.js +290 -0
- package/dist-ui/assets/{PublishingConviction-DbP1i3v0.js → PublishingConviction-BnAJjHL8.js} +2 -2
- package/dist-ui/assets/{Settings-I6g3MQCV.js → Settings-rEyPw1oS.js} +1 -1
- package/dist-ui/assets/{browserWalletTransaction-CXv612Pn.js → browserWalletTransaction-BJBFRjXx.js} +3 -3
- package/dist-ui/assets/{ccip-DY93ay8e.js → ccip-DYOqJfs7.js} +1 -1
- package/dist-ui/assets/{index-CIt7zWgM.css → index-CAdbSAQK.css} +1 -1
- package/dist-ui/assets/index-HEpqHVfE.js +1143 -0
- package/dist-ui/assets/index-_vQ99L0s.js +192 -0
- package/dist-ui/assets/{jsonld-32FQRO67-DKLfQ_nD.js → jsonld-32FQRO67-DVqZhSL_.js} +2 -2
- package/dist-ui/assets/{jsonld-BgpgXlDQ.js → jsonld-Dpm03cay.js} +1 -1
- package/dist-ui/assets/renderer-3d-IRPVRQWX-DjW_h88e.js +5126 -0
- package/dist-ui/assets/{shikiHighlighter-BXl6qMQO.js → shikiHighlighter-DL7LOds2.js} +4 -4
- package/dist-ui/assets/truncate-BWdqLeqV.js +22 -0
- package/dist-ui/assets/{useEntityOnChainReceipt-CUGQNIsP.js → useEntityOnChainReceipt-B_uLyqZc.js} +5 -5
- package/dist-ui/index.html +2 -2
- package/package.json +4 -4
- package/dist-ui/assets/3d-force-graph-DvzZZzFn.js +0 -1015
- package/dist-ui/assets/ActivityFeed-B5QxV1dk.js +0 -99
- package/dist-ui/assets/AgentProfilePage-DJJTn1WD.js +0 -1
- package/dist-ui/assets/MemoryLayerView-BOxI-_TF.js +0 -2
- package/dist-ui/assets/MemoryStackView-BTyZZKNm.js +0 -1
- package/dist-ui/assets/ProjectView-BP4vNSXI.js +0 -290
- package/dist-ui/assets/index-CumB6j2m.js +0 -192
- package/dist-ui/assets/index-DW3dBcQk.js +0 -1175
- package/dist-ui/assets/renderer-3d-2EVDZII7-BCmzI8Ii.js +0 -2
- package/dist-ui/assets/three.module-BXIk8GZS.js +0 -4112
- package/dist-ui/assets/truncate-BaiMkAOo.js +0 -1
- package/dist-ui/assets/useProjectActivity-BOgGdtS7.js +0 -1
|
@@ -1,1015 +0,0 @@
|
|
|
1
|
-
import{v as Po,c8 as Lh,aG as Qe,cD as _n,cX as ce,br as bl,cY as V,aM as St,o as si,aO as kt,ct as _l,r as Dt,aQ as Uh,n as Yi,ax as cm,ae as Oh,K as Ih,l as kh,F as dm,bv as hm,ay as Gh,u as fm,cJ as pm,db as z,af as it,cm as xl,ba as cs,bo as Vh,co as Tl,dd as $h,dc as Oe,d6 as k,s as Ge,cd as Ss,aA as vt,bD as It,cZ as ze,a7 as gm,a6 as mm,B as ot,a5 as hs,T as xn,cW as Or,c_ as uo,cI as Zt,t as Ns,bt as ym,S as zh,c9 as bm,cv as vl,i as Wh,ag as _m,aw as xm,aE as Tm,cc as vm,C as Sm,A as Nm,d as Rm,b3 as wm,p as Ws,cO as ht,cr as js,cV as ds,al as st,cS as Ve,a3 as rt,e as jh,ca as Fo,cb as Do,P as Tn,Q as vn,c5 as Jt,c6 as Lo,b_ as Uo,b$ as qh,cT as Hh,cU as Xh,cQ as Sn,cR as Sl,cP as Nl,a0 as Oo,a4 as Kh,R as nn,bq as Hr,j as Em,bs as Am,aP as On,J as qs,a as pn,d3 as Un,bw as Js,d2 as Cm,_ as Rl,$ as wl,E as yu,W as lo,cn as ae,aL as ri,bn as El,aH as dc,bB as Io,d1 as Xr,d5 as Mm,d8 as co,aY as ko,q as Kr,ce as Go,aB as fs,aC as bu,b1 as Yr,b2 as Yh,b0 as xt,be as Qh,a8 as ho,aa as er,X as Zh,as as ii,aq as Al,f as Jh,b4 as ef,aF as hc,b8 as tr,d7 as Bm,cg as tf,cB as nf,bj as sf,bk as rf,bl as of,bm as af,U as uf,V as lf,cy as cf,cx as df,cz as hf,bi as ff,I as Pm,G as Fm,H as Dm,aI as pf,b7 as Nn,a_ as ks,cC as Gs,c as Vs,bb as gn,bf as gf,a9 as mf,ab as yf,Y as bf,at as _f,ar as xf,g as Tf,b5 as vf,bE as Cl,c4 as Qi,bX as Zi,bY as Ji,bZ as eo,c3 as fc,c2 as pc,bW as gc,bV as mc,c0 as _u,c1 as xu,bU as Tu,bx as vu,ci as Su,bC as fo,cl as Nu,bL as Ru,bM as wu,bN as Eu,bO as Au,bP as Cu,bQ as Mu,bR as Bu,bS as Pu,bG as Fu,bH as Du,bI as Lu,bF as Uu,bJ as Ou,bK as Iu,bT as ku,bA as Gu,ck as Vu,bz as po,cj as $u,M as Sf,aT as Lm,aV as Um,aU as Om,aW as Im,aS as km,aR as Gm,az as Vm,bu as $m,cw as zm,cq as Wm,by as jm,D as Vo,cF as Ml,cK as qm,cM as Hm,cL as Xm,a2 as go,bg as Km,ad as Ym,ac as Qm,Z as Zm,au as Jm,av as ey,h as ty,b6 as ny,O as sy,ai as ry,N as iy,ah as oy,ao as ay,cf as uy,d4 as ly,ap as cy,aN as dy,aX as hy,ch as Nf,a1 as Rf,b as fy,aZ as py,a$ as gy,aJ as mo,bd as wf,aK as Ef,m as Af,w as my,k as yy,x as by,cs as _y,bp as xy,y as yo,z as bo,cE as ia,b9 as oa,bc as Ty,bh as vy,aj as Sy,ak as Ny,L as Ry,cA as Bl,aD as wy,an as Ey,am as Ay,d9 as Cy,cu as yc,c7 as My,cp as bc,cN as By,c$ as Py,cH as Cf,cG as Fy,d0 as Dy}from"./three.module-BXIk8GZS.js";import{aA as Ly}from"./index-DW3dBcQk.js";import{i as fe,s as Uy,e as Pl,c as Oy,d as Iy,a as ky,b as Gy,f as Vy,t as Mf,g as $y,G as zy,T as _c,E as xc}from"./index-CumB6j2m.js";import{o as Wy,h as jy,m as qy}from"./string-DtUow4KV.js";const Hs=new bl,mn=new ce,Bf=new V,aa=new ce,to=new ce,_o=new V,zu=new V,Pf=new St,Ff=new V,Df=new V;let nt=null,qt=null;const yn=[],$n={NONE:-1,PAN:0,ROTATE:1};class Hy extends Po{constructor(e,t,n=null){super(t,n),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new Lh,this.mouseButtons={LEFT:Qe.PAN,MIDDLE:Qe.PAN,RIGHT:Qe.ROTATE},this.touches={ONE:_n.PAN},this._onPointerMove=Xy.bind(this),this._onPointerDown=Ky.bind(this),this._onPointerCancel=Yy.bind(this),this._onContextMenu=Qy.bind(this),n!==null&&this.connect(n)}connect(e){super.connect(e),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerCancel),this.domElement.addEventListener("pointerleave",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerCancel),this.domElement.removeEventListener("pointerleave",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="",this.domElement.style.cursor=""}dispose(){this.disconnect()}_updatePointer(e){const t=this.domElement.getBoundingClientRect();mn.x=(e.clientX-t.left)/t.width*2-1,mn.y=-(e.clientY-t.top)/t.height*2+1}_updateState(e){let t;if(e.pointerType==="touch")t=this.touches.ONE;else switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=null}switch(t){case Qe.PAN:case _n.PAN:this.state=$n.PAN;break;case Qe.ROTATE:case _n.ROTATE:this.state=$n.ROTATE;break;default:this.state=$n.NONE}}}function Xy(i){const e=this.object,t=this.domElement,n=this.raycaster;if(this.enabled!==!1){if(this._updatePointer(i),n.setFromCamera(mn,e),nt)this.state===$n.PAN?n.ray.intersectPlane(Hs,_o)&&(nt.position.copy(_o.sub(Bf).applyMatrix4(Pf)),this.dispatchEvent({type:"drag",object:nt})):this.state===$n.ROTATE&&(aa.subVectors(mn,to).multiplyScalar(this.rotateSpeed),nt.rotateOnWorldAxis(Ff,aa.x),nt.rotateOnWorldAxis(Df.normalize(),-aa.y),this.dispatchEvent({type:"drag",object:nt})),to.copy(mn);else if(i.pointerType==="mouse"||i.pointerType==="pen")if(yn.length=0,n.setFromCamera(mn,e),n.intersectObjects(this.objects,this.recursive,yn),yn.length>0){const s=yn[0].object;Hs.setFromNormalAndCoplanarPoint(e.getWorldDirection(Hs.normal),zu.setFromMatrixPosition(s.matrixWorld)),qt!==s&&qt!==null&&(this.dispatchEvent({type:"hoveroff",object:qt}),t.style.cursor="auto",qt=null),qt!==s&&(this.dispatchEvent({type:"hoveron",object:s}),t.style.cursor="pointer",qt=s)}else qt!==null&&(this.dispatchEvent({type:"hoveroff",object:qt}),t.style.cursor="auto",qt=null);to.copy(mn)}}function Ky(i){const e=this.object,t=this.domElement,n=this.raycaster;this.enabled!==!1&&(this._updatePointer(i),this._updateState(i),yn.length=0,n.setFromCamera(mn,e),n.intersectObjects(this.objects,this.recursive,yn),yn.length>0&&(this.transformGroup===!0?nt=Lf(yn[0].object):nt=yn[0].object,Hs.setFromNormalAndCoplanarPoint(e.getWorldDirection(Hs.normal),zu.setFromMatrixPosition(nt.matrixWorld)),n.ray.intersectPlane(Hs,_o)&&(this.state===$n.PAN?(Pf.copy(nt.parent.matrixWorld).invert(),Bf.copy(_o).sub(zu.setFromMatrixPosition(nt.matrixWorld)),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:nt})):this.state===$n.ROTATE&&(Ff.set(0,1,0).applyQuaternion(e.quaternion).normalize(),Df.set(1,0,0).applyQuaternion(e.quaternion).normalize(),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:nt})))),to.copy(mn))}function Yy(){this.enabled!==!1&&(nt&&(this.dispatchEvent({type:"dragend",object:nt}),nt=null),this.domElement.style.cursor=qt?"pointer":"auto",this.state=$n.NONE)}function Qy(i){this.enabled!==!1&&i.preventDefault()}function Lf(i,e=null){return i.isGroup&&(e=i),i.parent===null?e:Lf(i.parent,e)}function Zy(i){eb(i);const e=Jy(i);return i.on=e.on,i.off=e.off,i.fire=e.fire,i}function Jy(i){let e=Object.create(null);return{on:function(t,n,s){if(typeof n!="function")throw new Error("callback is expected to be a function");let r=e[t];return r||(r=e[t]=[]),r.push({callback:n,ctx:s}),i},off:function(t,n){if(typeof t>"u")return e=Object.create(null),i;if(e[t])if(typeof n!="function")delete e[t];else{const o=e[t];for(let a=0;a<o.length;++a)o[a].callback===n&&o.splice(a,1)}return i},fire:function(t){const n=e[t];if(!n)return i;let s;arguments.length>1&&(s=Array.prototype.slice.call(arguments,1));for(let r=0;r<n.length;++r){const o=n[r];o.callback.apply(o.ctx,s)}return i}}}function eb(i){if(!i)throw new Error("Eventify cannot use falsy object as events subject");const e=["on","fire","off"];for(let t=0;t<e.length;++t)if(i.hasOwnProperty(e[t]))throw new Error("Subject cannot be eventified, since it already has property '"+e[t]+"'")}function tb(i){if(i=i||{},"uniqueLinkId"in i&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n",`
|
|
2
|
-
`,`Note: there is also change in default behavior: From now on each graph
|
|
3
|
-
is considered to be not a multigraph by default (each edge is unique).`),i.multigraph=i.uniqueLinkId),i.multigraph===void 0&&(i.multigraph=!1),typeof Map!="function")throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var e=new Map,t=new Map,n={},s=0,r=i.multigraph?S:T,o=[],a=F,u=F,l=F,c=F,d={version:20,addNode:g,addLink:_,removeLink:P,removeNode:y,getNode:m,getNodeCount:N,getLinkCount:R,getEdgeCount:R,getLinksCount:R,getNodesCount:N,getLinks:v,forEachNode:ve,forEachLinkedNode:se,forEachLink:re,beginUpdate:l,endUpdate:c,clear:ee,hasLink:L,hasNode:m,getLink:L,getLinkById:j};return Zy(d),h(),d;function h(){var I=d.on;d.on=H;function H(){return d.beginUpdate=l=G,d.endUpdate=c=Q,a=f,u=p,d.on=I,I.apply(d,arguments)}}function f(I,H){o.push({link:I,changeType:H})}function p(I,H){o.push({node:I,changeType:H})}function g(I,H){if(I===void 0)throw new Error("Invalid node identifier");l();var le=m(I);return le?(le.data=H,u(le,"update")):(le=new nb(I,H),u(le,"add")),e.set(I,le),c(),le}function m(I){return e.get(I)}function y(I){var H=m(I);if(!H)return!1;l();var le=H.links;return le&&(le.forEach(D),H.links=null),e.delete(I),u(H,"remove"),c(),!0}function _(I,H,le){l();var Ce=m(I)||g(I),B=m(H)||g(H),U=r(I,H,le),K=t.has(U.id);return t.set(U.id,U),Tc(Ce,U),I!==H&&Tc(B,U),a(U,K?"update":"add"),c(),U}function T(I,H,le){var Ce=hi(I,H),B=t.get(Ce);return B?(B.data=le,B):new vc(I,H,le,Ce)}function S(I,H,le){var Ce=hi(I,H),B=n.hasOwnProperty(Ce);if(B||L(I,H)){B||(n[Ce]=0);var U="@"+ ++n[Ce];Ce=hi(I+U,H+U)}return new vc(I,H,le,Ce)}function N(){return e.size}function R(){return t.size}function v(I){var H=m(I);return H?H.links:null}function P(I,H){return H!==void 0&&(I=L(I,H)),D(I)}function D(I){if(!I||!t.get(I.id))return!1;l(),t.delete(I.id);var H=m(I.fromId),le=m(I.toId);return H&&H.links.delete(I),le&&le.links.delete(I),a(I,"remove"),c(),!0}function L(I,H){if(!(I===void 0||H===void 0))return t.get(hi(I,H))}function j(I){if(I!==void 0)return t.get(I)}function ee(){l(),ve(function(I){y(I.id)}),c()}function re(I){if(typeof I=="function")for(var H=t.values(),le=H.next();!le.done;){if(I(le.value))return!0;le=H.next()}}function se(I,H,le){var Ce=m(I);if(Ce&&Ce.links&&typeof H=="function")return le?oe(Ce.links,I,H):Z(Ce.links,I,H)}function Z(I,H,le){for(var Ce,B=I.values(),U=B.next();!U.done;){var K=U.value,me=K.fromId===H?K.toId:K.fromId;if(Ce=le(e.get(me),K),Ce)return!0;U=B.next()}}function oe(I,H,le){for(var Ce,B=I.values(),U=B.next();!U.done;){var K=U.value;if(K.fromId===H&&(Ce=le(e.get(K.toId),K),Ce))return!0;U=B.next()}}function F(){}function G(){s+=1}function Q(){s-=1,s===0&&o.length>0&&(d.fire("changed",o),o.length=0)}function ve(I){if(typeof I!="function")throw new Error("Function is expected to iterate over graph nodes. You passed "+I);for(var H=e.values(),le=H.next();!le.done;){if(I(le.value))return!0;le=H.next()}}}function nb(i,e){this.id=i,this.links=null,this.data=e}function Tc(i,e){i.links?i.links.add(e):i.links=new Set([e])}function vc(i,e,t,n){this.fromId=i,this.toId=e,this.data=t,this.id=n}function hi(i,e){return i.toString()+"👉 "+e.toString()}var fi={exports:{}},Cs={exports:{}},ua,Sc;function Uf(){return Sc||(Sc=1,ua=function(e){return e===0?"x":e===1?"y":e===2?"z":"c"+(e+1)}),ua}var la,Nc;function ar(){if(Nc)return la;Nc=1;const i=Uf();return la=function(t){return n;function n(s,r){let o=r&&r.indent||0,a=r&&r.join!==void 0?r.join:`
|
|
4
|
-
`,u=Array(o+1).join(" "),l=[];for(let c=0;c<t;++c){let d=i(c),h=c===0?"":u;l.push(h+s.replace(/{var}/g,d))}return l.join(a)}},la}var Rc;function sb(){if(Rc)return Cs.exports;Rc=1;const i=ar();Cs.exports=e,Cs.exports.generateCreateBodyFunctionBody=t,Cs.exports.getVectorCode=s,Cs.exports.getBodyCode=n;function e(r,o){let a=t(r,o),{Body:u}=new Function(a)();return u}function t(r,o){return`
|
|
5
|
-
${s(r,o)}
|
|
6
|
-
${n(r)}
|
|
7
|
-
return {Body: Body, Vector: Vector};
|
|
8
|
-
`}function n(r){let o=i(r),a=o("{var}",{join:", "});return`
|
|
9
|
-
function Body(${a}) {
|
|
10
|
-
this.isPinned = false;
|
|
11
|
-
this.pos = new Vector(${a});
|
|
12
|
-
this.force = new Vector();
|
|
13
|
-
this.velocity = new Vector();
|
|
14
|
-
this.mass = 1;
|
|
15
|
-
|
|
16
|
-
this.springCount = 0;
|
|
17
|
-
this.springLength = 0;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
Body.prototype.reset = function() {
|
|
21
|
-
this.force.reset();
|
|
22
|
-
this.springCount = 0;
|
|
23
|
-
this.springLength = 0;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
Body.prototype.setPosition = function (${a}) {
|
|
27
|
-
${o("this.pos.{var} = {var} || 0;",{indent:2})}
|
|
28
|
-
};`}function s(r,o){let a=i(r),u="";return o&&(u=`${a(`
|
|
29
|
-
var v{var};
|
|
30
|
-
Object.defineProperty(this, '{var}', {
|
|
31
|
-
set: function(v) {
|
|
32
|
-
if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');
|
|
33
|
-
v{var} = v;
|
|
34
|
-
},
|
|
35
|
-
get: function() { return v{var}; }
|
|
36
|
-
});`)}`),`function Vector(${a("{var}",{join:", "})}) {
|
|
37
|
-
${u}
|
|
38
|
-
if (typeof arguments[0] === 'object') {
|
|
39
|
-
// could be another vector
|
|
40
|
-
let v = arguments[0];
|
|
41
|
-
${a('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}
|
|
42
|
-
${a("this.{var} = v.{var};",{indent:4})}
|
|
43
|
-
} else {
|
|
44
|
-
${a('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
Vector.prototype.reset = function () {
|
|
49
|
-
${a("this.{var} = ",{join:""})}0;
|
|
50
|
-
};`}return Cs.exports}var cn={exports:{}},wc;function rb(){if(wc)return cn.exports;wc=1;const i=ar(),e=Uf();cn.exports=t,cn.exports.generateQuadTreeFunctionBody=n,cn.exports.getInsertStackCode=u,cn.exports.getQuadNodeCode=a,cn.exports.isSamePosition=s,cn.exports.getChildBodyCode=o,cn.exports.setChildBodyCode=r;function t(l){let c=n(l);return new Function(c)()}function n(l){let c=i(l),d=Math.pow(2,l);return`
|
|
51
|
-
${u()}
|
|
52
|
-
${a(l)}
|
|
53
|
-
${s(l)}
|
|
54
|
-
${o(l)}
|
|
55
|
-
${r(l)}
|
|
56
|
-
|
|
57
|
-
function createQuadTree(options, random) {
|
|
58
|
-
options = options || {};
|
|
59
|
-
options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;
|
|
60
|
-
options.theta = typeof options.theta === 'number' ? options.theta : 0.8;
|
|
61
|
-
|
|
62
|
-
var gravity = options.gravity;
|
|
63
|
-
var updateQueue = [];
|
|
64
|
-
var insertStack = new InsertStack();
|
|
65
|
-
var theta = options.theta;
|
|
66
|
-
|
|
67
|
-
var nodesCache = [];
|
|
68
|
-
var currentInCache = 0;
|
|
69
|
-
var root = newNode();
|
|
70
|
-
|
|
71
|
-
return {
|
|
72
|
-
insertBodies: insertBodies,
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Gets root node if it is present
|
|
76
|
-
*/
|
|
77
|
-
getRoot: function() {
|
|
78
|
-
return root;
|
|
79
|
-
},
|
|
80
|
-
|
|
81
|
-
updateBodyForce: update,
|
|
82
|
-
|
|
83
|
-
options: function(newOptions) {
|
|
84
|
-
if (newOptions) {
|
|
85
|
-
if (typeof newOptions.gravity === 'number') {
|
|
86
|
-
gravity = newOptions.gravity;
|
|
87
|
-
}
|
|
88
|
-
if (typeof newOptions.theta === 'number') {
|
|
89
|
-
theta = newOptions.theta;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
return this;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
return {
|
|
96
|
-
gravity: gravity,
|
|
97
|
-
theta: theta
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
function newNode() {
|
|
103
|
-
// To avoid pressure on GC we reuse nodes.
|
|
104
|
-
var node = nodesCache[currentInCache];
|
|
105
|
-
if (node) {
|
|
106
|
-
${g(" node.")}
|
|
107
|
-
node.body = null;
|
|
108
|
-
node.mass = ${c("node.mass_{var} = ",{join:""})}0;
|
|
109
|
-
${c("node.min_{var} = node.max_{var} = ",{join:""})}0;
|
|
110
|
-
} else {
|
|
111
|
-
node = new QuadNode();
|
|
112
|
-
nodesCache[currentInCache] = node;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
++currentInCache;
|
|
116
|
-
return node;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
function update(sourceBody) {
|
|
120
|
-
var queue = updateQueue;
|
|
121
|
-
var v;
|
|
122
|
-
${c("var d{var};",{indent:4})}
|
|
123
|
-
var r;
|
|
124
|
-
${c("var f{var} = 0;",{indent:4})}
|
|
125
|
-
var queueLength = 1;
|
|
126
|
-
var shiftIdx = 0;
|
|
127
|
-
var pushIdx = 1;
|
|
128
|
-
|
|
129
|
-
queue[0] = root;
|
|
130
|
-
|
|
131
|
-
while (queueLength) {
|
|
132
|
-
var node = queue[shiftIdx];
|
|
133
|
-
var body = node.body;
|
|
134
|
-
|
|
135
|
-
queueLength -= 1;
|
|
136
|
-
shiftIdx += 1;
|
|
137
|
-
var differentBody = (body !== sourceBody);
|
|
138
|
-
if (body && differentBody) {
|
|
139
|
-
// If the current node is a leaf node (and it is not source body),
|
|
140
|
-
// calculate the force exerted by the current node on body, and add this
|
|
141
|
-
// amount to body's net force.
|
|
142
|
-
${c("d{var} = body.pos.{var} - sourceBody.pos.{var};",{indent:8})}
|
|
143
|
-
r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
|
|
144
|
-
|
|
145
|
-
if (r === 0) {
|
|
146
|
-
// Poor man's protection against zero distance.
|
|
147
|
-
${c("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}
|
|
148
|
-
r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// This is standard gravitation force calculation but we divide
|
|
152
|
-
// by r^3 to save two operations when normalizing force vector.
|
|
153
|
-
v = gravity * body.mass * sourceBody.mass / (r * r * r);
|
|
154
|
-
${c("f{var} += v * d{var};",{indent:8})}
|
|
155
|
-
} else if (differentBody) {
|
|
156
|
-
// Otherwise, calculate the ratio s / r, where s is the width of the region
|
|
157
|
-
// represented by the internal node, and r is the distance between the body
|
|
158
|
-
// and the node's center-of-mass
|
|
159
|
-
${c("d{var} = node.mass_{var} / node.mass - sourceBody.pos.{var};",{indent:8})}
|
|
160
|
-
r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
|
|
161
|
-
|
|
162
|
-
if (r === 0) {
|
|
163
|
-
// Sorry about code duplication. I don't want to create many functions
|
|
164
|
-
// right away. Just want to see performance first.
|
|
165
|
-
${c("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}
|
|
166
|
-
r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
|
|
167
|
-
}
|
|
168
|
-
// If s / r < θ, treat this internal node as a single body, and calculate the
|
|
169
|
-
// force it exerts on sourceBody, and add this amount to sourceBody's net force.
|
|
170
|
-
if ((node.max_${e(0)} - node.min_${e(0)}) / r < theta) {
|
|
171
|
-
// in the if statement above we consider node's width only
|
|
172
|
-
// because the region was made into square during tree creation.
|
|
173
|
-
// Thus there is no difference between using width or height.
|
|
174
|
-
v = gravity * node.mass * sourceBody.mass / (r * r * r);
|
|
175
|
-
${c("f{var} += v * d{var};",{indent:10})}
|
|
176
|
-
} else {
|
|
177
|
-
// Otherwise, run the procedure recursively on each of the current node's children.
|
|
178
|
-
|
|
179
|
-
// I intentionally unfolded this loop, to save several CPU cycles.
|
|
180
|
-
${p()}
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
${c("sourceBody.force.{var} += f{var};",{indent:4})}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
function insertBodies(bodies) {
|
|
189
|
-
${c("var {var}min = Number.MAX_VALUE;",{indent:4})}
|
|
190
|
-
${c("var {var}max = Number.MIN_VALUE;",{indent:4})}
|
|
191
|
-
var i = bodies.length;
|
|
192
|
-
|
|
193
|
-
// To reduce quad tree depth we are looking for exact bounding box of all particles.
|
|
194
|
-
while (i--) {
|
|
195
|
-
var pos = bodies[i].pos;
|
|
196
|
-
${c("if (pos.{var} < {var}min) {var}min = pos.{var};",{indent:6})}
|
|
197
|
-
${c("if (pos.{var} > {var}max) {var}max = pos.{var};",{indent:6})}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// Makes the bounds square.
|
|
201
|
-
var maxSideLength = -Infinity;
|
|
202
|
-
${c("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}
|
|
203
|
-
|
|
204
|
-
currentInCache = 0;
|
|
205
|
-
root = newNode();
|
|
206
|
-
${c("root.min_{var} = {var}min;",{indent:4})}
|
|
207
|
-
${c("root.max_{var} = {var}min + maxSideLength;",{indent:4})}
|
|
208
|
-
|
|
209
|
-
i = bodies.length - 1;
|
|
210
|
-
if (i >= 0) {
|
|
211
|
-
root.body = bodies[i];
|
|
212
|
-
}
|
|
213
|
-
while (i--) {
|
|
214
|
-
insert(bodies[i], root);
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
function insert(newBody) {
|
|
219
|
-
insertStack.reset();
|
|
220
|
-
insertStack.push(root, newBody);
|
|
221
|
-
|
|
222
|
-
while (!insertStack.isEmpty()) {
|
|
223
|
-
var stackItem = insertStack.pop();
|
|
224
|
-
var node = stackItem.node;
|
|
225
|
-
var body = stackItem.body;
|
|
226
|
-
|
|
227
|
-
if (!node.body) {
|
|
228
|
-
// This is internal node. Update the total mass of the node and center-of-mass.
|
|
229
|
-
${c("var {var} = body.pos.{var};",{indent:8})}
|
|
230
|
-
node.mass += body.mass;
|
|
231
|
-
${c("node.mass_{var} += body.mass * {var};",{indent:8})}
|
|
232
|
-
|
|
233
|
-
// Recursively insert the body in the appropriate quadrant.
|
|
234
|
-
// But first find the appropriate quadrant.
|
|
235
|
-
var quadIdx = 0; // Assume we are in the 0's quad.
|
|
236
|
-
${c("var min_{var} = node.min_{var};",{indent:8})}
|
|
237
|
-
${c("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}
|
|
238
|
-
|
|
239
|
-
${f(8)}
|
|
240
|
-
|
|
241
|
-
var child = getChild(node, quadIdx);
|
|
242
|
-
|
|
243
|
-
if (!child) {
|
|
244
|
-
// The node is internal but this quadrant is not taken. Add
|
|
245
|
-
// subnode to it.
|
|
246
|
-
child = newNode();
|
|
247
|
-
${c("child.min_{var} = min_{var};",{indent:10})}
|
|
248
|
-
${c("child.max_{var} = max_{var};",{indent:10})}
|
|
249
|
-
child.body = body;
|
|
250
|
-
|
|
251
|
-
setChild(node, quadIdx, child);
|
|
252
|
-
} else {
|
|
253
|
-
// continue searching in this quadrant.
|
|
254
|
-
insertStack.push(child, body);
|
|
255
|
-
}
|
|
256
|
-
} else {
|
|
257
|
-
// We are trying to add to the leaf node.
|
|
258
|
-
// We have to convert current leaf into internal node
|
|
259
|
-
// and continue adding two nodes.
|
|
260
|
-
var oldBody = node.body;
|
|
261
|
-
node.body = null; // internal nodes do not cary bodies
|
|
262
|
-
|
|
263
|
-
if (isSamePosition(oldBody.pos, body.pos)) {
|
|
264
|
-
// Prevent infinite subdivision by bumping one node
|
|
265
|
-
// anywhere in this quadrant
|
|
266
|
-
var retriesCount = 3;
|
|
267
|
-
do {
|
|
268
|
-
var offset = random.nextDouble();
|
|
269
|
-
${c("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}
|
|
270
|
-
|
|
271
|
-
${c("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}
|
|
272
|
-
retriesCount -= 1;
|
|
273
|
-
// Make sure we don't bump it out of the box. If we do, next iteration should fix it
|
|
274
|
-
} while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));
|
|
275
|
-
|
|
276
|
-
if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {
|
|
277
|
-
// This is very bad, we ran out of precision.
|
|
278
|
-
// if we do not return from the method we'll get into
|
|
279
|
-
// infinite loop here. So we sacrifice correctness of layout, and keep the app running
|
|
280
|
-
// Next layout iteration should get larger bounding box in the first step and fix this
|
|
281
|
-
return;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
// Next iteration should subdivide node further.
|
|
285
|
-
insertStack.push(node, oldBody);
|
|
286
|
-
insertStack.push(node, body);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
return createQuadTree;
|
|
292
|
-
|
|
293
|
-
`;function f(m){let y=[],_=Array(m+1).join(" ");for(let T=0;T<l;++T)y.push(_+`if (${e(T)} > max_${e(T)}) {`),y.push(_+` quadIdx = quadIdx + ${Math.pow(2,T)};`),y.push(_+` min_${e(T)} = max_${e(T)};`),y.push(_+` max_${e(T)} = node.max_${e(T)};`),y.push(_+"}");return y.join(`
|
|
294
|
-
`)}function p(){let m=Array(11).join(" "),y=[];for(let _=0;_<d;++_)y.push(m+`if (node.quad${_}) {`),y.push(m+` queue[pushIdx] = node.quad${_};`),y.push(m+" queueLength += 1;"),y.push(m+" pushIdx += 1;"),y.push(m+"}");return y.join(`
|
|
295
|
-
`)}function g(m){let y=[];for(let _=0;_<d;++_)y.push(`${m}quad${_} = null;`);return y.join(`
|
|
296
|
-
`)}}function s(l){let c=i(l);return`
|
|
297
|
-
function isSamePosition(point1, point2) {
|
|
298
|
-
${c("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}
|
|
299
|
-
|
|
300
|
-
return ${c("d{var} < 1e-8",{join:" && "})};
|
|
301
|
-
}
|
|
302
|
-
`}function r(l){var c=Math.pow(2,l);return`
|
|
303
|
-
function setChild(node, idx, child) {
|
|
304
|
-
${d()}
|
|
305
|
-
}`;function d(){let h=[];for(let f=0;f<c;++f){let p=f===0?" ":" else ";h.push(`${p}if (idx === ${f}) node.quad${f} = child;`)}return h.join(`
|
|
306
|
-
`)}}function o(l){return`function getChild(node, idx) {
|
|
307
|
-
${c()}
|
|
308
|
-
return null;
|
|
309
|
-
}`;function c(){let d=[],h=Math.pow(2,l);for(let f=0;f<h;++f)d.push(` if (idx === ${f}) return node.quad${f};`);return d.join(`
|
|
310
|
-
`)}}function a(l){let c=i(l),d=Math.pow(2,l);var h=`
|
|
311
|
-
function QuadNode() {
|
|
312
|
-
// body stored inside this node. In quad tree only leaf nodes (by construction)
|
|
313
|
-
// contain bodies:
|
|
314
|
-
this.body = null;
|
|
315
|
-
|
|
316
|
-
// Child nodes are stored in quads. Each quad is presented by number:
|
|
317
|
-
// 0 | 1
|
|
318
|
-
// -----
|
|
319
|
-
// 2 | 3
|
|
320
|
-
${f(" this.")}
|
|
321
|
-
|
|
322
|
-
// Total mass of current node
|
|
323
|
-
this.mass = 0;
|
|
324
|
-
|
|
325
|
-
// Center of mass coordinates
|
|
326
|
-
${c("this.mass_{var} = 0;",{indent:2})}
|
|
327
|
-
|
|
328
|
-
// bounding box coordinates
|
|
329
|
-
${c("this.min_{var} = 0;",{indent:2})}
|
|
330
|
-
${c("this.max_{var} = 0;",{indent:2})}
|
|
331
|
-
}
|
|
332
|
-
`;return h;function f(p){let g=[];for(let m=0;m<d;++m)g.push(`${p}quad${m} = null;`);return g.join(`
|
|
333
|
-
`)}}function u(){return`
|
|
334
|
-
/**
|
|
335
|
-
* Our implementation of QuadTree is non-recursive to avoid GC hit
|
|
336
|
-
* This data structure represent stack of elements
|
|
337
|
-
* which we are trying to insert into quad tree.
|
|
338
|
-
*/
|
|
339
|
-
function InsertStack () {
|
|
340
|
-
this.stack = [];
|
|
341
|
-
this.popIdx = 0;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
InsertStack.prototype = {
|
|
345
|
-
isEmpty: function() {
|
|
346
|
-
return this.popIdx === 0;
|
|
347
|
-
},
|
|
348
|
-
push: function (node, body) {
|
|
349
|
-
var item = this.stack[this.popIdx];
|
|
350
|
-
if (!item) {
|
|
351
|
-
// we are trying to avoid memory pressure: create new element
|
|
352
|
-
// only when absolutely necessary
|
|
353
|
-
this.stack[this.popIdx] = new InsertStackElement(node, body);
|
|
354
|
-
} else {
|
|
355
|
-
item.node = node;
|
|
356
|
-
item.body = body;
|
|
357
|
-
}
|
|
358
|
-
++this.popIdx;
|
|
359
|
-
},
|
|
360
|
-
pop: function () {
|
|
361
|
-
if (this.popIdx > 0) {
|
|
362
|
-
return this.stack[--this.popIdx];
|
|
363
|
-
}
|
|
364
|
-
},
|
|
365
|
-
reset: function () {
|
|
366
|
-
this.popIdx = 0;
|
|
367
|
-
}
|
|
368
|
-
};
|
|
369
|
-
|
|
370
|
-
function InsertStackElement(node, body) {
|
|
371
|
-
this.node = node; // QuadTree node
|
|
372
|
-
this.body = body; // physical body which needs to be inserted to node
|
|
373
|
-
}
|
|
374
|
-
`}return cn.exports}var pi={exports:{}},Ec;function ib(){if(Ec)return pi.exports;Ec=1,pi.exports=e,pi.exports.generateFunctionBody=t;const i=ar();function e(n){let s=t(n);return new Function("bodies","settings","random",s)}function t(n){let s=i(n);return`
|
|
375
|
-
var boundingBox = {
|
|
376
|
-
${s("min_{var}: 0, max_{var}: 0,",{indent:4})}
|
|
377
|
-
};
|
|
378
|
-
|
|
379
|
-
return {
|
|
380
|
-
box: boundingBox,
|
|
381
|
-
|
|
382
|
-
update: updateBoundingBox,
|
|
383
|
-
|
|
384
|
-
reset: resetBoundingBox,
|
|
385
|
-
|
|
386
|
-
getBestNewPosition: function (neighbors) {
|
|
387
|
-
var ${s("base_{var} = 0",{join:", "})};
|
|
388
|
-
|
|
389
|
-
if (neighbors.length) {
|
|
390
|
-
for (var i = 0; i < neighbors.length; ++i) {
|
|
391
|
-
let neighborPos = neighbors[i].pos;
|
|
392
|
-
${s("base_{var} += neighborPos.{var};",{indent:10})}
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
${s("base_{var} /= neighbors.length;",{indent:8})}
|
|
396
|
-
} else {
|
|
397
|
-
${s("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
var springLength = settings.springLength;
|
|
401
|
-
return {
|
|
402
|
-
${s("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}
|
|
403
|
-
};
|
|
404
|
-
}
|
|
405
|
-
};
|
|
406
|
-
|
|
407
|
-
function updateBoundingBox() {
|
|
408
|
-
var i = bodies.length;
|
|
409
|
-
if (i === 0) return; // No bodies - no borders.
|
|
410
|
-
|
|
411
|
-
${s("var max_{var} = -Infinity;",{indent:4})}
|
|
412
|
-
${s("var min_{var} = Infinity;",{indent:4})}
|
|
413
|
-
|
|
414
|
-
while(i--) {
|
|
415
|
-
// this is O(n), it could be done faster with quadtree, if we check the root node bounds
|
|
416
|
-
var bodyPos = bodies[i].pos;
|
|
417
|
-
${s("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}
|
|
418
|
-
${s("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
${s("boundingBox.min_{var} = min_{var};",{indent:4})}
|
|
422
|
-
${s("boundingBox.max_{var} = max_{var};",{indent:4})}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
function resetBoundingBox() {
|
|
426
|
-
${s("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}
|
|
427
|
-
}
|
|
428
|
-
`}return pi.exports}var gi={exports:{}},Ac;function ob(){if(Ac)return gi.exports;Ac=1;const i=ar();gi.exports=e,gi.exports.generateCreateDragForceFunctionBody=t;function e(n){let s=t(n);return new Function("options",s)}function t(n){return`
|
|
429
|
-
if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');
|
|
430
|
-
|
|
431
|
-
return {
|
|
432
|
-
update: function(body) {
|
|
433
|
-
${i(n)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}
|
|
434
|
-
}
|
|
435
|
-
};
|
|
436
|
-
`}return gi.exports}var mi={exports:{}},Cc;function ab(){if(Cc)return mi.exports;Cc=1;const i=ar();mi.exports=e,mi.exports.generateCreateSpringForceFunctionBody=t;function e(n){let s=t(n);return new Function("options","random",s)}function t(n){let s=i(n);return`
|
|
437
|
-
if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');
|
|
438
|
-
if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');
|
|
439
|
-
|
|
440
|
-
return {
|
|
441
|
-
/**
|
|
442
|
-
* Updates forces acting on a spring
|
|
443
|
-
*/
|
|
444
|
-
update: function (spring) {
|
|
445
|
-
var body1 = spring.from;
|
|
446
|
-
var body2 = spring.to;
|
|
447
|
-
var length = spring.length < 0 ? options.springLength : spring.length;
|
|
448
|
-
${s("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}
|
|
449
|
-
var r = Math.sqrt(${s("d{var} * d{var}",{join:" + "})});
|
|
450
|
-
|
|
451
|
-
if (r === 0) {
|
|
452
|
-
${s("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}
|
|
453
|
-
r = Math.sqrt(${s("d{var} * d{var}",{join:" + "})});
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
var d = r - length;
|
|
457
|
-
var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;
|
|
458
|
-
|
|
459
|
-
${s("body1.force.{var} += coefficient * d{var}",{indent:6})};
|
|
460
|
-
body1.springCount += 1;
|
|
461
|
-
body1.springLength += r;
|
|
462
|
-
|
|
463
|
-
${s("body2.force.{var} -= coefficient * d{var}",{indent:6})};
|
|
464
|
-
body2.springCount += 1;
|
|
465
|
-
body2.springLength += r;
|
|
466
|
-
}
|
|
467
|
-
};
|
|
468
|
-
`}return mi.exports}var yi={exports:{}},Mc;function ub(){if(Mc)return yi.exports;Mc=1;const i=ar();yi.exports=e,yi.exports.generateIntegratorFunctionBody=t;function e(n){let s=t(n);return new Function("bodies","timeStep","adaptiveTimeStepWeight",s)}function t(n){let s=i(n);return`
|
|
469
|
-
var length = bodies.length;
|
|
470
|
-
if (length === 0) return 0;
|
|
471
|
-
|
|
472
|
-
${s("var d{var} = 0, t{var} = 0;",{indent:2})}
|
|
473
|
-
|
|
474
|
-
for (var i = 0; i < length; ++i) {
|
|
475
|
-
var body = bodies[i];
|
|
476
|
-
if (body.isPinned) continue;
|
|
477
|
-
|
|
478
|
-
if (adaptiveTimeStepWeight && body.springCount) {
|
|
479
|
-
timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
var coeff = timeStep / body.mass;
|
|
483
|
-
|
|
484
|
-
${s("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}
|
|
485
|
-
${s("var v{var} = body.velocity.{var};",{indent:4})}
|
|
486
|
-
var v = Math.sqrt(${s("v{var} * v{var}",{join:" + "})});
|
|
487
|
-
|
|
488
|
-
if (v > 1) {
|
|
489
|
-
// We normalize it so that we move within timeStep range.
|
|
490
|
-
// for the case when v <= 1 - we let velocity to fade out.
|
|
491
|
-
${s("body.velocity.{var} = v{var} / v;",{indent:6})}
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
${s("d{var} = timeStep * body.velocity.{var};",{indent:4})}
|
|
495
|
-
|
|
496
|
-
${s("body.pos.{var} += d{var};",{indent:4})}
|
|
497
|
-
|
|
498
|
-
${s("t{var} += Math.abs(d{var});",{indent:4})}
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
return (${s("t{var} * t{var}",{join:" + "})})/length;
|
|
502
|
-
`}return yi.exports}var ca,Bc;function lb(){if(Bc)return ca;Bc=1,ca=i;function i(e,t,n,s){this.from=e,this.to=t,this.length=n,this.coefficient=s}return ca}var da,Pc;function cb(){if(Pc)return da;Pc=1,da=i;function i(e,t){var n;if(e||(e={}),t){for(n in t)if(t.hasOwnProperty(n)){var s=e.hasOwnProperty(n),r=typeof t[n],o=!s||typeof e[n]!==r;o?e[n]=t[n]:r==="object"&&(e[n]=i(e[n],t[n]))}}return e}return da}var ha,Fc;function Of(){if(Fc)return ha;Fc=1;function i(n){t(n);const s=e(n);return n.on=s.on,n.off=s.off,n.fire=s.fire,n}function e(n){let s=Object.create(null);return{on:function(r,o,a){if(typeof o!="function")throw new Error("callback is expected to be a function");let u=s[r];return u||(u=s[r]=[]),u.push({callback:o,ctx:a}),n},off:function(r,o){if(typeof r>"u")return s=Object.create(null),n;if(s[r])if(typeof o!="function")delete s[r];else{const a=s[r];for(let u=0;u<a.length;++u)a[u].callback===o&&a.splice(u,1)}return n},fire:function(r){const o=s[r];if(!o)return n;let a;arguments.length>1&&(a=Array.prototype.slice.call(arguments,1));for(let u=0;u<o.length;++u){const l=o[u];l.callback.apply(l.ctx,a)}return n}}}function t(n){if(!n)throw new Error("Eventify cannot use falsy object as events subject");const s=["on","fire","off"];for(let r=0;r<s.length;++r)if(n.hasOwnProperty(s[r]))throw new Error("Subject cannot be eventified, since it already has property '"+s[r]+"'")}return ha=i,ha}var _r={exports:{}},Dc;function db(){if(Dc)return _r.exports;Dc=1,_r.exports=i,_r.exports.random=i,_r.exports.randomIterator=a;function i(u){var l=typeof u=="number"?u:+new Date;return new e(l)}function e(u){this.seed=u}e.prototype.next=o,e.prototype.nextDouble=r,e.prototype.uniform=r,e.prototype.gaussian=t,e.prototype.random=r;function t(){var u,l,c;do l=this.nextDouble()*2-1,c=this.nextDouble()*2-1,u=l*l+c*c;while(u>=1||u===0);return l*Math.sqrt(-2*Math.log(u)/u)}e.prototype.levy=n;function n(){var u=1.5,l=Math.pow(s(1+u)*Math.sin(Math.PI*u/2)/(s((1+u)/2)*u*Math.pow(2,(u-1)/2)),1/u);return this.gaussian()*l/Math.pow(Math.abs(this.gaussian()),1/u)}function s(u){return Math.sqrt(2*Math.PI/u)*Math.pow(1/Math.E*(u+1/(12*u-1/(10*u))),u)}function r(){var u=this.seed;return u=u+2127912214+(u<<12)&4294967295,u=(u^3345072700^u>>>19)&4294967295,u=u+374761393+(u<<5)&4294967295,u=(u+3550635116^u<<9)&4294967295,u=u+4251993797+(u<<3)&4294967295,u=(u^3042594569^u>>>16)&4294967295,this.seed=u,(u&268435455)/268435456}function o(u){return Math.floor(this.nextDouble()*u)}function a(u,l){var c=l||i();if(typeof c.next!="function")throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:h,shuffle:d};function d(){var f,p,g;for(f=u.length-1;f>0;--f)p=c.next(f+1),g=u[p],u[p]=u[f],u[f]=g;return u}function h(f){var p,g,m;for(p=u.length-1;p>0;--p)g=c.next(p+1),m=u[g],u[g]=u[p],u[p]=m,f(m);u.length&&f(u[0])}}return _r.exports}var fa,Lc;function Uc(){if(Lc)return fa;Lc=1,fa=a;var i=sb(),e=rb(),t=ib(),n=ob(),s=ab(),r=ub(),o={};function a(c){var d=lb(),h=cb(),f=Of();if(c){if(c.springCoeff!==void 0)throw new Error("springCoeff was renamed to springCoefficient");if(c.dragCoeff!==void 0)throw new Error("dragCoeff was renamed to dragCoefficient")}c=h(c,{springLength:10,springCoefficient:.8,gravity:-12,theta:.8,dragCoefficient:.9,timeStep:.5,adaptiveTimeStepWeight:0,dimensions:2,debug:!1});var p=o[c.dimensions];if(!p){var g=c.dimensions;p={Body:i(g,c.debug),createQuadTree:e(g),createBounds:t(g),createDragForce:n(g),createSpringForce:s(g),integrate:r(g)},o[g]=p}var m=p.Body,y=p.createQuadTree,_=p.createBounds,T=p.createDragForce,S=p.createSpringForce,N=p.integrate,R=B=>new m(B),v=db().random(42),P=[],D=[],L=y(c,v),j=_(P,c,v),ee=S(c,v),re=T(c),se=0,Z=[],oe=new Map,F=0;ve("nbody",le),ve("spring",Ce);var G={bodies:P,quadTree:L,springs:D,settings:c,addForce:ve,removeForce:I,getForces:H,step:function(){for(var B=0;B<Z.length;++B)Z[B](F);var U=N(P,c.timeStep,c.adaptiveTimeStepWeight);return F+=1,U},addBody:function(B){if(!B)throw new Error("Body is required");return P.push(B),B},addBodyAt:function(B){if(!B)throw new Error("Body position is required");var U=R(B);return P.push(U),U},removeBody:function(B){if(B){var U=P.indexOf(B);if(!(U<0))return P.splice(U,1),P.length===0&&j.reset(),!0}},addSpring:function(B,U,K,me){if(!B||!U)throw new Error("Cannot add null spring to force simulator");typeof K!="number"&&(K=-1);var Ue=new d(B,U,K,me>=0?me:-1);return D.push(Ue),Ue},getTotalMovement:function(){return se},removeSpring:function(B){if(B){var U=D.indexOf(B);if(U>-1)return D.splice(U,1),!0}},getBestNewBodyPosition:function(B){return j.getBestNewPosition(B)},getBBox:Q,getBoundingBox:Q,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(B){return B!==void 0?(c.gravity=B,L.options({gravity:B}),this):c.gravity},theta:function(B){return B!==void 0?(c.theta=B,L.options({theta:B}),this):c.theta},random:v};return u(c,G),f(G),G;function Q(){return j.update(),j.box}function ve(B,U){if(oe.has(B))throw new Error("Force "+B+" is already added");oe.set(B,U),Z.push(U)}function I(B){var U=Z.indexOf(oe.get(B));U<0||(Z.splice(U,1),oe.delete(B))}function H(){return oe}function le(){if(P.length!==0){L.insertBodies(P);for(var B=P.length;B--;){var U=P[B];U.isPinned||(U.reset(),L.updateBodyForce(U),re.update(U))}}}function Ce(){for(var B=D.length;B--;)ee.update(D[B])}}function u(c,d){for(var h in c)l(c,d,h)}function l(c,d,h){if(c.hasOwnProperty(h)&&typeof d[h]!="function"){var f=Number.isFinite(c[h]);f?d[h]=function(p){if(p!==void 0){if(!Number.isFinite(p))throw new Error("Value of "+h+" should be a valid number.");return c[h]=p,d}return c[h]}:d[h]=function(p){return p!==void 0?(c[h]=p,d):c[h]}}}return fa}var Oc;function hb(){if(Oc)return fi.exports;Oc=1,fi.exports=e,fi.exports.simulator=Uc();var i=Of();function e(n,s){if(!n)throw new Error("Graph structure cannot be undefined");var r=s&&s.createSimulator||Uc(),o=r(s);if(Array.isArray(s))throw new Error("Physics settings is expected to be an object");var a=n.version>19?oe:Z;s&&typeof s.nodeMass=="function"&&(a=s.nodeMass);var u=new Map,l={},c=0,d=o.settings.springTransform||t;R(),T();var h=!1,f={step:function(){if(c===0)return p(!0),!0;var F=o.step();f.lastMove=F,f.fire("step");var G=F/c,Q=G<=.01;return p(Q),Q},getNodePosition:function(F){return se(F).pos},setNodePosition:function(F){var G=se(F);G.setPosition.apply(G,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(F){var G=l[F];if(G)return{from:G.from.pos,to:G.to.pos}},getGraphRect:function(){return o.getBBox()},forEachBody:g,pinNode:function(F,G){var Q=se(F.id);Q.isPinned=!!G},isNodePinned:function(F){return se(F.id).isPinned},dispose:function(){n.off("changed",N),f.fire("disposed")},getBody:_,getSpring:y,getForceVectorLength:m,simulator:o,graph:n,lastMove:0};return i(f),f;function p(F){h!==F&&(h=F,S(F))}function g(F){u.forEach(F)}function m(){var F=0,G=0;return g(function(Q){F+=Math.abs(Q.force.x),G+=Math.abs(Q.force.y)}),Math.sqrt(F*F+G*G)}function y(F,G){var Q;if(G===void 0)typeof F!="object"?Q=F:Q=F.id;else{var ve=n.hasLink(F,G);if(!ve)return;Q=ve.id}return l[Q]}function _(F){return u.get(F)}function T(){n.on("changed",N)}function S(F){f.fire("stable",F)}function N(F){for(var G=0;G<F.length;++G){var Q=F[G];Q.changeType==="add"?(Q.node&&v(Q.node.id),Q.link&&D(Q.link)):Q.changeType==="remove"&&(Q.node&&P(Q.node),Q.link&&L(Q.link))}c=n.getNodesCount()}function R(){c=0,n.forEachNode(function(F){v(F.id),c+=1}),n.forEachLink(D)}function v(F){var G=u.get(F);if(!G){var Q=n.getNode(F);if(!Q)throw new Error("initBody() was called with unknown node id");var ve=Q.position;if(!ve){var I=j(Q);ve=o.getBestNewBodyPosition(I)}G=o.addBodyAt(ve),G.id=F,u.set(F,G),ee(F),re(Q)&&(G.isPinned=!0)}}function P(F){var G=F.id,Q=u.get(G);Q&&(u.delete(G),o.removeBody(Q))}function D(F){ee(F.fromId),ee(F.toId);var G=u.get(F.fromId),Q=u.get(F.toId),ve=o.addSpring(G,Q,F.length);d(F,ve),l[F.id]=ve}function L(F){var G=l[F.id];if(G){var Q=n.getNode(F.fromId),ve=n.getNode(F.toId);Q&&ee(Q.id),ve&&ee(ve.id),delete l[F.id],o.removeSpring(G)}}function j(F){var G=[];if(!F.links)return G;for(var Q=Math.min(F.links.length,2),ve=0;ve<Q;++ve){var I=F.links[ve],H=I.fromId!==F.id?u.get(I.fromId):u.get(I.toId);H&&H.pos&&G.push(H)}return G}function ee(F){var G=u.get(F);if(G.mass=a(F),Number.isNaN(G.mass))throw new Error("Node mass should be a number")}function re(F){return F&&(F.isPinned||F.data&&F.data.isPinned)}function se(F){var G=u.get(F);return G||(v(F),G=u.get(F)),G}function Z(F){var G=n.getLinks(F);return G?1+G.length/3:1}function oe(F){var G=n.getLinks(F);return G?1+G.size/3:1}}function t(){}return fi.exports}var fb=hb();const pb=Ly(fb);function Wu(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function gb(i){if(Array.isArray(i))return i}function mb(i){if(Array.isArray(i))return Wu(i)}function If(i,e,t){if(typeof i=="function"?i===e:i.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function yb(i,e){if(e.has(i))throw new TypeError("Cannot initialize the same private elements twice on an object")}function bb(i,e){if(!(i instanceof e))throw new TypeError("Cannot call a class as a function")}function et(i,e){return i.get(If(i,e))}function Ms(i,e,t){yb(i,e),e.set(i,t)}function bi(i,e,t){return i.set(If(i,e),t),t}function _b(i,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(i,Ab(n.key),n)}}function xb(i,e,t){return e&&_b(i.prototype,e),Object.defineProperty(i,"prototype",{writable:!1}),i}function Tb(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function vb(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,s,r,o,a=[],u=!0,l=!1;try{if(r=(t=t.call(i)).next,e!==0)for(;!(u=(n=r.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,s=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}function Sb(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
503
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Nb(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
504
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Rb(i,e){return gb(i)||vb(i,e)||kf(i,e)||Sb()}function wb(i){return mb(i)||Tb(i)||kf(i)||Nb()}function Eb(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(i)}function Ab(i){var e=Eb(i,"string");return typeof e=="symbol"?e:e+""}function kf(i,e){if(i){if(typeof i=="string")return Wu(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Wu(i,e):void 0}}var Bs=new WeakMap,xr=new WeakMap,Ps=new WeakMap,pa=new WeakMap,ga=new WeakMap,ma=new WeakMap,Cb=(function(){function i(){bb(this,i),Ms(this,Bs,new Map),Ms(this,xr,new Map),Ms(this,Ps,function(e){return e}),Ms(this,pa,function(){return{}}),Ms(this,ga,function(){}),Ms(this,ma,function(){})}return xb(i,[{key:"getObj",value:function(t){return et(Bs,this).get(et(Ps,this).call(this,t))}},{key:"getData",value:function(t){return et(xr,this).get(t)}},{key:"entries",value:function(){return wb(et(xr,this).entries()).map(function(t){var n=Rb(t,2),s=n[0],r=n[1];return[r,s]})}},{key:"id",value:function(t){return bi(Ps,this,fe(t)),this}},{key:"onCreateObj",value:function(t){return bi(pa,this,t),this}},{key:"onUpdateObj",value:function(t){return bi(ga,this,t),this}},{key:"onRemoveObj",value:function(t){return bi(ma,this,t),this}},{key:"digest",value:function(t){var n=this;t.filter(function(r){return!et(Bs,n).has(et(Ps,n).call(n,r))}).forEach(function(r){var o=et(pa,n).call(n,r);et(Bs,n).set(et(Ps,n).call(n,r),o),et(xr,n).set(o,r)});var s=new Map(t.map(function(r){return[et(Ps,n).call(n,r),r]}));return et(Bs,this).forEach(function(r,o){s.has(o)?et(ga,n).call(n,r,s.get(o)):(et(ma,n).call(n,r,o),et(Bs,n).delete(o),et(xr,n).delete(r))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])})();function ju(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function Mb(i){if(Array.isArray(i))return i}function Bb(i){if(Array.isArray(i))return ju(i)}function Gf(i,e,t){if(typeof i=="function"?i===e:i.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function Pb(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}function Vf(i,e,t){return e=nr(e),Gb(i,Fl()?Reflect.construct(e,t||[],nr(i).constructor):e.apply(i,t))}function Fb(i,e){if(e.has(i))throw new TypeError("Cannot initialize the same private elements twice on an object")}function $f(i,e){if(!(i instanceof e))throw new TypeError("Cannot call a class as a function")}function ya(i,e){return i.get(Gf(i,e))}function Ic(i,e,t){Fb(i,e),e.set(i,t)}function kc(i,e,t){return i.set(Gf(i,e),t),t}function zf(i,e,t){if(Fl())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var s=new(i.bind.apply(i,n));return s}function Db(i,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(i,qf(n.key),n)}}function Wf(i,e,t){return e&&Db(i.prototype,e),Object.defineProperty(i,"prototype",{writable:!1}),i}function $o(i,e,t){return(e=qf(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function qu(){return qu=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(i,e,t){var n=Vb(i,e);if(n){var s=Object.getOwnPropertyDescriptor(n,e);return s.get?s.get.call(arguments.length<3?i:t):s.value}},qu.apply(null,arguments)}function nr(i){return nr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},nr(i)}function jf(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),Object.defineProperty(i,"prototype",{writable:!1}),e&&Hu(i,e)}function Fl(){try{var i=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Fl=function(){return!!i})()}function Lb(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function Ub(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,s,r,o,a=[],u=!0,l=!1;try{if(r=(t=t.call(i)).next,e!==0)for(;!(u=(n=r.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,s=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}function Ob(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
505
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ib(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
506
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Gc(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,n)}return t}function kb(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Gc(Object(t),!0).forEach(function(n){$o(i,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Gc(Object(t)).forEach(function(n){Object.defineProperty(i,n,Object.getOwnPropertyDescriptor(t,n))})}return i}function Gb(i,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Pb(i)}function Hu(i,e){return Hu=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},Hu(i,e)}function Ir(i,e){return Mb(i)||Ub(i,e)||Hf(i,e)||Ob()}function Vb(i,e){for(;!{}.hasOwnProperty.call(i,e)&&(i=nr(i))!==null;);return i}function ba(i,e,t,n){var s=qu(nr(i.prototype),e,t);return typeof s=="function"?function(r){return s.apply(t,r)}:s}function Ot(i){return Bb(i)||Lb(i)||Hf(i)||Ib()}function $b(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function qf(i){var e=$b(i,"string");return typeof e=="symbol"?e:e+""}function Xu(i){"@babel/helpers - typeof";return Xu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xu(i)}function Hf(i,e){if(i){if(typeof i=="string")return ju(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?ju(i,e):void 0}}var Xf=function(e){e instanceof Array?e.forEach(Xf):(e.map&&e.map.dispose(),e.dispose())},Dl=function(e){e.geometry&&e.geometry.dispose(),e.material&&Xf(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Dl)},Vc=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),Dl(t)}},_a=new WeakMap,_i=new WeakMap,Tr=(function(i){function e(t){var n,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=s.dataBindAttr,o=r===void 0?"__data":r,a=s.objBindAttr,u=a===void 0?"__threeObj":a;return $f(this,e),n=Vf(this,e),$o(n,"scene",void 0),Ic(n,_a,void 0),Ic(n,_i,void 0),n.scene=t,kc(_a,n,o),kc(_i,n,u),n.onRemoveObj(function(){}),n}return jf(e,i),Wf(e,[{key:"onCreateObj",value:function(n){var s=this;return ba(e,"onCreateObj",this)([function(r){var o=n(r);return r[ya(_i,s)]=o,o[ya(_a,s)]=r,s.scene.add(o),o}]),this}},{key:"onRemoveObj",value:function(n){var s=this;return ba(e,"onRemoveObj",this)([function(r,o){var a=ba(e,"getData",s)([r]);n(r,o),s.scene.remove(r),Dl(r),delete a[ya(_i,s)]}]),this}}])})(Cb),vr=function(e){return isNaN(e)?parseInt(Mf(e).toHex(),16):e},xa=function(e){return isNaN(e)?Mf(e).getAlpha():1},zb=Wy(Uy);function $c(i,e,t){!e||typeof t!="string"||i.filter(function(n){return!n[t]}).forEach(function(n){n[t]=zb(e(n))})}function Wb(i,e){var t=i.nodes,n=i.links,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=s.nodeFilter,o=r===void 0?function(){return!0}:r,a=s.onLoopError,u=a===void 0?function(f){throw"Invalid DAG structure! Found cycle in node path: ".concat(f.join(" -> "),".")}:a,l={};t.forEach(function(f){return l[e(f)]={data:f,out:[],depth:-1,skip:!o(f)}}),n.forEach(function(f){var p=f.source,g=f.target,m=S(p),y=S(g);if(!l.hasOwnProperty(m))throw"Missing source node with id: ".concat(m);if(!l.hasOwnProperty(y))throw"Missing target node with id: ".concat(y);var _=l[m],T=l[y];_.out.push(T);function S(N){return Xu(N)==="object"?e(N):N}});var c=[];h(Object.values(l));var d=Object.assign.apply(Object,[{}].concat(Ot(Object.entries(l).filter(function(f){var p=Ir(f,2),g=p[1];return!g.skip}).map(function(f){var p=Ir(f,2),g=p[0],m=p[1];return $o({},g,m.depth)}))));return d;function h(f){for(var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,m=function(){var S=f[y];if(p.indexOf(S)!==-1){var N=[].concat(Ot(p.slice(p.indexOf(S))),[S]).map(function(R){return e(R.data)});return c.some(function(R){return R.length===N.length&&R.every(function(v,P){return v===N[P]})})||(c.push(N),u(N)),1}g>S.depth&&(S.depth=g,h(S.out,[].concat(Ot(p),[S]),g+(S.skip?0:1)))},y=0,_=f.length;y<_;y++)m()}}var ne=window.THREE?window.THREE:{Group:Oh,Mesh:kt,MeshLambertMaterial:Uh,Color:Dt,BufferGeometry:si,BufferAttribute:Yi,Matrix4:St,Vector3:V,SphereGeometry:_l,CylinderGeometry:Ih,TubeGeometry:pm,ConeGeometry:fm,Line:cm,LineBasicMaterial:Gh,QuadraticBezierCurve3:hm,CubicBezierCurve3:dm,Box3:kh},zc={graph:tb,forcelayout:pb},jb=2,Ta=new ne.BufferGeometry().setAttribute?"setAttribute":"addAttribute",xi=new ne.BufferGeometry().applyMatrix4?"applyMatrix4":"applyMatrix",qb=Pl({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(s){return s.json()}).then(function(s){t.fetchingJson=!1,t.onFinishLoading(s),n.graphData(s)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force("charge");n&&n.strength(e>2?-60:-30),e<3&&s(t.graphData.nodes,"z"),e<2&&s(t.graphData.nodes,"y");function s(r,o){r.forEach(function(a){delete a[o],delete a["v".concat(o)]})}}},dagMode:{onChange:function(e,t){!e&&t.forceEngine==="d3"&&(t.graphData.nodes||[]).forEach(function(n){return n.fx=n.fy=n.fz=void 0})}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return n===void 0?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t=e.forceEngine!=="ngraph";return e.engineRunning&&n(),s(),r(),this;function n(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||t&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin?(e.engineRunning=!1,e.onEngineStop()):(e.layout[t?"tick":"step"](),e.onEngineTick());var o=fe(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(function(h){var f=Ir(h,2),p=f[0],g=f[1];if(g){var m=t?p:e.layout.getNodePosition(p[e.nodeId]),y=o(p);(!e.nodePositionUpdate||!e.nodePositionUpdate(y?g.children[0]:g,{x:m.x,y:m.y,z:m.z},p)||y)&&(g.position.x=m.x,g.position.y=m.y||0,g.position.z=m.z||0)}});var a=fe(e.linkWidth),u=fe(e.linkCurvature),l=fe(e.linkCurveRotation),c=fe(e.linkThreeObjectExtend);e.linkDataMapper.entries().forEach(function(h){var f=Ir(h,2),p=f[0],g=f[1];if(g){var m=t?p:e.layout.getLinkPosition(e.layout.graph.getLink(p.source,p.target).id),y=m[t?"source":"from"],_=m[t?"target":"to"];if(!(!y||!_||!y.hasOwnProperty("x")||!_.hasOwnProperty("x"))){d(p);var T=c(p);if(!(e.linkPositionUpdate&&e.linkPositionUpdate(T?g.children[1]:g,{start:{x:y.x,y:y.y,z:y.z},end:{x:_.x,y:_.y,z:_.z}},p)&&!T)){var S=30,N=p.__curve,R=g.children.length?g.children[0]:g;if(R.type==="Line"){if(N){var P=N.getPoints(S);R.geometry.getAttribute("position").array.length!==P.length*3&&R.geometry[Ta]("position",new ne.BufferAttribute(new Float32Array(P.length*3),3)),R.geometry.setFromPoints(P)}else{var v=R.geometry.getAttribute("position");(!v||!v.array||v.array.length!==6)&&R.geometry[Ta]("position",v=new ne.BufferAttribute(new Float32Array(6),3)),v.array[0]=y.x,v.array[1]=y.y||0,v.array[2]=y.z||0,v.array[3]=_.x,v.array[4]=_.y||0,v.array[5]=_.z||0,v.needsUpdate=!0}R.geometry.computeBoundingSphere()}else if(R.type==="Mesh")if(N){R.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(R.position.set(0,0,0),R.rotation.set(0,0,0),R.scale.set(1,1,1));var Z=Math.ceil(a(p)*10)/10,oe=Z/2,F=new ne.TubeGeometry(N,S,oe,e.linkResolution,!1);R.geometry.dispose(),R.geometry=F}else{if(!R.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var D=Math.ceil(a(p)*10)/10,L=D/2,j=new ne.CylinderGeometry(L,L,1,e.linkResolution,1,!1);j[xi](new ne.Matrix4().makeTranslation(0,1/2,0)),j[xi](new ne.Matrix4().makeRotationX(Math.PI/2)),R.geometry.dispose(),R.geometry=j}var ee=new ne.Vector3(y.x,y.y||0,y.z||0),re=new ne.Vector3(_.x,_.y||0,_.z||0),se=ee.distanceTo(re);R.position.x=ee.x,R.position.y=ee.y,R.position.z=ee.z,R.scale.z=se,R.parent.localToWorld(re),R.lookAt(re)}}}}});function d(h){var f=t?h:e.layout.getLinkPosition(e.layout.graph.getLink(h.source,h.target).id),p=f[t?"source":"from"],g=f[t?"target":"to"];if(!(!p||!g||!p.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var m=u(h);if(!m)h.__curve=null;else{var y=new ne.Vector3(p.x,p.y||0,p.z||0),_=new ne.Vector3(g.x,g.y||0,g.z||0),T=y.distanceTo(_),S,N=l(h);if(T>0){var R=g.x-p.x,v=g.y-p.y||0,P=new ne.Vector3().subVectors(_,y),D=P.clone().multiplyScalar(m).cross(R!==0||v!==0?new ne.Vector3(0,0,1):new ne.Vector3(0,1,0)).applyAxisAngle(P.normalize(),N).add(new ne.Vector3().addVectors(y,_).divideScalar(2));S=new ne.QuadraticBezierCurve3(y,D,_)}else{var L=m*70,j=-N,ee=j+Math.PI/2;S=new ne.CubicBezierCurve3(y,new ne.Vector3(L*Math.cos(ee),L*Math.sin(ee),0).add(y),new ne.Vector3(L*Math.cos(j),L*Math.sin(j),0).add(y),_)}h.__curve=S}}}}function s(){var o=fe(e.linkDirectionalArrowRelPos),a=fe(e.linkDirectionalArrowLength),u=fe(e.nodeVal);e.arrowDataMapper.entries().forEach(function(l){var c=Ir(l,2),d=c[0],h=c[1];if(h){var f=t?d:e.layout.getLinkPosition(e.layout.graph.getLink(d.source,d.target).id),p=f[t?"source":"from"],g=f[t?"target":"to"];if(!(!p||!g||!p.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var m=Math.cbrt(Math.max(0,u(p)||1))*e.nodeRelSize,y=Math.cbrt(Math.max(0,u(g)||1))*e.nodeRelSize,_=a(d),T=o(d),S=d.__curve?function(L){return d.__curve.getPoint(L)}:function(L){var j=function(re,se,Z,oe){return se[re]+(Z[re]-se[re])*oe||0};return{x:j("x",p,g,L),y:j("y",p,g,L),z:j("z",p,g,L)}},N=d.__curve?d.__curve.getLength():Math.sqrt(["x","y","z"].map(function(L){return Math.pow((g[L]||0)-(p[L]||0),2)}).reduce(function(L,j){return L+j},0)),R=m+_+(N-m-y-_)*T,v=S(R/N),P=S((R-_)/N);["x","y","z"].forEach(function(L){return h.position[L]=P[L]});var D=zf(ne.Vector3,Ot(["x","y","z"].map(function(L){return v[L]})));h.parent.localToWorld(D),h.lookAt(D)}}})}function r(){var o=fe(e.linkDirectionalParticleSpeed),a=fe(e.linkDirectionalParticleOffset);e.graphData.links.forEach(function(u){var l=e.particlesDataMapper.getObj(u),c=l&&l.children,d=u.__singleHopPhotonsObj&&u.__singleHopPhotonsObj.children;if(!((!d||!d.length)&&(!c||!c.length))){var h=t?u:e.layout.getLinkPosition(e.layout.graph.getLink(u.source,u.target).id),f=h[t?"source":"from"],p=h[t?"target":"to"];if(!(!f||!p||!f.hasOwnProperty("x")||!p.hasOwnProperty("x"))){var g=o(u),m=Math.abs(a(u)),y=u.__curve?function(T){return u.__curve.getPoint(T)}:function(T){var S=function(R,v,P,D){return v[R]+(P[R]-v[R])*D||0};return{x:S("x",f,p,T),y:S("y",f,p,T),z:S("z",f,p,T)}},_=[].concat(Ot(c||[]),Ot(d||[]));_.forEach(function(T,S){var N=T.parent.__linkThreeObjType==="singleHopPhotons";if(T.hasOwnProperty("__progressRatio")||(T.__progressRatio=N?g<0?1:0:(S+m)/c.length),T.__progressRatio+=g,T.__progressRatio>=1||T.__progressRatio<0)if(!N)T.__progressRatio=T.__progressRatio%1,T.__progressRatio<0&&T.__progressRatio++;else{T.parent.remove(T),Vc(T);return}var R=T.__progressRatio,v=y(R);T.geometry.type!=="SphereGeometry"&&T.lookAt(v.x,v.y,v.z),["x","y","z"].forEach(function(P){return T.position[P]=v[P]})})}}})}},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new ne.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var s=fe(e.linkDirectionalParticleThreeObject)(t);if(s&&e.linkDirectionalParticleThreeObject===s&&(s=s.clone()),!s){var r=fe(e.linkDirectionalParticleWidth),o=Math.ceil(r(t)*10)/10/2,a=e.linkDirectionalParticleResolution,u=new ne.SphereGeometry(o,a,a),l=fe(e.linkColor),c=fe(e.linkDirectionalParticleColor),d=c(t)||l(t)||"#f0f0f0",h=new ne.Color(vr(d)),f=e.linkOpacity*3,p=new ne.MeshLambertMaterial({color:h,transparent:!0,opacity:f});s=new ne.Mesh(u,p)}t.__singleHopPhotonsObj.add(s)}return this},getGraphBbox:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=(function s(r){var o=[];if(r.geometry){r.geometry.computeBoundingBox();var a=new ne.Box3;a.copy(r.geometry.boundingBox).applyMatrix4(r.matrixWorld),o.push(a)}return o.concat.apply(o,Ot((r.children||[]).filter(function(u){return!u.hasOwnProperty("__graphObjType")||u.__graphObjType==="node"&&t(u.__data)}).map(s)))})(e.graphScene);return n.length?Object.assign.apply(Object,Ot(["x","y","z"].map(function(s){return $o({},s,[jy(n,function(r){return r.min[s]}),qy(n,function(r){return r.max[s]})])}))):null}},stateInit:function(){return{d3ForceLayout:Iy().force("link",ky()).force("charge",Gy()).force("center",Vy()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new Tr(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new Tr(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new Tr(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new Tr(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(U){return U.some(function(K){return t.hasOwnProperty(K)})};if(e.engineRunning=!1,typeof e.onUpdate=="function"&&e.onUpdate(),e.nodeAutoColorBy!==null&&n(["nodeAutoColorBy","graphData","nodeColor"])&&$c(e.graphData.nodes,fe(e.nodeAutoColorBy),e.nodeColor),e.linkAutoColorBy!==null&&n(["linkAutoColorBy","graphData","linkColor"])&&$c(e.graphData.links,fe(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var s=fe(e.nodeThreeObject),r=fe(e.nodeThreeObjectExtend),o=fe(e.nodeVal),a=fe(e.nodeColor),u=fe(e.nodeVisibility),l={},c={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(B){var U=s(B),K=r(B);U&&e.nodeThreeObject===U&&(U=U.clone());var me;return U&&!K?me=U:(me=new ne.Mesh,me.__graphDefaultObj=!0,U&&K&&me.add(U)),me.__graphObjType="node",me}).onUpdateObj(function(B,U){if(B.__graphDefaultObj){var K=o(U)||1,me=Math.cbrt(K)*e.nodeRelSize,Ue=e.nodeResolution;(!B.geometry.type.match(/^Sphere(Buffer)?Geometry$/)||B.geometry.parameters.radius!==me||B.geometry.parameters.widthSegments!==Ue)&&(l.hasOwnProperty(K)||(l[K]=new ne.SphereGeometry(me,Ue,Ue)),B.geometry.dispose(),B.geometry=l[K]);var Ie=a(U),ke=new ne.Color(vr(Ie||"#ffffaa")),Gt=e.nodeOpacity*xa(Ie);(B.material.type!=="MeshLambertMaterial"||!B.material.color.equals(ke)||B.material.opacity!==Gt)&&(c.hasOwnProperty(Ie)||(c[Ie]=new ne.MeshLambertMaterial({color:ke,transparent:!0,opacity:Gt})),B.material.dispose(),B.material=c[Ie])}}).digest(e.graphData.nodes.filter(u))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){var d=fe(e.linkThreeObject),h=fe(e.linkThreeObjectExtend),f=fe(e.linkMaterial),p=fe(e.linkVisibility),g=fe(e.linkColor),m=fe(e.linkWidth),y={},_={},T={},S=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(B){var U=B.__data&&B.__data.__singleHopPhotonsObj;U&&(U.parent.remove(U),Vc(U),delete B.__data.__singleHopPhotonsObj)}).onCreateObj(function(B){var U=d(B),K=h(B);U&&e.linkThreeObject===U&&(U=U.clone());var me;if(!U||K){var Ue=!!m(B);if(Ue)me=new ne.Mesh;else{var Ie=new ne.BufferGeometry;Ie[Ta]("position",new ne.BufferAttribute(new Float32Array(6),3)),me=new ne.Line(Ie)}}var ke;return U?K?(ke=new ne.Group,ke.__graphDefaultObj=!0,ke.add(me),ke.add(U)):ke=U:(ke=me,ke.__graphDefaultObj=!0),ke.renderOrder=10,ke.__graphObjType="link",ke}).onUpdateObj(function(B,U){if(B.__graphDefaultObj){var K=B.children.length?B.children[0]:B,me=Math.ceil(m(U)*10)/10,Ue=!!me;if(Ue){var Ie=me/2,ke=e.linkResolution;if(!K.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||K.geometry.parameters.radiusTop!==Ie||K.geometry.parameters.radialSegments!==ke){if(!y.hasOwnProperty(me)){var Gt=new ne.CylinderGeometry(Ie,Ie,1,ke,1,!1);Gt[xi](new ne.Matrix4().makeTranslation(0,1/2,0)),Gt[xi](new ne.Matrix4().makeRotationX(Math.PI/2)),y[me]=Gt}K.geometry.dispose(),K.geometry=y[me]}}var Zn=f(U);if(Zn)K.material=Zn;else{var Cn=g(U),yr=new ne.Color(vr(Cn||"#f0f0f0")),As=e.linkOpacity*xa(Cn),Mn=Ue?"MeshLambertMaterial":"LineBasicMaterial";if(K.material.type!==Mn||!K.material.color.equals(yr)||K.material.opacity!==As){var br=Ue?_:T;br.hasOwnProperty(Cn)||(br[Cn]=new ne[Mn]({color:yr,transparent:As<1,opacity:As,depthWrite:As>=1})),K.material.dispose(),K.material=br[Cn]}}}}).digest(S),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var N=fe(e.linkDirectionalArrowLength),R=fe(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var B=new ne.Mesh(void 0,new ne.MeshLambertMaterial({transparent:!0}));return B.__linkThreeObjType="arrow",B}).onUpdateObj(function(B,U){var K=N(U),me=e.linkDirectionalArrowResolution;if(!B.geometry.type.match(/^Cone(Buffer)?Geometry$/)||B.geometry.parameters.height!==K||B.geometry.parameters.radialSegments!==me){var Ue=new ne.ConeGeometry(K*.25,K,me);Ue.translate(0,K/2,0),Ue.rotateX(Math.PI/2),B.geometry.dispose(),B.geometry=Ue}var Ie=R(U)||g(U)||"#f0f0f0";B.material.color=new ne.Color(vr(Ie)),B.material.opacity=e.linkOpacity*3*xa(Ie)}).digest(S.filter(N))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var v=fe(e.linkDirectionalParticles),P=fe(e.linkDirectionalParticleWidth),D=fe(e.linkDirectionalParticleColor),L=fe(e.linkDirectionalParticleThreeObject),j={},ee={};e.particlesDataMapper.onCreateObj(function(){var B=new ne.Group;return B.__linkThreeObjType="photons",B.__photonDataMapper=new Tr(B),B}).onUpdateObj(function(B,U){var K=!!B.children.length&&B.children[0],me=L(U),Ue,Ie;if(me)Ue=me.geometry,Ie=me.material;else{var ke=Math.ceil(P(U)*10)/10/2,Gt=e.linkDirectionalParticleResolution;K&&K.geometry.parameters.radius===ke&&K.geometry.parameters.widthSegments===Gt?Ue=K.geometry:(ee.hasOwnProperty(ke)||(ee[ke]=new ne.SphereGeometry(ke,Gt,Gt)),Ue=ee[ke]);var Zn=D(U)||g(U)||"#f0f0f0",Cn=new ne.Color(vr(Zn)),yr=e.linkOpacity*3;K&&K.material.color.equals(Cn)&&K.material.opacity===yr?Ie=K.material:(j.hasOwnProperty(Zn)||(j[Zn]=new ne.MeshLambertMaterial({color:Cn,transparent:!0,opacity:yr})),Ie=j[Zn])}K&&(K.geometry!==Ue&&K.geometry.dispose(),K.material!==Ie&&K.material.dispose());var As=Math.round(Math.abs(v(U)));B.__photonDataMapper.id(function(Mn){return Mn.idx}).onCreateObj(function(){return new ne.Mesh(Ue,Ie)}).onUpdateObj(function(Mn){Mn.geometry=Ue,Mn.material=Ie}).digest(Ot(new Array(As)).map(function(Mn,br){return{idx:br}}))}).digest(S.filter(v))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(B){B.source=B[e.linkSource],B.target=B[e.linkTarget]});var re=e.forceEngine!=="ngraph",se;if(re){(se=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var Z=e.d3ForceLayout.force("link");Z&&Z.id(function(B){return B[e.nodeId]}).links(e.graphData.links);var oe=e.dagMode&&Wb(e.graphData,function(B){return B[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),F=Math.max.apply(Math,Ot(Object.values(oe||[]))),G=e.dagLevelDistance||e.graphData.nodes.length/(F||1)*jb*(["radialin","radialout"].indexOf(e.dagMode)!==-1?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){var Q=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(B){return delete B[Q]})}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){var ve=["rl","td","zout"].includes(e.dagMode),I=function(U){return(oe[U[e.nodeId]]-F/2)*G*(ve?-1:1)},H=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(B){return B[H]=I(B)})}e.d3ForceLayout.force("dagRadial",["radialin","radialout"].indexOf(e.dagMode)!==-1?Oy(function(B){var U=oe[B[e.nodeId]]||-1;return(e.dagMode==="radialin"?F-U:U)*G}).strength(function(B){return e.dagNodeFilter(B)?1:0}):null)}else{var le=zc.graph();e.graphData.nodes.forEach(function(B){le.addNode(B[e.nodeId])}),e.graphData.links.forEach(function(B){le.addLink(B.source,B.target)}),se=zc.forcelayout(le,kb({dimensions:e.numDimensions},e.ngraphPhysics)),se.graph=le}for(var Ce=0;Ce<e.warmupTicks&&!(re&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);Ce++)se[re?"tick":"step"]();e.layout=se,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});function Hb(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Object,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=(function(s){function r(){var o;$f(this,r);for(var a=arguments.length,u=new Array(a),l=0;l<a;l++)u[l]=arguments[l];return o=Vf(this,r,[].concat(u)),o.__kapsuleInstance=zf(i,[].concat(Ot(t?[o]:[]),u)),o}return jf(r,s),Wf(r)})(e);return Object.keys(i()).forEach(function(s){return n.prototype[s]=function(){var r,o=(r=this.__kapsuleInstance)[s].apply(r,arguments);return o===this.__kapsuleInstance?this:o}}),n}var Xb=window.THREE?window.THREE:{Group:Oh},Kf=Hb(qb,Xb.Group,!0);/**
|
|
507
|
-
* @license
|
|
508
|
-
* Copyright 2010-2026 Three.js Authors
|
|
509
|
-
* SPDX-License-Identifier: MIT
|
|
510
|
-
*/const Kb=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],va=new WeakMap,Wc=new WeakMap,jc=new WeakMap;class Yb{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=Kb,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1?(this.getRenderObjectData(e),!0):!1}needsVelocity(e){const t=e.getMRT();return t!==null&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){const{geometry:n,object:s}=e;if(t={geometryId:n.id,worldMatrix:s.matrixWorld.clone()},s.center&&(t.center=s.center.clone()),s.morphTargetInfluences&&(t.morphTargetInfluences=s.morphTargetInfluences.slice()),e.bundle!==null&&(t.version=e.bundle.version),e.material.transmission>0){const{width:r,height:o}=e.context;t.bufferWidth=r,t.bufferHeight=o}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const s=e[n];t[n]={id:s.id,version:s.version}}return t}containsNode(e){const t=e.material;for(const n in t)if(t[n]&&t[n].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=jc.get(e);return t===void 0&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},jc.set(e,t)),t}getMaterialData(e){let t=Wc.get(e);if(t===void 0){t={_renderId:-1,_equal:!1};for(const n of this.refreshUniforms){const s=e[n];s!=null&&(typeof s=="object"&&s.clone!==void 0?s.isTexture===!0?t[n]={id:s.id,version:s.version}:t[n]=s.clone():t[n]=s)}Wc.set(e,t)}return t}equals(e,t,n){const{object:s,material:r,geometry:o}=e,a=this.getRenderObjectData(e);if(a.worldMatrix.equals(s.matrixWorld)!==!0)return a.worldMatrix.copy(s.matrixWorld),!1;const u=this.getMaterialData(e.material);if(u._renderId!==n){u._renderId=n;for(const c in u){const d=u[c],h=r[c];if(c!=="_renderId"&&c!=="_equal"){if(d.equals!==void 0){if(d.equals(h)===!1)return d.copy(h),u._equal=!1,!1}else if(h.isTexture===!0){if(d.id!==h.id||d.version!==h.version)return d.id=h.id,d.version=h.version,u._equal=!1,!1}else if(d!==h)return u[c]=h,u._equal=!1,!1}}if(u.transmission>0){const{width:c,height:d}=e.context;if(a.bufferWidth!==c||a.bufferHeight!==d)return a.bufferWidth=c,a.bufferHeight=d,u._equal=!1,!1}u._equal=!0}else if(u._equal===!1)return!1;if(a.geometryId!==o.id)return a.geometryId=o.id,!1;const l=this.getGeometryData(e.geometry);if(l._renderId!==n){l._renderId=n;const c=o.attributes,d=l.attributes;let h=0,f=0;for(const T in c)h++;for(const T in d){f++;const S=d[T],N=c[T];if(N===void 0)return delete d[T],l._equal=!1,!1;if(S.id!==N.id||S.version!==N.version)return S.id=N.id,S.version=N.version,l._equal=!1,!1}if(f!==h)return l.attributes=this.getAttributesData(c),l._equal=!1,!1;const p=o.index,g=l.indexId,m=l.indexVersion,y=p?p.id:null,_=p?p.version:null;if(g!==y||m!==_)return l.indexId=y,l.indexVersion=_,l._equal=!1,!1;if(l.drawRange.start!==o.drawRange.start||l.drawRange.count!==o.drawRange.count)return l.drawRange.start=o.drawRange.start,l.drawRange.count=o.drawRange.count,l._equal=!1,!1;l._equal=!0}else if(l._equal===!1)return!1;if(a.morphTargetInfluences){let c=!1;for(let d=0;d<a.morphTargetInfluences.length;d++)a.morphTargetInfluences[d]!==s.morphTargetInfluences[d]&&(a.morphTargetInfluences[d]=s.morphTargetInfluences[d],c=!0);if(c)return!1}if(a.lights){for(let c=0;c<t.length;c++)if(a.lights[c].map!==t[c].map)return!1}return a.center&&a.center.equals(s.center)===!1?(a.center.copy(s.center),!0):(e.bundle!==null&&(a.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const n of e)n.isSpotLight===!0&&n.map!==null&&t.push({map:n.map.version});return t}getLights(e,t){if(va.has(e)){const s=va.get(e);if(s.renderId===t)return s.lightsData}const n=this.getLightsData(e.getLights());return va.set(e,{renderId:t,lightsData:n}),n}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:n}=t;if(this.renderId!==n)return this.renderId=n,!0;const s=e.object.static===!0,r=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;if(s||r)return!1;const o=this.getLights(e.lightsNode,n);return this.equals(e,o,n)!==!0}}const Qb=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];function Zb(i){const e=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return i.split(`
|
|
511
|
-
`).map(t=>{const n=t.match(e);if(!n)return null;const s=n[1]||n[2]||"",r=n[3].split("?")[0],o=parseInt(n[4],10),a=parseInt(n[5],10),u=r.split("/").pop();return{fn:s,file:u,line:o,column:a}}).filter(t=>t&&!Qb.some(n=>n.test(t.file)))}class at{constructor(e=null){this.isStackTrace=!0,this.stack=Zb(e||new Error().stack)}getLocation(){if(this.stack.length===0)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(this.stack.length===0)return e;const t=this.stack.map(n=>{const s=`${n.file}:${n.line}:${n.column}`;return n.fn?` at ${n.fn} (${s})`:` at ${s}`}).join(`
|
|
512
|
-
`);return`${e}
|
|
513
|
-
${t}`}}function Ll(i,e=0){let t=3735928559^e,n=1103547991^e;if(Array.isArray(i))for(let s=0,r;s<i.length;s++)r=i[s],t=Math.imul(t^r,2654435761),n=Math.imul(n^r,1597334677);else for(let s=0,r;s<i.length;s++)r=i.charCodeAt(s),t=Math.imul(t^r,2654435761),n=Math.imul(n^r,1597334677);return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&n)+(t>>>0)}const ur=i=>Ll(i),oi=i=>Ll(i),kr=(...i)=>Ll(i),Jb=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),qc=new WeakMap;function Yf(i){return Jb.get(i)}function xo(i){if(i==null)return null;const e=typeof i;return i.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":i.isVector2===!0?"vec2":i.isVector3===!0?"vec3":i.isVector4===!0?"vec4":i.isMatrix2===!0?"mat2":i.isMatrix3===!0?"mat3":i.isMatrix4===!0?"mat4":i.isColor===!0?"color":i instanceof ArrayBuffer?"ArrayBuffer":null}function Ul(i,...e){const t=i?i.slice(-4):void 0;return e.length===1&&(t==="vec2"?e=[e[0],e[0]]:t==="vec3"?e=[e[0],e[0],e[0]]:t==="vec4"&&(e=[e[0],e[0],e[0],e[0]])),i==="color"?new Dt(...e):t==="vec2"?new ce(...e):t==="vec3"?new V(...e):t==="vec4"?new ze(...e):t==="mat2"?new Ef(...e):t==="mat3"?new ri(...e):t==="mat4"?new St(...e):i==="bool"?e[0]||!1:i==="float"||i==="int"||i==="uint"?e[0]||0:i==="string"?e[0]||"":i==="ArrayBuffer"?t_(e[0]):null}function Qf(i){let e=qc.get(i);return e===void 0&&(e={},qc.set(i,e)),e}function e_(i){let e="";const t=new Uint8Array(i);for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function t_(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer}const Ti={VERTEX:"vertex"},te={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Mt={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},n_=["fragment","vertex"],Sa=["setup","analyze","generate"],Na=[...n_,"compute"],lr=["x","y","z","w"],s_={analyze:"setup",generate:"analyze"};let r_=0;class X extends Oo{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=te.NONE,this.updateBeforeType=te.NONE,this.updateAfterType=te.NONE,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=r_++,this.stackTrace=null,X.captureStackTrace===!0&&(this.stackTrace=new at)}set needsUpdate(e){e===!0&&this.version++}get uuid(){return this._uuid===null&&(this._uuid=mo.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,te.FRAME)}onRenderUpdate(e){return this.onUpdate(e,te.RENDER)}onObjectUpdate(e){return this.onUpdate(e,te.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const n of Object.getOwnPropertyNames(this)){const s=this[n];if(!(n.startsWith("_")===!0||e.has(s))){if(Array.isArray(s)===!0)for(let r=0;r<s.length;r++){const o=s[r];o&&o.isNode===!0&&t.push({property:n,index:r,childNode:o})}else if(s&&s.isNode===!0)t.push({property:n,childNode:s});else if(s&&Object.getPrototypeOf(s)===Object.prototype)for(const r in s){if(r.startsWith("_")===!0)continue;const o=s[r];o&&o.isNode===!0&&t.push({property:n,index:r,childNode:o})}}}return t}getCacheKey(e=!1,t=null){if(e=e||this.version!==this._cacheKeyVersion,e===!0||this._cacheKey===null){t===null&&(t=new Set);const n=[];for(const{property:s,childNode:r}of this._getChildren(t))n.push(ur(s.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=kr(oi(n),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){const n=e.getDataFromNode(this);let s;return t!==null?(n.typeFromOutput=n.typeFromOutput||{},s=n.typeFromOutput[t],s===void 0&&(s=this.generateNodeType(e,t),n.typeFromOutput[t]=s)):(s=n.type,s===void 0&&(s=this.generateNodeType(e),n.type=s)),s}generateNodeType(e,t=null){const n=e.getNodeProperties(this);return n.outputNode?n.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let n=0;for(const s of this.getChildren())t["node"+n++]=s;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(this.parents===!0){const s=e.getDataFromNode(this,"any");s.stages=s.stages||{},s.stages[e.shaderStage]=s.stages[e.shaderStage]||[],s.stages[e.shaderStage].push(t)}if(n===1){const s=e.getNodeProperties(this);for(const r of Object.values(s))r&&r.isNode===!0&&r.build(e,this)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&n.isNode===!0)return n.build(e,t)}updateBefore(){z("Abstract function.")}updateAfter(){z("Abstract function.")}update(){z("Abstract function.")}before(e){return this._beforeNodes===null&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);if(this._beforeNodes!==null){const u=this._beforeNodes;this._beforeNodes=null;for(const l of u)l.build(e,t);this._beforeNodes=u}const s=e.getDataFromNode(this);s.buildStages=s.buildStages||{},s.buildStages[e.buildStage]=!0;const r=s_[e.buildStage];if(r&&s.buildStages[r]!==!0){const u=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(u)}e.addChain(this);let o=null;const a=e.getBuildStage();if(a==="setup"){e.addNode(this),this.updateReference(e);const u=e.getNodeProperties(this);if(u.initialized!==!0){u.initialized=!0,u.outputNode=this.setup(e)||u.outputNode||null;for(const l of Object.values(u))if(l&&l.isNode===!0){if(l.parents===!0){const c=e.getNodeProperties(l);c.parents=c.parents||[],c.parents.push(this)}l.build(e)}e.addSequentialNode(this)}o=u.outputNode}else if(a==="analyze")this.analyze(e,t);else if(a==="generate"){if(this.generate.length<2){const l=this.getNodeType(e),c=e.getDataFromNode(this);o=c.snippet,o===void 0?c.generated===void 0?(c.generated=!0,o=this.generate(e)||"",c.snippet=o):(z("Node: Recursion detected.",this),o="/* Recursion detected. */"):c.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),o=e.format(o,l,t)}else o=this.generate(e,t)||"";o===""&&t!==null&&t!=="void"&&t!=="OutputType"&&(k(`TSL: Invalid generated code, expected a "${t}".`),o=e.generateConst(t))}return e.removeChain(this),o}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:s,index:r,childNode:o}of t)r!==void 0?(n[s]===void 0&&(n[s]=Number.isInteger(r)?[]:{}),n[s][r]=o.toJSON(e.meta).uuid):n[s]=o.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(e.inputNodes!==void 0){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const s=[];for(const r of e.inputNodes[n])s.push(t[r]);this[n]=s}else if(typeof e.inputNodes[n]=="object"){const s={};for(const r in e.inputNodes[n]){const o=e.inputNodes[n][r];s[r]=t[o]}this[n]=s}else{const s=e.inputNodes[n];this[n]=t[s]}}}toJSON(e){const{uuid:t,type:n}=this,s=e===void 0||typeof e=="string";s&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];r===void 0&&(r={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},s!==!0&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta);function o(a){const u=[];for(const l in a){const c=a[l];delete c.metadata,u.push(c)}return u}if(s){const a=o(e.textures),u=o(e.images),l=o(e.nodes);a.length>0&&(r.textures=a),u.length>0&&(r.images=u),l.length>0&&(r.nodes=l)}return r}}X.captureStackTrace=!1;class cr extends X{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e),n=this.node.build(e),s=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${n}[ ${s} ]`}}class Zf extends X{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const s of this.convertTo.split("|"))(n===null||e.getTypeLength(t)===e.getTypeLength(s))&&(n=s);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,s=this.getNodeType(e),r=n.build(e,s);return e.format(r,s,t)}}class je extends X{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if(e.getBuildStage()==="generate"){const s=e.getVectorType(this.getNodeType(e,t)),r=e.getDataFromNode(this);if(r.propertyName!==void 0)return e.format(r.propertyName,s,t);if(s!=="void"&&t!=="void"&&this.hasDependencies(e)){const o=super.build(e,s),a=e.getVarFromNode(this,null,s),u=e.getPropertyName(a);return e.addLineFlowCode(`${u} = ${o}`,this),r.snippet=o,r.propertyName=u,e.format(r.propertyName,s,t)}}return super.build(e,t)}}class i_ extends je{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return this.nodeType!==null?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){const n=this.getNodeType(e),s=e.getTypeLength(n),r=this.nodes,o=e.getComponentType(n),a=[];let u=0;for(const c of r){if(u>=s){k(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let d=c.getNodeType(e),h=e.getTypeLength(d),f;if(u+h>s&&(k(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),h=s-u,d=e.getTypeFromLength(h)),u+=h,f=c.build(e,d),e.getComponentType(d)!==o){const g=e.getTypeFromLength(h,o);f=e.format(f,d,g)}a.push(f)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const o_=lr.join("");class a_ extends X{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(lr.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const n=this.node,s=e.getTypeLength(n.getNodeType(e));let r=null;if(s>1){let o=null;this.getVectorLength()>=s&&(o=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const u=n.build(e,o);this.components.length===s&&this.components===o_.slice(0,this.components.length)?r=e.format(u,o,t):r=e.format(`${u}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class u_ extends je{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:s}=this,r=this.getNodeType(e),o=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(n.length,o),u=s.build(e,a),l=t.build(e,r),c=e.getTypeLength(r),d=[];for(let h=0;h<c;h++){const f=lr[h];f===n[0]?(d.push(u),h+=n.length-1):d.push(l+"."+f)}return`${e.getType(r)}( ${d.join(", ")} )`}}class l_ extends je{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,s=this.getNodeType(e),r=n.build(e),o=e.getVarFromNode(this),a=e.getPropertyName(o);e.addLineFlowCode(a+" = "+r,this);const u=e.getTypeLength(s),l=[];let c=0;for(let d=0;d<u;d++){const h=lr[d];h===t[c]?(l.push("1.0 - "+(a+"."+h)),c++):l.push(a+"."+h)}return`${e.getType(s)}( ${l.join(", ")} )`}}class Ol extends X{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return this.nodeType===null?xo(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=xo(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=e_(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Ul(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){z("Abstract function.")}}const Hc=/float|u?int/;class un extends Ol{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const n=this.getNodeType(e);return Hc.test(n)&&Hc.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class c_ extends X{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return this.structNode.isMemberNode&&this.structNode.hasMember(e)===!1?!1:this.structNode.getMemberType(e,this.property)!=="void"}generateNodeType(e){return this.hasMember(e)===!1?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(this.hasMember(e)===!1)return"float";const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}generate(e){if(this.hasMember(e)===!1){z(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const n=this.getNodeType(e);return e.generateConst(n)}return this.structNode.build(e)+"."+this.property}}let bs=null;const Ku=new Map;function E(i,e){if(Ku.has(i)){z(`TSL: Redefinition of method chaining '${i}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${i} is not a function`);Ku.set(i,e),i!=="assign"&&(X.prototype[i]=function(...t){return this.isStackNode?this.addToStack(e(...t)):e(this,...t)},X.prototype[i+"Assign"]=function(...t){return this.isStackNode?this.assign(t[0],e(...t)):this.assign(e(this,...t))})}const d_=i=>i.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Xc=i=>d_(i).split("").sort().join("");X.prototype.assign=function(...i){if(this.isStackNode!==!0)return bs!==null?bs.assign(this,...i):k("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new at),this;{const e=Ku.get("assign");return this.addToStack(e(...i))}};X.prototype.toVarIntent=function(){return this};X.prototype.get=function(i){return new c_(this,i)};const Gr={};function vi(i,e,t){Gr[i]=Gr[e]=Gr[t]={get(){this._cache=this._cache||{};let o=this._cache[i];return o===void 0&&(o=new a_(this,i),this._cache[i]=o),o},set(o){this[i].assign(q(o))}};const n=i.toUpperCase(),s=e.toUpperCase(),r=t.toUpperCase();X.prototype["set"+n]=X.prototype["set"+s]=X.prototype["set"+r]=function(o){const a=Xc(i);return new u_(this,a,q(o))},X.prototype["flip"+n]=X.prototype["flip"+s]=X.prototype["flip"+r]=function(){const o=Xc(i);return new l_(this,o)}}const Vt=["x","y","z","w"],$t=["r","g","b","a"],zt=["s","t","p","q"];for(let i=0;i<4;i++){let e=Vt[i],t=$t[i],n=zt[i];vi(e,t,n);for(let s=0;s<4;s++){e=Vt[i]+Vt[s],t=$t[i]+$t[s],n=zt[i]+zt[s],vi(e,t,n);for(let r=0;r<4;r++){e=Vt[i]+Vt[s]+Vt[r],t=$t[i]+$t[s]+$t[r],n=zt[i]+zt[s]+zt[r],vi(e,t,n);for(let o=0;o<4;o++)e=Vt[i]+Vt[s]+Vt[r]+Vt[o],t=$t[i]+$t[s]+$t[r]+$t[o],n=zt[i]+zt[s]+zt[r]+zt[o],vi(e,t,n)}}}for(let i=0;i<32;i++)Gr[i]={get(){this._cache=this._cache||{};let e=this._cache[i];return e===void 0&&(e=new cr(this,new un(i,"uint")),this._cache[i]=e),e},set(e){this[i].assign(q(e))}};Object.defineProperties(X.prototype,Gr);const Kc=new WeakMap,h_=function(i,e=null){const t=xo(i);return t==="node"?i:e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string"?q(Yu(i,e)):t==="shader"?i.isFn?i:M(i):i},f_=function(i,e=null){for(const t in i)i[t]=q(i[t],e);return i},p_=function(i,e=null){const t=i.length;for(let n=0;n<t;n++)i[n]=q(i[n],e);return i},Jf=function(i,e=null,t=null,n=null){function s(c){return n!==null?(c=q(Object.assign(c,n)),n.intent===!0&&(c=c.toVarIntent())):c=q(c),c}let r,o=e,a,u;function l(c){let d;return o?d=/[a-z]/i.test(o)?o+"()":o:d=i.type,a!==void 0&&c.length<a?(k(`TSL: "${d}" parameter length is less than minimum required.`,new at),c.concat(new Array(a-c.length).fill(0))):u!==void 0&&c.length>u?(k(`TSL: "${d}" parameter length exceeds limit.`,new at),c.slice(0,u)):c}return e===null?r=(...c)=>s(new i(...Xs(l(c)))):t!==null?(t=q(t),r=(...c)=>s(new i(e,...Xs(l(c)),t))):r=(...c)=>s(new i(e,...Xs(l(c)))),r.setParameterLength=(...c)=>(c.length===1?a=u=c[0]:c.length===2&&([a,u]=c),r),r.setName=c=>(o=c,r),r},g_=function(i,...e){return new i(...Xs(e))};class m_ extends X{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:n}=this,s=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",o=r||"default";if(s[o])return s[o];const a=e.subBuildFn,u=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;if(t.layout){let c=Kc.get(e.constructor);c===void 0&&(c=new WeakMap,Kc.set(e.constructor,c));let d=c.get(t);d===void 0&&(d=q(e.buildFunctionNode(t)),c.set(t,d)),e.addInclude(d);const h=n?y_(n):null;l=q(d.call(h))}else{const c=new Proxy(e,{get:(g,m,y)=>{let _;return Symbol.iterator===m?_=function*(){yield void 0}:_=Reflect.get(g,m,y),_}}),d=n?b_(n):null,h=Array.isArray(n)?n.length>0:n!==null,f=t.jsFunc,p=h||f.length>1?f(d,c):f(c);l=q(p)}return e.subBuildFn=a,e.fnCall=u,t.once&&(s[o]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null;const s=e.getBuildStage(),r=e.getNodeProperties(this),o=e.getSubBuildOutput(this),a=this.getOutputNode(e),u=e.fnCall;if(e.fnCall=this,s==="setup"){const l=e.getSubBuildProperty("initialized",this);if(r[l]!==!0&&(r[l]=!0,r[o]=this.getOutputNode(e),r[o].build(e),this.shaderNode.subBuilds))for(const c of e.chaining){const d=e.getDataFromNode(c,"any");d.subBuilds=d.subBuilds||new Set;for(const h of this.shaderNode.subBuilds)d.subBuilds.add(h)}n=r[o]}else s==="analyze"?a.build(e,t):s==="generate"&&(n=a.build(e,t)||"");return e.fnCall=u,n}}function y_(i){let e;return Vl(i),i[0]&&(i[0].isNode||Object.getPrototypeOf(i[0])!==Object.prototype)?e=[...i]:e=i[0],e}function b_(i){let e=0;return Vl(i),new Proxy(i,{get:(t,n,s)=>{let r;if(n==="length")return r=i.length,r;if(Symbol.iterator===n)r=function*(){for(const o of i)yield q(o)};else{if(i.length>0)if(Object.getPrototypeOf(i[0])===Object.prototype){const o=i[0];o[n]===void 0?r=o[e++]:r=Reflect.get(o,n,s)}else i[0]instanceof X&&(i[n]===void 0?r=i[e++]:r=Reflect.get(i,n,s));else r=Reflect.get(t,n,s);r=q(r)}return r}})}class __ extends X{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new m_(this,e)}setup(){return this.call()}}const x_=[!1,!0],T_=[0,1,2,3],v_=[-1,-2],ep=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],Il=new Map;for(const i of x_)Il.set(i,new un(i));const kl=new Map;for(const i of T_)kl.set(i,new un(i,"uint"));const Gl=new Map([...kl].map(i=>new un(i.value,"int")));for(const i of v_)Gl.set(i,new un(i,"int"));const zo=new Map([...Gl].map(i=>new un(i.value)));for(const i of ep)zo.set(i,new un(i));for(const i of ep)zo.set(-i,new un(-i));const Wo={bool:Il,uint:kl,ints:Gl,float:zo},Yc=new Map([...Il,...zo]),Yu=(i,e)=>Yc.has(i)?Yc.get(i):i.isNode===!0?i:new un(i,e),qe=function(i,e=null){return(...t)=>{for(const s of t)if(s===void 0)return k(`TSL: Invalid parameter for the type "${i}".`,new at),new un(0,i);if((t.length===0||!["bool","float","int","uint"].includes(i)&&t.every(s=>{const r=typeof s;return r!=="object"&&r!=="function"}))&&(t=[Ul(i,...t)]),t.length===1&&e!==null&&e.has(t[0]))return Si(e.get(t[0]));if(t.length===1){const s=Yu(t[0],i);return s.nodeType===i?Si(s):Si(new Zf(s,i))}const n=t.map(s=>Yu(s));return Si(new i_(n,i))}};function Qu(i){return i&&i.isNode&&i.traverse(e=>{e.isConstNode&&(i=e.value)}),!!i}const S_=i=>i!=null?i.nodeType||i.convertTo||(typeof i=="string"?i:null):null;function Dr(i,e){return new __(i,e)}const q=(i,e=null)=>h_(i,e),Si=(i,e=null)=>q(i,e).toVarIntent(),Vl=(i,e=null)=>new f_(i,e),Xs=(i,e=null)=>new p_(i,e),Ne=(i,e=null,t=null,n=null)=>new Jf(i,e,t,n),O=(i,...e)=>new g_(i,...e),$=(i,e=null,t=null,n={})=>new Jf(i,e,t,{...n,intent:!0});let N_=0;class R_ extends X{constructor(e,t=null){super();let n=null;t!==null&&(typeof t=="object"?n=t.return:(typeof t=="string"?n=t:k("TSL: Invalid layout type.",new at),t=null)),this.shaderNode=new Dr(e,n),t!==null&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if(typeof e.inputs!="object"){const n={name:"fn"+N_++,type:t,inputs:[]};for(const s in e)s!=="return"&&n.inputs.push({name:s,type:e[s]});e=n}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return this.shaderNode.nodeType==="void"&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return k('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function M(i,e=null){const t=new R_(i,e);return new Proxy(()=>{},{apply(n,s,r){return t.call(...r)},get(n,s,r){return Reflect.get(t,s,r)},set(n,s,r,o){return Reflect.set(t,s,r,o)}})}const To=i=>{bs=i},tp=()=>bs,Se=(...i)=>bs.If(...i);function np(i){return bs&&bs.addToStack(i),i}E("toStack",np);const w_=new qe("color"),w=new qe("float",Wo.float),Be=new qe("int",Wo.ints),de=new qe("uint",Wo.uint),jo=new qe("bool",Wo.bool),W=new qe("vec2"),Xt=new qe("ivec2"),sp=new qe("uvec2"),E_=new qe("bvec2"),A=new qe("vec3"),rp=new qe("ivec3"),ip=new qe("uvec3"),A_=new qe("bvec3"),ie=new qe("vec4"),op=new qe("ivec4"),ap=new qe("uvec4"),C_=new qe("bvec4"),$l=new qe("mat2"),Ze=new qe("mat3"),ps=new qe("mat4");E("toColor",w_);E("toFloat",w);E("toInt",Be);E("toUint",de);E("toBool",jo);E("toVec2",W);E("toIVec2",Xt);E("toUVec2",sp);E("toBVec2",E_);E("toVec3",A);E("toIVec3",rp);E("toUVec3",ip);E("toBVec3",A_);E("toVec4",ie);E("toIVec4",op);E("toUVec4",ap);E("toBVec4",C_);E("toMat2",$l);E("toMat3",Ze);E("toMat4",ps);const M_=Ne(cr).setParameterLength(2),B_=(i,e)=>new Zf(q(i),e);E("element",M_);E("convert",B_);E("append",i=>(z("TSL: .append() has been renamed to .toStack().",new at),np(i)));class ye extends X{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return ur(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return this.varying===!0?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const zn=(i,e)=>new ye(i,e),vo=(i,e)=>new ye(i,e,!0),xe=O(ye,"vec4","DiffuseColor"),Is=O(ye,"vec3","DiffuseContribution"),Qc=O(ye,"vec3","EmissiveColor"),bn=O(ye,"float","Roughness"),Gn=O(ye,"float","Metalness"),Zu=O(ye,"float","Clearcoat"),Vr=O(ye,"float","ClearcoatRoughness"),wt=O(ye,"vec3","Sheen"),is=O(ye,"float","SheenRoughness"),zl=O(ye,"float","Iridescence"),Ju=O(ye,"float","IridescenceIOR"),el=O(ye,"float","IridescenceThickness"),tl=O(ye,"float","AlphaT"),ss=O(ye,"float","Anisotropy"),no=O(ye,"vec3","AnisotropyT"),Ks=O(ye,"vec3","AnisotropyB"),_s=O(ye,"color","SpecularColor"),$s=O(ye,"color","SpecularColorBlended"),zs=O(ye,"float","SpecularF90"),nl=O(ye,"float","Shininess"),$r=O(ye,"vec4","Output"),Ra=O(ye,"float","dashSize"),Zc=O(ye,"float","gapSize"),so=O(ye,"float","IOR"),sl=O(ye,"float","Transmission"),up=O(ye,"float","Thickness"),lp=O(ye,"float","AttenuationDistance"),cp=O(ye,"color","AttenuationColor"),dp=O(ye,"float","Dispersion");class hp extends X{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1,s=null){super("string"),this.name=e,this.shared=t,this.order=n,this.updateType=s,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const P_=(i,e=1,t=null)=>new hp(i,!1,e,t),Wl=(i,e=0,t=null)=>new hp(i,!0,e,t);te.FRAME;const J=Wl("render",0,te.RENDER),F_=P_("object",1,te.OBJECT);class ai extends Ol{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=F_}setName(e){return this.name=e,this}label(e){return z('TSL: "label()" has been deprecated. Use "setName()" instead.',new at),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(n=>{const s=e(n,this);s!==void 0&&(this.value=s)},t)}getInputType(e){let t=super.getInputType(e);return t==="bool"&&(t="uint"),t}generate(e,t){const n=this.getNodeType(e),s=this.getUniformHash(e);let r=e.getNodeFromHash(s);r===void 0&&(e.setHashNode(this,s),r=this);const o=r.getInputType(e),a=e.getUniformFromNode(r,o,e.shaderStage,this.name||e.context.nodeName),u=e.getPropertyName(a);e.context.nodeName!==void 0&&delete e.context.nodeName;let l=u;if(n==="bool"){const c=e.getDataFromNode(this);let d=c.propertyName;if(d===void 0){const h=e.getVarFromNode(this,null,"bool");d=e.getPropertyName(h),c.propertyName=d,l=e.format(u,o,n),e.addLineFlowCode(`${d} = ${l}`,this)}l=d}return e.format(l,n,t)}}const Y=(i,e)=>{const t=S_(e||i);if(t===i&&(i=Ul(t)),i&&i.isNode===!0){let n=i.value;i.traverse(s=>{s.isConstNode===!0&&(n=s.value)}),i=n}return new ai(i,t)};class Jc extends je{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(e){return this.nodeType===null?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return this.nodeType===null?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const D_=(...i)=>{let e;if(i.length===1){const t=i[0];e=new Jc(null,t.length,t)}else{const t=i[0],n=i[1];e=new Jc(t,n)}return q(e)};E("toArray",(i,e)=>D_(Array(e).fill(i)));class L_ extends je{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return t!=="void"?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(e.isAvailable("swizzleAssign")===!1&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return lr.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,s=t.getScope(),r=e.getDataFromNode(s);r.assign=!0;const o=e.getNodeProperties(this);o.sourceNode=n,o.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:s}=e.getNodeProperties(this),r=this.needsSplitAssign(e),o=n.build(e),a=n.getNodeType(e),u=s.build(e,a),l=s.getNodeType(e),c=e.getDataFromNode(this);let d;if(c.initialized===!0)t!=="void"&&(d=o);else if(r){const h=e.getVarFromNode(this,null,a),f=e.getPropertyName(h);e.addLineFlowCode(`${f} = ${u}`,this);const p=n.node,m=p.node.context({assign:!0}).build(e);for(let y=0;y<p.components.length;y++){const _=p.components[y];e.addLineFlowCode(`${m}.${_} = ${f}[ ${y} ]`,this)}t!=="void"&&(d=o)}else d=`${o} = ${u}`,(t==="void"||l==="void")&&(e.addLineFlowCode(d,this),t!=="void"&&(d=o));return c.initialized=!0,e.format(d,a,t)}}const U_=Ne(L_).setParameterLength(2);E("assign",U_);class O_ extends je{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],n=this.functionNode,s=n.getInputs(e),r=this.parameters,o=(u,l)=>{const c=l.type,d=c==="pointer";let h;return d?h="&"+u.build(e):h=u.build(e,c),h};if(Array.isArray(r)){if(r.length>s.length)k("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=s.length;else if(r.length<s.length)for(k("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<s.length;)r.push(w(0));for(let u=0;u<r.length;u++)t.push(o(r[u],s[u]))}else for(const u of s){const l=r[u.name];l!==void 0?t.push(o(l,u)):(k(`TSL: Input '${u.name}' not found in 'Fn()'.`),t.push(o(w(0),u)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}const I_=(i,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?Xs(e):Vl(e[0]),new O_(q(i),e));E("call",I_);const k_={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Le extends je{static get type(){return"OperatorNode"}constructor(e,t,n,...s){if(super(),s.length>0){let r=new Le(e,t,n);for(let o=0;o<s.length-1;o++)r=new Le(e,r,s[o]);t=r,n=s[s.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(k_[this.op],t)}generateNodeType(e,t=null){const n=this.op,s=this.aNode,r=this.bNode,o=s.getNodeType(e),a=r?r.getNodeType(e):null;if(o==="void"||a==="void")return t||"void";if(n==="%")return o;if(n==="~"||n==="&"||n==="|"||n==="^"||n===">>"||n==="<<")return e.getIntegerType(o);if(n==="!"||n==="&&"||n==="||"||n==="^^")return"bool";if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">="){const u=Math.max(e.getTypeLength(o),e.getTypeLength(a));return u>1?`bvec${u}`:"bool"}else{if(e.isMatrix(o)){if(a==="float")return o;if(e.isVector(a))return e.getVectorFromMatrix(o);if(e.isMatrix(a))return o}else if(e.isMatrix(a)){if(o==="float")return a;if(e.isVector(o))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(o)?a:o}}generate(e,t){const n=this.op,{aNode:s,bNode:r}=this,o=this.getNodeType(e,t);let a=null,u=null;o!=="void"?(a=s.getNodeType(e),u=r?r.getNodeType(e):null,n==="<"||n===">"||n==="<="||n===">="||n==="=="||n==="!="?e.isVector(a)?u=a:e.isVector(u)?a=u:a!==u&&(a=u="float"):n===">>"||n==="<<"?(a=o,u=e.changeComponentType(u,"uint")):n==="%"?(a=o,u=e.isInteger(a)&&e.isInteger(u)?u:a):e.isMatrix(a)?u==="float"?u="float":e.isVector(u)?u=e.getVectorFromMatrix(a):e.isMatrix(u)||(a=u=o):e.isMatrix(u)?a==="float"?a="float":e.isVector(a)?a=e.getVectorFromMatrix(u):a=u=o:a=u=o):a=u=o;const l=s.build(e,a),c=r?r.build(e,u):null,d=e.getFunctionOperator(n);if(t!=="void"){const h=e.renderer.coordinateSystem===uo;if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">=")return h?e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${c} )`,o,t):e.format(`( ${l} ${n} ${c} )`,o,t):e.format(`( ${l} ${n} ${c} )`,o,t);if(n==="%")return e.isInteger(u)?e.format(`( ${l} % ${c} )`,o,t):e.format(`${this.getOperatorMethod(e,o)}( ${l}, ${c} )`,o,t);if(n==="!"||n==="~")return e.format(`(${n}${l})`,a,t);if(d)return e.format(`${d}( ${l}, ${c} )`,o,t);if(e.isMatrix(a)&&u==="float")return e.format(`( ${c} ${n} ${l} )`,o,t);if(a==="float"&&e.isMatrix(u))return e.format(`${l} ${n} ${c}`,o,t);{let f=`( ${l} ${n} ${c} )`;return!h&&o==="bool"&&e.isVector(a)&&e.isVector(u)&&(f=`all${f}`),e.format(f,o,t)}}else if(a!=="void")return d?e.format(`${d}( ${l}, ${c} )`,o,t):e.isMatrix(a)&&u==="float"?e.format(`${c} ${n} ${l}`,o,t):e.format(`${l} ${n} ${c}`,o,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const pt=$(Le,"+").setParameterLength(2,1/0).setName("add"),ct=$(Le,"-").setParameterLength(2,1/0).setName("sub"),ue=$(Le,"*").setParameterLength(2,1/0).setName("mul"),rn=$(Le,"/").setParameterLength(2,1/0).setName("div"),jl=$(Le,"%").setParameterLength(2).setName("mod"),G_=$(Le,"==").setParameterLength(2).setName("equal"),V_=$(Le,"!=").setParameterLength(2).setName("notEqual"),$_=$(Le,"<").setParameterLength(2).setName("lessThan"),z_=$(Le,">").setParameterLength(2).setName("greaterThan"),W_=$(Le,"<=").setParameterLength(2).setName("lessThanEqual"),j_=$(Le,">=").setParameterLength(2).setName("greaterThanEqual"),q_=$(Le,"&&").setParameterLength(2,1/0).setName("and"),H_=$(Le,"||").setParameterLength(2,1/0).setName("or"),X_=$(Le,"!").setParameterLength(1).setName("not"),K_=$(Le,"^^").setParameterLength(2).setName("xor"),Y_=$(Le,"&").setParameterLength(2).setName("bitAnd"),Q_=$(Le,"~").setParameterLength(1).setName("bitNot"),Z_=$(Le,"|").setParameterLength(2).setName("bitOr"),J_=$(Le,"^").setParameterLength(2).setName("bitXor"),ex=$(Le,"<<").setParameterLength(2).setName("shiftLeft"),tx=$(Le,">>").setParameterLength(2).setName("shiftRight"),nx=M(([i])=>(i.addAssign(1),i)),sx=M(([i])=>(i.subAssign(1),i)),rx=M(([i])=>{const e=Be(i).toConst();return i.addAssign(1),e}),ix=M(([i])=>{const e=Be(i).toConst();return i.subAssign(1),e});E("add",pt);E("sub",ct);E("mul",ue);E("div",rn);E("mod",jl);E("equal",G_);E("notEqual",V_);E("lessThan",$_);E("greaterThan",z_);E("lessThanEqual",W_);E("greaterThanEqual",j_);E("and",q_);E("or",H_);E("not",X_);E("xor",K_);E("bitAnd",Y_);E("bitNot",Q_);E("bitOr",Z_);E("bitXor",J_);E("shiftLeft",ex);E("shiftRight",tx);E("incrementBefore",nx);E("decrementBefore",sx);E("increment",rx);E("decrement",ix);const ox=(i,e)=>(z('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new at),jl(Be(i),Be(e)));E("modInt",ox);class x extends je{static get type(){return"MathNode"}constructor(e,t,n=null,s=null){if(super(),(e===x.MAX||e===x.MIN)&&arguments.length>3){let r=new x(e,t,n);for(let o=2;o<arguments.length-1;o++)r=new x(e,r,arguments[o]);t=r,n=arguments[arguments.length-1],s=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=s,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,s=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),o=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(s)?0:e.getTypeLength(s);return r>o&&r>a?t:o>a?n:a>r?s:t}generateNodeType(e){const t=this.method;return t===x.LENGTH||t===x.DISTANCE||t===x.DOT?"float":t===x.CROSS?"vec3":t===x.ALL||t===x.ANY?"bool":t===x.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:s}=this;let r=null;if(s===x.ONE_MINUS)r=ct(1,t);else if(s===x.RECIPROCAL)r=rn(1,t);else if(s===x.DIFFERENCE)r=bt(ct(t,n));else if(s===x.TRANSFORM_DIRECTION){let o=t,a=n;e.isMatrix(o.getNodeType(e))?a=ie(A(a),0):o=ie(A(o),0);const u=ue(o,a).xyz;r=sn(u)}return r!==null?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let s=this.method;const r=this.getNodeType(e),o=this.getInputType(e),a=this.aNode,u=this.bNode,l=this.cNode,c=e.renderer.coordinateSystem;if(s===x.NEGATE)return e.format("( - "+a.build(e,o)+" )",r,t);{const d=[];return s===x.CROSS?d.push(a.build(e,r),u.build(e,r)):c===uo&&s===x.STEP?d.push(a.build(e,e.getTypeLength(a.getNodeType(e))===1?"float":o),u.build(e,o)):c===uo&&(s===x.MIN||s===x.MAX)?d.push(a.build(e,o),u.build(e,e.getTypeLength(u.getNodeType(e))===1?"float":o)):s===x.REFRACT?d.push(a.build(e,o),u.build(e,o),l.build(e,"float")):s===x.MIX?d.push(a.build(e,o),u.build(e,o),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":o)):(c===Xr&&s===x.ATAN&&u!==null&&(s="atan2"),e.shaderStage!=="fragment"&&(s===x.DFDX||s===x.DFDY)&&(z(`TSL: '${s}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),s="/*"+s+"*/"),d.push(a.build(e,o)),u!==null&&d.push(u.build(e,o)),l!==null&&d.push(l.build(e,o))),e.format(`${e.getMethod(s,r)}( ${d.join(", ")} )`,r,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}x.ALL="all";x.ANY="any";x.RADIANS="radians";x.DEGREES="degrees";x.EXP="exp";x.EXP2="exp2";x.LOG="log";x.LOG2="log2";x.SQRT="sqrt";x.INVERSE_SQRT="inversesqrt";x.FLOOR="floor";x.CEIL="ceil";x.NORMALIZE="normalize";x.FRACT="fract";x.SIN="sin";x.SINH="sinh";x.COS="cos";x.COSH="cosh";x.TAN="tan";x.TANH="tanh";x.ASIN="asin";x.ASINH="asinh";x.ACOS="acos";x.ACOSH="acosh";x.ATAN="atan";x.ATANH="atanh";x.ABS="abs";x.SIGN="sign";x.LENGTH="length";x.NEGATE="negate";x.ONE_MINUS="oneMinus";x.DFDX="dFdx";x.DFDY="dFdy";x.ROUND="round";x.RECIPROCAL="reciprocal";x.TRUNC="trunc";x.FWIDTH="fwidth";x.TRANSPOSE="transpose";x.DETERMINANT="determinant";x.INVERSE="inverse";x.EQUALS="equals";x.MIN="min";x.MAX="max";x.STEP="step";x.REFLECT="reflect";x.DISTANCE="distance";x.DIFFERENCE="difference";x.DOT="dot";x.CROSS="cross";x.POW="pow";x.TRANSFORM_DIRECTION="transformDirection";x.MIX="mix";x.CLAMP="clamp";x.REFRACT="refract";x.SMOOTHSTEP="smoothstep";x.FACEFORWARD="faceforward";const ql=w(1e-6),ax=w(Math.PI),ux=$(x,x.ALL).setParameterLength(1),lx=$(x,x.ANY).setParameterLength(1),cx=$(x,x.RADIANS).setParameterLength(1),dx=$(x,x.DEGREES).setParameterLength(1),fp=$(x,x.EXP).setParameterLength(1),Qr=$(x,x.EXP2).setParameterLength(1),pp=$(x,x.LOG).setParameterLength(1),Rn=$(x,x.LOG2).setParameterLength(1),Wn=$(x,x.SQRT).setParameterLength(1),hx=$(x,x.INVERSE_SQRT).setParameterLength(1),gs=$(x,x.FLOOR).setParameterLength(1),Hl=$(x,x.CEIL).setParameterLength(1),sn=$(x,x.NORMALIZE).setParameterLength(1),on=$(x,x.FRACT).setParameterLength(1),yt=$(x,x.SIN).setParameterLength(1),fx=$(x,x.SINH).setParameterLength(1),Kt=$(x,x.COS).setParameterLength(1),px=$(x,x.COSH).setParameterLength(1),gx=$(x,x.TAN).setParameterLength(1),mx=$(x,x.TANH).setParameterLength(1),yx=$(x,x.ASIN).setParameterLength(1),bx=$(x,x.ASINH).setParameterLength(1),gp=$(x,x.ACOS).setParameterLength(1),_x=$(x,x.ACOSH).setParameterLength(1),xx=$(x,x.ATAN).setParameterLength(1,2),Tx=$(x,x.ATANH).setParameterLength(1),bt=$(x,x.ABS).setParameterLength(1),mp=$(x,x.SIGN).setParameterLength(1),wn=$(x,x.LENGTH).setParameterLength(1),yp=$(x,x.NEGATE).setParameterLength(1),vx=$(x,x.ONE_MINUS).setParameterLength(1),bp=$(x,x.DFDX).setParameterLength(1),_p=$(x,x.DFDY).setParameterLength(1),Sx=$(x,x.ROUND).setParameterLength(1),Nx=$(x,x.RECIPROCAL).setParameterLength(1),Rx=$(x,x.TRUNC).setParameterLength(1),xp=$(x,x.FWIDTH).setParameterLength(1),wx=$(x,x.TRANSPOSE).setParameterLength(1),Ex=$(x,x.DETERMINANT).setParameterLength(1),Ax=$(x,x.INVERSE).setParameterLength(1),sr=$(x,x.MIN).setParameterLength(2,1/0),Je=$(x,x.MAX).setParameterLength(2,1/0),Zr=$(x,x.STEP).setParameterLength(2),Cx=$(x,x.REFLECT).setParameterLength(2),Mx=$(x,x.DISTANCE).setParameterLength(2),Bx=$(x,x.DIFFERENCE).setParameterLength(2),xs=$(x,x.DOT).setParameterLength(2),Ts=$(x,x.CROSS).setParameterLength(2),qo=$(x,x.POW).setParameterLength(2),Tp=i=>ue(i,i),Px=i=>ue(i,i,i),vp=i=>ue(i,i,i,i),Fx=$(x,x.TRANSFORM_DIRECTION).setParameterLength(2),Dx=i=>ue(mp(i),qo(bt(i),1/3)),Sp=i=>xs(i,i),Te=$(x,x.MIX).setParameterLength(3),jn=(i,e=0,t=1)=>new x(x.CLAMP,q(i),q(e),q(t)),Xl=i=>jn(i),Np=$(x,x.REFRACT).setParameterLength(3),En=$(x,x.SMOOTHSTEP).setParameterLength(3),Lx=$(x,x.FACEFORWARD).setParameterLength(3),Ux=M(([i])=>{const n=43758.5453,s=xs(i.xy,W(12.9898,78.233)),r=jl(s,ax);return on(yt(r).mul(n))}),Ox=(i,e,t)=>Te(e,t,i),Ix=(i,e,t)=>En(e,t,i),kx=(i,e)=>Zr(e,i);E("all",ux);E("any",lx);E("radians",cx);E("degrees",dx);E("exp",fp);E("exp2",Qr);E("log",pp);E("log2",Rn);E("sqrt",Wn);E("inverseSqrt",hx);E("floor",gs);E("ceil",Hl);E("normalize",sn);E("fract",on);E("sin",yt);E("sinh",fx);E("cos",Kt);E("cosh",px);E("tan",gx);E("tanh",mx);E("asin",yx);E("asinh",bx);E("acos",gp);E("acosh",_x);E("atan",xx);E("atanh",Tx);E("abs",bt);E("sign",mp);E("length",wn);E("lengthSq",Sp);E("negate",yp);E("oneMinus",vx);E("dFdx",bp);E("dFdy",_p);E("round",Sx);E("reciprocal",Nx);E("trunc",Rx);E("fwidth",xp);E("min",sr);E("max",Je);E("step",kx);E("reflect",Cx);E("distance",Mx);E("dot",xs);E("cross",Ts);E("pow",qo);E("pow2",Tp);E("pow3",Px);E("pow4",vp);E("transformDirection",Fx);E("mix",Ox);E("clamp",jn);E("refract",Np);E("smoothstep",Ix);E("faceForward",Lx);E("difference",Bx);E("saturate",Xl);E("cbrt",Dx);E("transpose",wx);E("determinant",Ex);E("inverse",Ax);E("rand",Ux);class Gx extends X{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}generateNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(n!==null){const r=n.getNodeType(e);if(e.getTypeLength(r)>e.getTypeLength(s))return r}return s}setup(e){const t=this.condNode,n=this.ifNode.isolate(),s=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=r,s!==null&&(e.getDataFromNode(s).parentNodeBlock=r);const o=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=o?n:n.context({nodeBlock:n}),a.elseNode=s?o?s:s.context({nodeBlock:s}):null}generate(e,t){const n=this.getNodeType(e),s=e.getDataFromNode(this);if(s.nodeProperty!==void 0)return s.nodeProperty;const{condNode:r,ifNode:o,elseNode:a}=e.getNodeProperties(this),u=e.currentFunctionNode,l=t!=="void",c=l?zn(n).build(e):"";s.nodeProperty=c;const d=r.build(e,"bool");if(e.context.uniformFlow&&a!==null){const p=o.build(e,n),g=a.build(e,n),m=e.getTernary(d,p,g);return e.format(m,n,t)}e.addFlowCode(`
|
|
514
|
-
${e.tab}if ( ${d} ) {
|
|
515
|
-
|
|
516
|
-
`).addFlowTab();let f=o.build(e,n);if(f&&(l?f=c+" = "+f+";":(f="return "+f+";",u===null&&(z("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),f="// "+f))),e.removeFlowTab().addFlowCode(e.tab+" "+f+`
|
|
517
|
-
|
|
518
|
-
`+e.tab+"}"),a!==null){e.addFlowCode(` else {
|
|
519
|
-
|
|
520
|
-
`).addFlowTab();let p=a.build(e,n);p&&(l?p=c+" = "+p+";":(p="return "+p+";",u===null&&(z("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),p="// "+p))),e.removeFlowTab().addFlowCode(e.tab+" "+p+`
|
|
521
|
-
|
|
522
|
-
`+e.tab+`}
|
|
523
|
-
|
|
524
|
-
`)}else e.addFlowCode(`
|
|
525
|
-
|
|
526
|
-
`);return e.format(c,n,t)}}const Tt=Ne(Gx).setParameterLength(2,3);E("select",Tt);class Rp extends X{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{t.isContextNode===!0&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const n=e.addContext(this.value),s=this.node.build(e,t);return e.setContext(n),s}}const Rs=(i=null,e={})=>{let t=i;return(t===null||t.isNode!==!0)&&(e=t||e,t=null),new Rp(t,e)},Vx=i=>Rs(i,{uniformFlow:!0}),wp=(i,e)=>Rs(i,{nodeName:e});function $x(i,e,t=null){return Rs(t,{getShadow:({light:n,shadowColorNode:s})=>e===n?s.mul(i):s})}function zx(i,e=null){return Rs(e,{getAO:(t,{material:n})=>n.transparent===!0?t:t!==null?t.mul(i):i})}function Wx(i,e){return z('TSL: "label()" has been deprecated. Use "setName()" instead.'),wp(i,e)}E("context",Rs);E("label",Wx);E("uniformFlow",Vx);E("setName",wp);E("builtinShadowContext",(i,e,t)=>$x(e,t,i));E("builtinAOContext",(i,e)=>zx(e,i));class ro extends X{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return e.getDataFromNode(this).forceDeclaration===!0?!1:this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(this._hasStack(t)===!1&&t.buildStage==="setup"&&(t.context.nodeLoop||t.context.nodeBlock)){let n=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&t.fnCall&&t.fnCall.shaderNode&&t.getDataFromNode(this.node.shaderNode).hasLoop){const o=t.getDataFromNode(this);o.forceDeclaration=!0,n=!0}const s=t.getBaseStack();n?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(t)&&this.isAssign(t)!==!0?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:n,readOnly:s}=this,{renderer:r}=e,o=r.backend.isWebGPUBackend===!0;let a=!1,u=!1;s&&(a=e.isDeterministic(t),u=o?s:a);const l=this.getNodeType(e);if(l=="void")return this.isIntent(e)!==!0&&k('TSL: ".toVar()" can not be used with void type.',this.stackTrace),t.build(e);const c=e.getVectorType(l),d=t.build(e,c),h=e.getVarFromNode(this,n,c,void 0,u),f=e.getPropertyName(h);let p=f;if(u)if(o)p=a?`const ${f}`:`let ${f}`;else{const g=t.getArrayCount(e);p=`const ${e.getVar(h.type,f,g)}`}return e.addLineFlowCode(`${p} = ${d}`,this),f}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}}const Kl=Ne(ro),jx=(i,e=null)=>Kl(i,e).toStack(),qx=(i,e=null)=>Kl(i,e,!0).toStack(),Hx=i=>Kl(i).setIntent(!0).toStack();E("toVar",jx);E("toConst",qx);E("toVarIntent",Hx);class Xx extends X{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(this.nodeType!==null)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const n=this.node.build(e,...t);return e.removeSubBuild(),n}}const Ys=(i,e,t=null)=>new Xx(q(i),e,t);class Kx extends X{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Ys(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(n===void 0){const s=this.name,r=this.getNodeType(e),o=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,s,r,o,a),t.node=Ys(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation=e.shaderStage==="fragment"),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ti.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ti.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),s=this.setupVarying(e);if(n[t]===void 0){const r=this.getNodeType(e),o=e.getPropertyName(s,Ti.VERTEX);e.flowNodeFromShaderStage(Ti.VERTEX,n.node,r,o),n[t]=o}return e.getPropertyName(s)}}const ws=Ne(Kx).setParameterLength(1,2),Yx=i=>ws(i);E("toVarying",ws);E("toVertexStage",Yx);const Qx=M(([i])=>{const e=i.mul(.9478672986).add(.0521327014).pow(2.4),t=i.mul(.0773993808),n=i.lessThanEqual(.04045);return Te(e,t,n)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Zx=M(([i])=>{const e=i.pow(.41666).mul(1.055).sub(.055),t=i.mul(12.92),n=i.lessThanEqual(.0031308);return Te(e,t,n)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Yl="WorkingColorSpace",Jx="OutputColorSpace";class Ep extends je{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===Yl?Ge.workingColorSpace:t===Jx?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let r=t;return Ge.enabled===!1||n===s||!n||!s||(Ge.getTransfer(n)===ae&&(r=ie(Qx(r.rgb),r.a)),Ge.getPrimaries(n)!==Ge.getPrimaries(s)&&(r=ie(Ze(Ge._getMatrix(new ri,n,s)).mul(r.rgb),r.a)),Ge.getTransfer(s)===ae&&(r=ie(Zx(r.rgb),r.a))),r}}const eT=(i,e)=>new Ep(q(i),Yl,e),Ql=(i,e)=>new Ep(q(i),e,Yl);E("workingToColorSpace",eT);E("colorSpaceToWorking",Ql);let tT=class extends cr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,n,s)}};class Ap extends X{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,s=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=s,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=te.OBJECT}setGroup(e){return this.group=e,this}element(e){return new tT(this,q(e))}setNodeType(e){const t=Y(null,e);this.group!==null&&t.setGroup(this.group),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let s=1;s<t.length;s++)n=n[t[s]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const nT=(i,e,t)=>new Ap(i,e,t);class sT extends Ap{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(J)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const rT=(i,e,t=null)=>new sT(i,e,t);class iT extends je{static get type(){return"ToneMappingNode"}constructor(e,t=aT,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return kr(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,n=this._toneMapping;if(n===cs)return t;let s=null;const r=e.renderer.library.getToneMappingFunction(n);return r!==null?s=ie(r(t.rgb,this.exposureNode),t.a):(k("ToneMappingNode: Unsupported Tone Mapping configuration.",n),s=t),s}}const oT=(i,e,t)=>new iT(i,q(e),q(t)),aT=rT("toneMappingExposure","float");E("toneMapping",(i,e,t)=>oT(e,t,i));const ed=new WeakMap;function td(i,e){let t=ed.get(i);return t===void 0&&(t=new Ay(i,e),ed.set(i,t)),t}class Bn extends Ol{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=s,this.usage=Bl,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(this.bufferStride===0&&this.bufferOffset===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}generateNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;const t=this.getNodeType(e),n=e.getTypeLength(t),s=this.value,r=this.bufferStride||n,o=this.bufferOffset;let a;s.isInterleavedBuffer===!0?a=s:s.isBufferAttribute===!0?a=td(s.array,r):a=td(s,r);const u=new Ey(a,n,o);a.setUsage(this.usage),this.attribute=u,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),s=e.getPropertyName(n);let r=null;return e.shaderStage==="vertex"||e.shaderStage==="compute"?(this.name=s,r=s):r=ws(this).build(e,t),r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function Zl(i,e=null,t=0,n=0,s=Bl,r=!1){return e==="mat3"||e===null&&i.itemSize===9?Ze(new Bn(i,"vec3",9,0).setUsage(s).setInstanced(r),new Bn(i,"vec3",9,3).setUsage(s).setInstanced(r),new Bn(i,"vec3",9,6).setUsage(s).setInstanced(r)):e==="mat4"||e===null&&i.itemSize===16?ps(new Bn(i,"vec4",16,0).setUsage(s).setInstanced(r),new Bn(i,"vec4",16,4).setUsage(s).setInstanced(r),new Bn(i,"vec4",16,8).setUsage(s).setInstanced(r),new Bn(i,"vec4",16,12).setUsage(s).setInstanced(r)):new Bn(i,e,t,n).setUsage(s)}const Cp=(i,e=null,t=0,n=0)=>Zl(i,e,t,n),nd=(i,e=null,t=0,n=0)=>Zl(i,e,t,n,Bl,!0),sd=(i,e=null,t=0,n=0)=>Zl(i,e,t,n,lo,!0);E("toAttribute",i=>Cp(i.value));class Fe extends X{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let s;if(n===Fe.VERTEX)s=e.getVertexIndex();else if(n===Fe.INSTANCE)s=e.getInstanceIndex();else if(n===Fe.DRAW)s=e.getDrawIndex();else if(n===Fe.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(n===Fe.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else if(n===Fe.SUBGROUP)s=e.getSubgroupIndex();else throw new Error("THREE.IndexNode: Unknown scope: "+n);let r;return e.shaderStage==="vertex"||e.shaderStage==="compute"?r=s:r=ws(this).build(e,t),r}}Fe.VERTEX="vertex";Fe.INSTANCE="instance";Fe.SUBGROUP="subgroup";Fe.INVOCATION_LOCAL="invocationLocal";Fe.INVOCATION_SUBGROUP="invocationSubgroup";Fe.DRAW="draw";const uT=O(Fe,Fe.VERTEX),Qs=O(Fe,Fe.INSTANCE);Fe.SUBGROUP;Fe.INVOCATION_SUBGROUP;Fe.INVOCATION_LOCAL;const lT=O(Fe,Fe.DRAW);class cT extends X{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=te.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return z('TSL: "label()" has been deprecated. Use "setName()" instead.',new at),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){this.count!==null&&this.countNode===null&&(this.countNode=Y(this.count,"uint").onObjectUpdate(()=>this.count));const t=this.computeNode.build(e);if(t){const n=e.getNodeProperties(this);n.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if(n==="compute"){const s=this.computeNode.build(e,"void");if(s!==""&&e.addLineFlowCode(s,this),this.count!==null&&e.allowEarlyReturns===!0){const r=this.countNode.build(e,"uint"),o=Qs.build(e,"uint");e.flow.code=`${e.tab}if ( ${o} >= ${r} ) { return; }
|
|
527
|
-
|
|
528
|
-
${e.flow.code}`}}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const Mp=(i,e=[64])=>{(e.length===0||e.length>3)&&k("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new at);for(let t=0;t<e.length;t++){const n=e[t];(typeof n!="number"||n<=0||!Number.isInteger(n))&&k(`TSL: compute() workgroupSize element at index [ ${t} ] must be a positive integer`,new at)}for(;e.length<3;)e.push(1);return new cT(q(i),e)},dT=(i,e,t)=>{const n=Mp(i,t);return typeof e=="number"?n.count=e:n.dispatchSize=e,n};E("compute",dT);E("computeKernel",Mp);class hT extends X{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const n=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const r=this.node.build(e,...t);return e.setCache(n),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const zr=i=>new hT(q(i));function fT(i,e=!0){return z('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),zr(i).setParent(e)}E("cache",fT);E("isolate",zr);class pT extends X{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return t!==""&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const gT=Ne(pT).setParameterLength(2);E("bypass",gT);const Bp=M(([i,e,t,n=w(0),s=w(1),r=jo(!1)])=>{let o=i.sub(e).div(t.sub(e));return Qu(r)&&(o=o.clamp()),o.mul(s.sub(n)).add(n)});function mT(i,e,t,n=w(0),s=w(1)){return Bp(i,e,t,n,s,!0)}E("remap",Bp);E("remapClamp",mT);class io extends X{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),s=this.snippet;if(n==="void")e.addLineFlowCode(s,this);else return e.format(s,n,t)}}const Yt=Ne(io).setParameterLength(1,2),yT=i=>(i?Tt(i,Yt("discard")):Yt("discard")).toStack();E("discard",yT);class bT extends je{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const n=(this._toneMapping!==null?this._toneMapping:e.toneMapping)||cs,s=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||tr;return n!==cs&&(t=t.toneMapping(n)),s!==tr&&s!==Ge.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Pp=(i,e=null,t=null)=>new bT(q(i),e,t);E("renderOutput",Pp);class _T extends je{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e);if(t!==null)t(e,n);else{const s="--- TSL debug - "+e.shaderStage+" shader ---",r="-".repeat(s.length);let o="";o+="// #"+s+`#
|
|
529
|
-
`,o+=e.flow.code.replace(/^\t/mg,"")+`
|
|
530
|
-
`,o+="/* ... */ "+n+` /* ... */
|
|
531
|
-
`,o+="// #"+r+`#
|
|
532
|
-
`,Cy(o)}return n}}const xT=(i,e=null)=>new _T(q(i),e).toStack();E("debug",xT);class Fp extends Oo{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class TT extends X{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=te.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return e.context.inspector===!0&&this.callback!==null&&(t=this.callback(t)),e.renderer.backend.isWebGPUBackend!==!0&&e.renderer.inspector.constructor!==Fp&&Oe('TSL: ".toInspector()" is only available with WebGPU.'),t}}function vT(i,e="",t=null){return i=q(i),i.before(new TT(i,e,t))}E("toInspector",vT);class Dp extends X{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(t===null){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const s=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){const r=e.geometry.getAttribute(t),o=e.getTypeFromAttribute(r),a=e.getAttribute(t,o);return e.shaderStage==="vertex"?e.format(a.name,o,n):ws(this).build(e,n)}else return z(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const qn=(i,e=null)=>new Dp(i,e),dr=(i=0)=>qn("uv"+(i>0?i:""),"vec2");class ST extends X{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),s=this.levelNode===null?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${s} )`,this.getNodeType(e),t)}}const Zs=Ne(ST).setParameterLength(1,2);class NT extends ai{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=te.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&n.width!==void 0){const{width:s,height:r}=n;this.value=Math.log2(Math.max(s,r))}}}const RT=Ne(NT).setParameterLength(1);class wT extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Lp=new Ml;class ui extends ai{static get type(){return"TextureNode"}constructor(e=Lp,t=null,n=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=te.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return this.value.isDepthTexture===!0?"float":this.value.type===Ve?"uvec4":this.value.type===st?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return dr(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=Y(this.value.matrix)),this._matrixUniform.mul(A(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(this._flipYUniform===null&&(this._flipYUniform=Y(!1)),t=t.toVar(),this.sampler?t=this._flipYUniform.select(t.flipY(),t):t=this._flipYUniform.select(t.setY(Be(Zs(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||n.isTexture!==!0)throw new wT("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const s=M(()=>{let u=this.uvNode;return(u===null||e.context.forceUVContext===!0)&&e.context.getUV&&(u=e.context.getUV(this,e)),u||(u=this.getDefaultUV()),this.updateMatrix===!0&&(u=this.getTransformedUV(u)),u=this.setupUV(e,u),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?te.OBJECT:te.NONE,u})();let r=this.levelNode;r===null&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let o=null,a=null;if(this.compareNode!==null)if(e.renderer.hasCompatibility(Ns.TEXTURE_COMPARE))o=this.compareNode;else{const u=n.compareFunction;u===null||u===Al||u===ii||u===ho||u===er?a=this.compareNode:(o=this.compareNode,Oe('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=s,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=o,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,s,r,o,a,u,l){const c=this.value;let d;return r?d=e.generateTextureBias(c,t,n,r,o,l):u?d=e.generateTextureGrad(c,t,n,u,o,l):a?d=e.generateTextureCompare(c,t,n,a,o,l):this.sampler===!1?d=e.generateTextureLoad(c,t,n,s,o,l):s?d=e.generateTextureLevel(c,t,n,s,o,l):d=e.generateTexture(c,t,n,o,l),d}generate(e,t){const n=this.value,s=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const o=e.getDataFromNode(this),a=this.getNodeType(e);let u=o.propertyName;if(u===void 0){const{uvNode:c,levelNode:d,biasNode:h,compareNode:f,compareStepNode:p,depthNode:g,gradNode:m,offsetNode:y}=s,_=this.generateUV(e,c),T=d?d.build(e,"float"):null,S=h?h.build(e,"float"):null,N=g?g.build(e,"int"):null,R=f?f.build(e,"float"):null,v=p?p.build(e,"float"):null,P=m?[m[0].build(e,"vec2"),m[1].build(e,"vec2")]:null,D=y?this.generateOffset(e,y):null;let L=N;L===null&&n.isArrayTexture&&this.isTexture3DNode!==!0&&(L="0");const j=e.getVarFromNode(this);u=e.getPropertyName(j);let ee=this.generateSnippet(e,r,_,T,S,L,R,P,D);if(v!==null){const re=n.compareFunction;re===ho||re===er?ee=Zr(Yt(ee,a),Yt(v,"float")).build(e,a):ee=Zr(Yt(v,"float"),Yt(ee,a)).build(e,a)}e.addLineFlowCode(`${u} = ${ee}`,this),o.snippet=ee,o.propertyName=u}let l=u;return e.needsToWorkingColorSpace(n)&&(l=Ql(Yt(l,a),n.colorSpace).setup(e).build(e,a)),e.format(l,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=q(e),t.referenceNode=this.getBase(),q(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=q(e).mul(RT(t)),t.referenceNode=this.getBase();const n=t.value;return t.generateMipmaps===!1&&(n&&n.generateMipmaps===!1||n.minFilter===xt||n.magFilter===xt)&&(z("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),q(t)}level(e){const t=this.clone();return t.levelNode=q(e),t.referenceNode=this.getBase(),q(t)}size(e){return Zs(this,e)}bias(e){const t=this.clone();return t.biasNode=q(e),t.referenceNode=this.getBase(),q(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=q(e),t.referenceNode=this.getBase(),q(t)}grad(e,t){const n=this.clone();return n.gradNode=[q(e),q(t)],n.referenceNode=this.getBase(),q(n)}depth(e){const t=this.clone();return t.depthNode=q(e),t.referenceNode=this.getBase(),q(t)}offset(e){const t=this.clone();return t.offsetNode=q(e),t.referenceNode=this.getBase(),q(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix();const n=this._flipYUniform;n!==null&&(n.value=e.image instanceof ImageBitmap&&e.flipY===!0||e.isRenderTargetTexture===!0||e.isFramebufferTexture===!0||e.isDepthTexture===!0)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const ET=Ne(ui).setParameterLength(1,4).setName("texture"),we=(i=Lp,e=null,t=null,n=null)=>{let s;return i&&i.isTextureNode===!0?(s=q(i.clone()),s.referenceNode=i.getBase(),e!==null&&(s.uvNode=q(e)),t!==null&&(s.levelNode=q(t)),n!==null&&(s.biasNode=q(n))):s=ET(i,e,t,n),s},Et=(...i)=>we(...i).setSampler(!1);class Jl extends ai{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Up=(i,e,t)=>new Jl(i,e,t);class AT extends cr{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(e),s=this.node.getPaddedType();return e.format(t,s,n)}}class CT extends Jl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?xo(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=te.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return e==="mat2"?t="mat2":/mat/.test(e)===!0?t="mat4":e.charAt(0)==="i"?t="ivec4":e.charAt(0)==="u"&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if(n==="float"||n==="int"||n==="uint")for(let s=0;s<e.length;s++){const r=s*4;t[r]=e[s]}else if(n==="color")for(let s=0;s<e.length;s++){const r=s*4,o=e[s];t[r]=o.r,t[r+1]=o.g,t[r+2]=o.b||0}else if(n==="mat2")for(let s=0;s<e.length;s++){const r=s*4,o=e[s];t[r]=o.elements[0],t[r+1]=o.elements[1],t[r+2]=o.elements[2],t[r+3]=o.elements[3]}else if(n==="mat3")for(let s=0;s<e.length;s++){const r=s*16,o=e[s];t[r]=o.elements[0],t[r+1]=o.elements[1],t[r+2]=o.elements[2],t[r+4]=o.elements[3],t[r+5]=o.elements[4],t[r+6]=o.elements[5],t[r+8]=o.elements[6],t[r+9]=o.elements[7],t[r+10]=o.elements[8],t[r+15]=1}else if(n==="mat4")for(let s=0;s<e.length;s++){const r=s*16,o=e[s];for(let a=0;a<o.elements.length;a++)t[r+a]=o.elements[a]}else for(let s=0;s<e.length;s++){const r=s*4,o=e[s];t[r]=o.x,t[r+1]=o.y,t[r+2]=o.z||0,t[r+3]=o.w||0}}setup(e){const t=this.array.length,n=this.elementType;let s=Float32Array;const r=this.paddedType,o=e.getTypeLength(r);return n.charAt(0)==="i"&&(s=Int32Array),n.charAt(0)==="u"&&(s=Uint32Array),this.value=new s(t*o),this.bufferCount=t,this.bufferType=r,this.update(),super.setup(e)}element(e){return new AT(this,q(e))}}const At=(i,e)=>new CT(i,e);class MT extends X{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const hr=Ne(MT).setParameterLength(1);let Sr,Nr;class Ee extends X{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===Ee.DPR?"float":this.scope===Ee.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=te.NONE;return(this.scope===Ee.SIZE||this.scope===Ee.VIEWPORT||this.scope===Ee.DPR)&&(e=te.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ee.VIEWPORT?t!==null?Nr.copy(t.viewport):(e.getViewport(Nr),Nr.multiplyScalar(e.getPixelRatio())):this.scope===Ee.DPR?this._output.value=e.getPixelRatio():t!==null?(Sr.width=t.width,Sr.height=t.height):e.getDrawingBufferSize(Sr)}setup(){const e=this.scope;let t=null;return e===Ee.SIZE?t=Y(Sr||(Sr=new ce)):e===Ee.VIEWPORT?t=Y(Nr||(Nr=new ze)):e===Ee.DPR?t=Y(1):t=W(fr.div(rl)),this._output=t,t}generate(e){if(this.scope===Ee.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(rl).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Ee.COORDINATE="coordinate";Ee.VIEWPORT="viewport";Ee.SIZE="size";Ee.UV="uv";Ee.DPR="dpr";const BT=O(Ee,Ee.DPR),ms=O(Ee,Ee.UV),rl=O(Ee,Ee.SIZE),fr=O(Ee,Ee.COORDINATE),Op=O(Ee,Ee.VIEWPORT),PT=Op.zw;Op.xy;let wa=null,Ni=null,Ea=null,Ri=null,Aa=null,wi=null,Ca=null,Ei=null;const Ho=Y(0,"uint").setName("u_cameraIndex").setGroup(Wl("cameraIndex")).toVarying("v_cameraIndex"),os=Y("float").setName("cameraNear").setGroup(J).onRenderUpdate(({camera:i})=>i.near),as=Y("float").setName("cameraFar").setGroup(J).onRenderUpdate(({camera:i})=>i.far),Wr=M(({camera:i})=>{let e;if(i.isArrayCamera&&i.cameras.length>0){const t=[];for(const n of i.cameras)t.push(n.projectionMatrix);Ni===null?Ni=At(t).setGroup(J).setName("cameraProjectionMatrices"):Ni.array=t,e=Ni.element(i.isMultiViewCamera?hr("gl_ViewID_OVR"):Ho).toConst("cameraProjectionMatrix")}else wa===null&&(wa=Y(i.projectionMatrix).setName("cameraProjectionMatrix").setGroup(J).onRenderUpdate(({camera:t})=>t.projectionMatrix)),e=wa;return e}).once()(),FT=M(({camera:i})=>{let e;if(i.isArrayCamera&&i.cameras.length>0){const t=[];for(const n of i.cameras)t.push(n.projectionMatrixInverse);Ri===null?Ri=At(t).setGroup(J).setName("cameraProjectionMatricesInverse"):Ri.array=t,e=Ri.element(i.isMultiViewCamera?hr("gl_ViewID_OVR"):Ho).toConst("cameraProjectionMatrixInverse")}else Ea===null&&(Ea=Y(i.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(J).onRenderUpdate(({camera:t})=>t.projectionMatrixInverse)),e=Ea;return e}).once()(),An=M(({camera:i})=>{let e;if(i.isArrayCamera&&i.cameras.length>0){const t=[];for(const n of i.cameras)t.push(n.matrixWorldInverse);wi===null?wi=At(t).setGroup(J).setName("cameraViewMatrices"):wi.array=t,e=wi.element(i.isMultiViewCamera?hr("gl_ViewID_OVR"):Ho).toConst("cameraViewMatrix")}else Aa===null&&(Aa=Y(i.matrixWorldInverse).setName("cameraViewMatrix").setGroup(J).onRenderUpdate(({camera:t})=>t.matrixWorldInverse)),e=Aa;return e}).once()(),DT=M(({camera:i})=>{let e;if(i.isArrayCamera&&i.cameras.length>0){const t=[];for(let n=0,s=i.cameras.length;n<s;n++)t.push(new V);Ei===null?Ei=At(t).setGroup(J).setName("cameraPositions").onRenderUpdate(({camera:n},s)=>{const r=n.cameras,o=s.array;for(let a=0,u=r.length;a<u;a++)o[a].setFromMatrixPosition(r[a].matrixWorld)}):Ei.array=t,e=Ei.element(i.isMultiViewCamera?hr("gl_ViewID_OVR"):Ho).toConst("cameraPosition")}else Ca===null&&(Ca=Y(new V).setName("cameraPosition").setGroup(J).onRenderUpdate(({camera:t},n)=>n.value.setFromMatrixPosition(t.matrixWorld))),e=Ca;return e}).once()(),rd=new _y;class Me extends X{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=te.OBJECT,this.uniformNode=new ai(null)}generateNodeType(){const e=this.scope;if(e===Me.WORLD_MATRIX)return"mat4";if(e===Me.POSITION||e===Me.VIEW_POSITION||e===Me.DIRECTION||e===Me.SCALE)return"vec3";if(e===Me.RADIUS)return"float"}update(e){const t=this.object3d,n=this.uniformNode,s=this.scope;if(s===Me.WORLD_MATRIX)n.value=t.matrixWorld;else if(s===Me.POSITION)n.value=n.value||new V,n.value.setFromMatrixPosition(t.matrixWorld);else if(s===Me.SCALE)n.value=n.value||new V,n.value.setFromMatrixScale(t.matrixWorld);else if(s===Me.DIRECTION)n.value=n.value||new V,t.getWorldDirection(n.value);else if(s===Me.VIEW_POSITION){const r=e.camera;n.value=n.value||new V,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(r.matrixWorldInverse)}else if(s===Me.RADIUS){const r=e.object.geometry;r.boundingSphere===null&&r.computeBoundingSphere(),rd.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),n.value=rd.radius}}generate(e){const t=this.scope;return t===Me.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Me.POSITION||t===Me.VIEW_POSITION||t===Me.DIRECTION||t===Me.SCALE?this.uniformNode.nodeType="vec3":t===Me.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Me.WORLD_MATRIX="worldMatrix";Me.POSITION="position";Me.SCALE="scale";Me.VIEW_POSITION="viewPosition";Me.DIRECTION="direction";Me.RADIUS="radius";class Ft extends Me{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}Ft.DIRECTION;const vs=O(Ft,Ft.WORLD_MATRIX);Ft.POSITION;Ft.SCALE;Ft.VIEW_POSITION;Ft.RADIUS;const LT=Y(new ri).onObjectUpdate(({object:i},e)=>e.value.getNormalMatrix(i.matrixWorld)),li=M(i=>i.context.modelViewMatrix||UT).once()().toVar("modelViewMatrix"),UT=An.mul(vs),id=M(i=>(i.context.isHighPrecisionModelViewMatrix=!0,Y("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),od=M(i=>{const e=i.context.isHighPrecisionModelViewMatrix;return Y("mat3").onObjectUpdate(({object:t,camera:n})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),OT=M(i=>i.shaderStage!=="fragment"?(Oe("TSL: `clipSpace` is only available in fragment stage."),ie()):i.context.clipSpace.toVarying("v_clipSpace")).once()(),Xo=qn("position","vec3"),Xe=Xo.toVarying("positionLocal"),So=Xo.toVarying("positionPrevious"),rr=M(i=>vs.mul(Xe).xyz.toVarying(i.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Ip=M(()=>Xe.transformDirection(vs).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),$e=M(i=>{if(i.shaderStage==="fragment"&&i.material.vertexNode){const e=FT.mul(OT);return e.xyz.div(e.w).toVar("positionView")}return i.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Ae=M(i=>{let e;return i.camera.isOrthographicCamera?e=A(0,0,1):e=$e.negate().toVarying("v_positionViewDirection").normalize(),e.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class IT extends X{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if(e.shaderStage!=="fragment")return"true";const{material:t}=e;return t.side===ot?"false":e.getFrontFacing()}}const kT=O(IT),kp=w(kT).mul(2).sub(1),ci=M(([i],{material:e})=>{const t=e.side;return t===ot?i=i.mul(-1):t===xn&&(i=i.mul(kp)),i}),Gp=qn("normal","vec3"),an=M(i=>i.geometry.hasAttribute("normal")===!1?(z('TSL: Vertex attribute "normal" not found on geometry.'),A(0,1,0)):Gp,"vec3").once()().toVar("normalLocal"),GT=$e.dFdx().cross($e.dFdy()).normalize().toVar("normalFlat"),Jr=M(i=>{let e;return i.isFlatShading()?e=GT:e=Vp(an).toVarying("v_normalViewGeometry").normalize(),e},"vec3").once()().toVar("normalViewGeometry"),VT=M(i=>{let e=Jr.transformDirection(An);return i.isFlatShading()!==!0&&(e=e.toVarying("v_normalWorldGeometry")),e.normalize().toVar("normalWorldGeometry")},"vec3").once()(),pe=M(i=>{let e;return i.subBuildFn==="NORMAL"||i.subBuildFn==="VERTEX"?(e=Jr,i.isFlatShading()!==!0&&(e=ci(e))):e=i.context.setupNormal().context({getUV:null,getTextureLevel:null}),e},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),pr=pe.transformDirection(An).toVar("normalWorld"),us=M(({subBuildFn:i,context:e})=>{let t;return i==="NORMAL"||i==="VERTEX"?t=pe:t=e.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),$T=M(([i,e=vs])=>{const t=Ze(e),n=i.div(A(t[0].dot(t[0]),t[1].dot(t[1]),t[2].dot(t[2])));return t.mul(n).xyz}),Vp=M(([i],e)=>{const t=e.context.modelNormalViewMatrix;if(t)return t.transformDirection(i);const n=LT.mul(i);return An.transformDirection(n)});M(()=>(z('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),pe)).once(["NORMAL","VERTEX"])();M(()=>(z('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),pr)).once(["NORMAL","VERTEX"])();M(()=>(z('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),us)).once(["NORMAL","VERTEX"])();const Ma=new St,zT=Y(0).onReference(({material:i})=>i).onObjectUpdate(({material:i})=>i.refractionRatio),Ba=Y(1).onReference(({material:i})=>i).onObjectUpdate(function({material:i,scene:e}){return i.envMap?i.envMapIntensity:e.environmentIntensity}),$p=Y(new St).onReference(function(i){return i.material}).onObjectUpdate(function({material:i,scene:e}){const t=e.environment!==null&&i.envMap===null?e.environmentRotation:i.envMapRotation;return t?Ma.makeRotationFromEuler(t).transpose():Ma.identity(),Ma}),WT=Ae.negate().reflect(pe),jT=Ae.negate().refract(pe,zT),qT=WT.transformDirection(An).toVar("reflectVector"),HT=jT.transformDirection(An).toVar("reflectVector"),XT=new Vo;class KT extends ui{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,s=null){super(e,t,n,s),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===yo?qT:e.mapping===bo?HT:(k('CubeTextureNode: Mapping "%s" not supported.',e.mapping),A(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return n.isDepthTexture===!0?e.renderer.coordinateSystem===Xr?A(t.x,t.y.negate(),t.z):t:(t=$p.mul(t),(e.renderer.coordinateSystem===Xr||!n.isRenderTargetTexture)&&(t=A(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}}const YT=Ne(KT).setParameterLength(1,4).setName("cubeTexture"),dt=(i=XT,e=null,t=null,n=null)=>{let s;return i&&i.isCubeTextureNode===!0?(s=q(i.clone()),s.referenceNode=i,e!==null&&(s.uvNode=q(e)),t!==null&&(s.levelNode=q(t)),n!==null&&(s.biasNode=q(n))):s=YT(i,e,t,n),s};class QT extends cr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(e),s=this.getNodeType(e);return e.format(t,n,s)}}class ec extends X{static get type(){return"ReferenceNode"}constructor(e,t,n=null,s=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=s,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=te.OBJECT}element(e){return new QT(this,q(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return z('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;this.count!==null?t=Up(null,e,this.count):Array.isArray(this.getValueFromReference())?t=At(null,e):e==="texture"?t=we(null):e==="cubeTexture"?t=dt(null):t=Y(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.setName(this.name),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let s=1;s<t.length;s++)n=n[t[s]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Pe=(i,e,t)=>new ec(i,e,t),ad=(i,e,t,n)=>new ec(i,e,n,t);class ZT extends ec{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=this.material!==null?this.material:e.material,this.reference}}const In=(i,e,t=null)=>new ZT(i,e,t),zp=dr(),JT=$e.dFdx(),ev=$e.dFdy(),Wp=zp.dFdx(),jp=zp.dFdy(),qp=pe,Hp=ev.cross(qp),Xp=qp.cross(JT),il=Hp.mul(Wp.x).add(Xp.mul(jp.x)),ol=Hp.mul(Wp.y).add(Xp.mul(jp.y)),ud=il.dot(il).max(ol.dot(ol)),Kp=ud.equal(0).select(0,ud.inverseSqrt()),tv=il.mul(Kp).toVar("tangentViewFrame"),nv=ol.mul(Kp).toVar("bitangentViewFrame"),Yp=qn("tangent","vec4"),No=Yp.xyz.toVar("tangentLocal"),Qp=M(i=>{let e;return i.subBuildFn==="VERTEX"||i.geometry.hasAttribute("tangent")?e=li.mul(ie(No,0)).xyz.toVarying("v_tangentView").normalize():e=tv,i.isFlatShading()!==!0&&(e=ci(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),sv=M(([i,e],t)=>{let n=i.mul(Yp.w).xyz;return t.subBuildFn==="NORMAL"&&t.isFlatShading()!==!0&&(n=n.toVarying(e)),n}).once(["NORMAL"]),rv=M(i=>{let e;return i.subBuildFn==="VERTEX"||i.geometry.hasAttribute("tangent")?e=sv(pe.cross(Qp),"v_bitangentView").normalize():e=nv,i.isFlatShading()!==!0&&(e=ci(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Lr=Ze(Qp,rv,pe).toVar("TBNViewMatrix"),iv=M(()=>{let i=Ks.cross(Ae);return i=i.cross(Ks).normalize(),i=Te(i,pe,ss.mul(bn.oneMinus()).oneMinus().pow2().pow2()).normalize(),i}).once()(),ov=i=>q(i).mul(.5).add(.5),ld=i=>A(i,Wn(Xl(w(1).sub(xs(i,i)))));class av extends je{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=ia,this.unpackNormalMode=oa}setup(e){const{normalMapType:t,scaleNode:n,unpackNormalMode:s}=this;let r=this.node.mul(2).sub(1);if(t===ia?s===wf?r=ld(r.xy):s===Ty?r=ld(r.yw):s!==oa&&k(`THREE.NodeMaterial: Unexpected unpack normal mode: ${s}`):s!==oa&&k(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${s}'`),n!==null){let a=n;e.isFlatShading()===!0&&(a=ci(a)),r=A(r.xy.mul(a),r.z)}let o=null;return t===vy?o=Vp(r):t===ia?o=Lr.mul(r).normalize():(k(`NodeMaterial: Unsupported normal map type: ${t}`),o=pe),o}}const cd=Ne(av).setParameterLength(1,2),uv=M(({textureNode:i,bumpScale:e})=>{const t=s=>i.isolate().context({getUV:r=>s(r.uvNode||dr()),forceUVContext:!0}),n=w(t(s=>s));return W(w(t(s=>s.add(s.dFdx()))).sub(n),w(t(s=>s.add(s.dFdy()))).sub(n)).mul(e)}),lv=M(i=>{const{surf_pos:e,surf_norm:t,dHdxy:n}=i,s=e.dFdx().normalize(),r=e.dFdy().normalize(),o=t,a=r.cross(o),u=o.cross(s),l=s.dot(a).mul(kp),c=l.sign().mul(n.x.mul(a).add(n.y.mul(u)));return l.abs().mul(t).sub(c).normalize()});class cv extends je{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=this.scaleNode!==null?this.scaleNode:1,t=uv({textureNode:this.textureNode,bumpScale:e});return lv({surf_pos:$e,surf_norm:pe,dHdxy:t})}}const dv=Ne(cv).setParameterLength(1,2),dd=new Map;class C extends X{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=dd.get(e);return n===void 0&&(n=In(e,t),dd.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache(e==="map"?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let s=null;if(n===C.COLOR){const r=t.color!==void 0?this.getColor(n):A();t.map&&t.map.isTexture===!0?s=r.mul(this.getTexture("map")):s=r}else if(n===C.OPACITY){const r=this.getFloat(n);t.alphaMap&&t.alphaMap.isTexture===!0?s=r.mul(this.getTexture("alpha")):s=r}else if(n===C.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?s=this.getTexture("specular").r:s=w(1);else if(n===C.SPECULAR_INTENSITY){const r=this.getFloat(n);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?s=r.mul(this.getTexture(n).a):s=r}else if(n===C.SPECULAR_COLOR){const r=this.getColor(n);t.specularColorMap&&t.specularColorMap.isTexture===!0?s=r.mul(this.getTexture(n).rgb):s=r}else if(n===C.ROUGHNESS){const r=this.getFloat(n);t.roughnessMap&&t.roughnessMap.isTexture===!0?s=r.mul(this.getTexture(n).g):s=r}else if(n===C.METALNESS){const r=this.getFloat(n);t.metalnessMap&&t.metalnessMap.isTexture===!0?s=r.mul(this.getTexture(n).b):s=r}else if(n===C.EMISSIVE){const r=this.getFloat("emissiveIntensity"),o=this.getColor(n).mul(r);t.emissiveMap&&t.emissiveMap.isTexture===!0?s=o.mul(this.getTexture(n)):s=o}else if(n===C.NORMAL)t.normalMap?(s=cd(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType,(t.normalMap.format==Jt||t.normalMap.format==po||t.normalMap.format==fo)&&(s.unpackNormalMode=wf)):t.bumpMap?s=dv(this.getTexture("bump").r,this.getFloat("bumpScale")):s=pe;else if(n===C.CLEARCOAT){const r=this.getFloat(n);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?s=r.mul(this.getTexture(n).r):s=r}else if(n===C.CLEARCOAT_ROUGHNESS){const r=this.getFloat(n);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?s=r.mul(this.getTexture(n).r):s=r}else if(n===C.CLEARCOAT_NORMAL)t.clearcoatNormalMap?s=cd(this.getTexture(n),this.getCache(n+"Scale","vec2")):s=pe;else if(n===C.SHEEN){const r=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?s=r.mul(this.getTexture("sheenColor").rgb):s=r}else if(n===C.SHEEN_ROUGHNESS){const r=this.getFloat(n);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?s=r.mul(this.getTexture(n).a):s=r,s=s.clamp(1e-4,1)}else if(n===C.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const r=this.getTexture(n);s=$l(Rr.x,Rr.y,Rr.y.negate(),Rr.x).mul(r.rg.mul(2).sub(W(1)).normalize().mul(r.b))}else s=Rr;else if(n===C.IRIDESCENCE_THICKNESS){const r=Pe("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const o=Pe("0","float",t.iridescenceThicknessRange);s=r.sub(o).mul(this.getTexture(n).g).add(o)}else s=r}else if(n===C.TRANSMISSION){const r=this.getFloat(n);t.transmissionMap?s=r.mul(this.getTexture(n).r):s=r}else if(n===C.THICKNESS){const r=this.getFloat(n);t.thicknessMap?s=r.mul(this.getTexture(n).g):s=r}else if(n===C.IOR)s=this.getFloat(n);else if(n===C.LIGHT_MAP)s=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===C.AO)s=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===C.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(n):w(0);else{const r=this.getNodeType(e);s=this.getCache(n,r)}return s}}C.ALPHA_TEST="alphaTest";C.COLOR="color";C.OPACITY="opacity";C.SHININESS="shininess";C.SPECULAR="specular";C.SPECULAR_STRENGTH="specularStrength";C.SPECULAR_INTENSITY="specularIntensity";C.SPECULAR_COLOR="specularColor";C.REFLECTIVITY="reflectivity";C.ROUGHNESS="roughness";C.METALNESS="metalness";C.NORMAL="normal";C.CLEARCOAT="clearcoat";C.CLEARCOAT_ROUGHNESS="clearcoatRoughness";C.CLEARCOAT_NORMAL="clearcoatNormal";C.EMISSIVE="emissive";C.ROTATION="rotation";C.SHEEN="sheen";C.SHEEN_ROUGHNESS="sheenRoughness";C.ANISOTROPY="anisotropy";C.IRIDESCENCE="iridescence";C.IRIDESCENCE_IOR="iridescenceIOR";C.IRIDESCENCE_THICKNESS="iridescenceThickness";C.IOR="ior";C.TRANSMISSION="transmission";C.THICKNESS="thickness";C.ATTENUATION_DISTANCE="attenuationDistance";C.ATTENUATION_COLOR="attenuationColor";C.LINE_SCALE="scale";C.LINE_DASH_SIZE="dashSize";C.LINE_GAP_SIZE="gapSize";C.LINE_WIDTH="linewidth";C.LINE_DASH_OFFSET="dashOffset";C.POINT_SIZE="size";C.DISPERSION="dispersion";C.LIGHT_MAP="light";C.AO="ao";const hv=O(C,C.ALPHA_TEST),fv=O(C,C.COLOR),pv=O(C,C.SHININESS),gv=O(C,C.EMISSIVE),Zp=O(C,C.OPACITY),mv=O(C,C.SPECULAR),hd=O(C,C.SPECULAR_INTENSITY),yv=O(C,C.SPECULAR_COLOR),oo=O(C,C.SPECULAR_STRENGTH),Pa=O(C,C.REFLECTIVITY),bv=O(C,C.ROUGHNESS),_v=O(C,C.METALNESS),xv=O(C,C.NORMAL),Tv=O(C,C.CLEARCOAT),vv=O(C,C.CLEARCOAT_ROUGHNESS),Sv=O(C,C.CLEARCOAT_NORMAL),Nv=O(C,C.ROTATION),Rv=O(C,C.SHEEN),wv=O(C,C.SHEEN_ROUGHNESS),Ev=O(C,C.ANISOTROPY),Av=O(C,C.IRIDESCENCE),Cv=O(C,C.IRIDESCENCE_IOR),Mv=O(C,C.IRIDESCENCE_THICKNESS),Bv=O(C,C.TRANSMISSION),Pv=O(C,C.THICKNESS),Fv=O(C,C.IOR),Dv=O(C,C.ATTENUATION_DISTANCE),Lv=O(C,C.ATTENUATION_COLOR),Uv=O(C,C.LINE_SCALE),Ov=O(C,C.LINE_DASH_SIZE),Iv=O(C,C.LINE_GAP_SIZE);C.LINE_WIDTH;const kv=O(C,C.LINE_DASH_OFFSET),Gv=O(C,C.POINT_SIZE),Vv=O(C,C.DISPERSION),Jp=O(C,C.LIGHT_MAP),$v=O(C,C.AO),Rr=Y(new ce).onReference(function(i){return i.material}).onRenderUpdate(function({material:i}){this.value.set(i.anisotropy*Math.cos(i.anisotropyRotation),i.anisotropy*Math.sin(i.anisotropyRotation))}),zv=M(i=>i.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Wv extends cr{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):"void"}setup(e){return e.isAvailable("storageBuffer")===!1&&this.node.isPBO===!0&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n;const s=e.context.assign;if(e.isAvailable("storageBuffer")===!1?this.node.isPBO===!0&&s!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!=="compute")?n=e.generatePBO(this):n=this.node.build(e):n=super.generate(e),s!==!0){const r=this.getNodeType(e);n=e.format(n,r,t)}return n}}const jv=Ne(Wv).setParameterLength(2);class qv extends Jl{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let s,r=null;t&&t.isStruct?(s="struct",r=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=Yf(e.itemSize),n=e.count):s=t,super(e,s,n),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=Mt.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,e.isStorageBufferAttribute!==!0&&e.isStorageInstancedBufferAttribute!==!0&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(this.bufferCount===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return jv(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Mt.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=Cp(this.value),this._varying=ws(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(this.structTypeNode!==null)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return this.structTypeNode!==null?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(this.structTypeNode!==null&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:n}=this.getAttributeData(),s=n.build(e);return e.registerTransform(s,t),s}}const fd=(i,e=null,t=0)=>new qv(i,e,t);class Hv extends X{static get type(){return"InstanceNode"}constructor(e,t,n=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=n,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=te.FRAME,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&e.isStorageInstancedBufferAttribute===!0}get isStorageColor(){const{instanceColor:e}=this;return e&&e.isStorageInstancedBufferAttribute===!0}setup(e){let{instanceMatrixNode:t,instanceColorNode:n}=this;t===null&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:s,isStorageColor:r}=this;if(s&&n===null){if(r)n=fd(s,"vec3",Math.max(s.count,1)).element(Qs);else{const a=new Sy(s.array,3),u=s.usage===lo?sd:nd;this.bufferColor=a,n=A(u(a,"vec3",3,0))}this.instanceColorNode=n}const o=t.mul(Xe).xyz;if(Xe.assign(o),e.needsPreviousData()&&So.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const a=$T(an,t);an.assign(a)}this.instanceColorNode!==null&&vo("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){this.buffer!==null&&this.isStorageMatrix!==!0&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&this.bufferColor!==null&&this.isStorageColor!==!0&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),this.previousInstanceMatrixNode!==null&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return this.previousInstanceMatrixNode===null&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(So).xyz}_createInstanceMatrixNode(e,t){let n;const{instanceMatrix:s}=this,{count:r}=s;if(this.isStorageMatrix)n=fd(s,"mat4",Math.max(r,1)).element(Qs);else if(r*16*4<=t.getUniformBufferLimit())n=Up(s.array,"mat4",Math.max(r,1)).element(Qs);else{const a=new Ny(s.array,16,1);e===!0&&(this.buffer=a);const u=s.usage===lo?sd:nd,l=[u(a,"vec4",16,0),u(a,"vec4",16,4),u(a,"vec4",16,8),u(a,"vec4",16,12)];n=ps(...l)}return n}}class Xv extends Hv{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:s}=e;super(t,n,s),this.instancedMesh=e}}const Kv=Ne(Xv).setParameterLength(1);class Yv extends X{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){this.batchingIdNode===null&&(e.getDrawIndex()===null?this.batchingIdNode=Qs:this.batchingIdNode=lT);const n=M(([p])=>{const g=Be(Zs(Et(this.batchMesh._indirectTexture),0).x).toConst(),m=Be(p).mod(g).toConst(),y=Be(p).div(g).toConst();return Et(this.batchMesh._indirectTexture,Xt(m,y)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(Be(this.batchingIdNode)),s=this.batchMesh._matricesTexture,r=Be(Zs(Et(s),0).x).toConst(),o=w(n).mul(4).toInt().toConst(),a=o.mod(r).toConst(),u=o.div(r).toConst(),l=ps(Et(s,Xt(a,u)),Et(s,Xt(a.add(1),u)),Et(s,Xt(a.add(2),u)),Et(s,Xt(a.add(3),u))),c=this.batchMesh._colorsTexture;if(c!==null){const g=M(([m])=>{const y=Be(Zs(Et(c),0).x).toConst(),_=m,T=_.mod(y).toConst(),S=_.div(y).toConst();return Et(c,Xt(T,S)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(n);vo("vec3","vBatchColor").assign(g)}const d=Ze(l);Xe.assign(l.mul(Xe));const h=an.div(A(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),f=d.mul(h).xyz;an.assign(f),e.hasGeometryAttribute("tangent")&&No.mulAssign(d)}}const Qv=Ne(Yv).setParameterLength(1),pd=new WeakMap;class Zv extends X{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=te.OBJECT,this.skinIndexNode=qn("skinIndex","uvec4"),this.skinWeightNode=qn("skinWeight","vec4"),this.bindMatrixNode=Pe("bindMatrix","mat4"),this.bindMatrixInverseNode=Pe("bindMatrixInverse","mat4"),this.boneMatricesNode=ad("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Xe,this.toPositionNode=Xe,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:n,skinWeightNode:s,bindMatrixNode:r,bindMatrixInverseNode:o}=this,a=e.element(n.x),u=e.element(n.y),l=e.element(n.z),c=e.element(n.w),d=r.mul(t),h=pt(a.mul(s.x).mul(d),u.mul(s.y).mul(d),l.mul(s.z).mul(d),c.mul(s.w).mul(d));return o.mul(h).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=an,n=No){const{skinIndexNode:s,skinWeightNode:r,bindMatrixNode:o,bindMatrixInverseNode:a}=this,u=e.element(s.x),l=e.element(s.y),c=e.element(s.z),d=e.element(s.w);let h=pt(r.x.mul(u),r.y.mul(l),r.z.mul(c),r.w.mul(d));h=a.mul(h).mul(o);const f=h.transformDirection(t).xyz,p=h.transformDirection(n).xyz;return{skinNormal:f,skinTangent:p}}getPreviousSkinnedPosition(e){const t=e.object;return this.previousBoneMatricesNode===null&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=ad("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,So)}setup(e){e.needsPreviousData()&&So.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:n,skinTangent:s}=this.getSkinnedNormalAndTangent();an.assign(n),e.hasGeometryAttribute("tangent")&&No.assign(s)}return t}generate(e,t){if(t!=="void")return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;pd.get(t)!==e.frameId&&(pd.set(t,e.frameId),this.previousBoneMatricesNode!==null&&(t.previousBoneMatrices===null&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const Jv=i=>new Zv(i);class e0 extends X{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){const t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;const n={};for(let a=0,u=this.params.length-1;a<u;a++){const l=this.params[a],c=l.isNode!==!0&&l.name||this.getVarName(a),d=l.isNode!==!0&&l.type||"int";n[c]=Yt(c,d)}const s=e.addStack(),r=this.params[this.params.length-1](n);t.returnsNode=r.context({nodeLoop:r}),t.stackNode=s;const o=this.params[0];if(o.isNode!==!0&&typeof o.update=="function"){const a=M(this.params[0].update)(n);t.updateNode=a.context({nodeLoop:a})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){const t=e.getDataFromNode(e.fnCall.shaderNode);t.hasLoop=!0}}generate(e){const t=this.getProperties(e),n=this.params,s=t.stackNode;for(let o=0,a=n.length-1;o<a;o++){const u=n[o];let l=!1,c=null,d=null,h=null,f=null,p=null,g=null;u.isNode?u.getNodeType(e)==="bool"?(l=!0,f="bool",d=u.build(e,f)):(f="int",h=this.getVarName(o),c="0",d=u.build(e,f),p="<"):(f=u.type||"int",h=u.name||this.getVarName(o),c=u.start,d=u.end,p=u.condition,g=u.update,typeof c=="number"?c=e.generateConst(f,c):c&&c.isNode&&(c=c.build(e,f)),typeof d=="number"?d=e.generateConst(f,d):d&&d.isNode&&(d=d.build(e,f)),c!==void 0&&d===void 0?(c=c+" - 1",d="0",p=">="):d!==void 0&&c===void 0&&(c="0",p="<"),p===void 0&&(Number(c)>Number(d)?p=">=":p="<"));let m;if(l)m=`while ( ${d} )`;else{const y={start:c,end:d},_=y.start,T=y.end;let S;const N=()=>p.includes("<")?"+=":"-=";if(g!=null)switch(typeof g){case"function":S=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":S=h+" "+N()+" "+e.generateConst(f,g);break;case"string":S=h+" "+g;break;default:g.isNode?S=h+" "+N()+" "+g.build(e):(k("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),S="break /* invalid update */")}else f==="int"||f==="uint"?g=p.includes("<")?"++":"--":g=N()+" 1.",S=h+" "+g;const R=e.getVar(f,h)+" = "+_,v=h+" "+p+" "+T;m=`for ( ${R}; ${v}; ${S} )`}e.addFlowCode((o===0?`
|
|
533
|
-
`:"")+e.tab+m+` {
|
|
534
|
-
|
|
535
|
-
`).addFlowTab()}const r=s.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode(`
|
|
536
|
-
`+e.tab+r);for(let o=0,a=this.params.length-1;o<a;o++)e.addFlowCode((o===0?"":e.tab)+`}
|
|
537
|
-
|
|
538
|
-
`).removeFlowTab();e.addFlowTab()}}const Ct=(...i)=>new e0(Xs(i,"int")).toStack(),t0=()=>Yt("break").toStack(),Fa=new WeakMap,mt=new ze,gd=M(({bufferMap:i,influence:e,stride:t,width:n,depth:s,offset:r})=>{const o=Be(uT).mul(t).add(r),a=o.div(n),u=o.sub(a.mul(n));return Et(i,Xt(u,a)).depth(s).xyz.mul(e)});function n0(i){const e=i.morphAttributes.position!==void 0,t=i.morphAttributes.normal!==void 0,n=i.morphAttributes.color!==void 0,s=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,r=s!==void 0?s.length:0;let o=Fa.get(i);if(o===void 0||o.count!==r){let y=function(){g.dispose(),Fa.delete(i),i.removeEventListener("dispose",y)};o!==void 0&&o.texture.dispose();const a=i.morphAttributes.position||[],u=i.morphAttributes.normal||[],l=i.morphAttributes.color||[];let c=0;e===!0&&(c=1),t===!0&&(c=2),n===!0&&(c=3);let d=i.attributes.position.count*c,h=1;const f=4096;d>f&&(h=Math.ceil(d/f),d=f);const p=new Float32Array(d*h*4*r),g=new Ry(p,d,h,r);g.type=rt,g.needsUpdate=!0;const m=c*4;for(let _=0;_<r;_++){const T=a[_],S=u[_],N=l[_],R=d*h*4*_;for(let v=0;v<T.count;v++){const P=v*m;e===!0&&(mt.fromBufferAttribute(T,v),p[R+P+0]=mt.x,p[R+P+1]=mt.y,p[R+P+2]=mt.z,p[R+P+3]=0),t===!0&&(mt.fromBufferAttribute(S,v),p[R+P+4]=mt.x,p[R+P+5]=mt.y,p[R+P+6]=mt.z,p[R+P+7]=0),n===!0&&(mt.fromBufferAttribute(N,v),p[R+P+8]=mt.x,p[R+P+9]=mt.y,p[R+P+10]=mt.z,p[R+P+11]=N.itemSize===4?mt.w:1)}}o={count:r,texture:g,stride:c,size:new ce(d,h)},Fa.set(i,o),i.addEventListener("dispose",y)}return o}class s0 extends X{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Y(1),this.updateType=te.OBJECT}setup(e){const{geometry:t}=e,n=t.morphAttributes.position!==void 0,s=t.hasAttribute("normal")&&t.morphAttributes.normal!==void 0,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,o=r!==void 0?r.length:0,{texture:a,stride:u,size:l}=n0(t);n===!0&&Xe.mulAssign(this.morphBaseInfluence),s===!0&&an.mulAssign(this.morphBaseInfluence);const c=Be(l.width);Ct(o,({i:d})=>{const h=w(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?h.assign(Et(this.mesh.morphTexture,Xt(Be(d).add(1),Be(Qs))).r):h.assign(Pe("morphTargetInfluences","float").element(d).toVar()),Se(h.notEqual(0),()=>{n===!0&&Xe.addAssign(gd({bufferMap:a,influence:h,stride:u,width:c,depth:d,offset:Be(0)})),s===!0&&an.addAssign(gd({bufferMap:a,influence:h,stride:u,width:c,depth:d,offset:Be(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((t,n)=>t+n,0)}}const r0=Ne(s0).setParameterLength(1);class gr extends X{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class i0 extends gr{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class o0 extends Rp{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,s=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=s,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n=A().toVar("directDiffuse"),s=A().toVar("directSpecular"),r=A().toVar("indirectDiffuse"),o=A().toVar("indirectSpecular"),a={directDiffuse:n,directSpecular:s,indirectDiffuse:r,indirectSpecular:o};return{radiance:A().toVar("radiance"),irradiance:A().toVar("irradiance"),iblIrradiance:A().toVar("iblIrradiance"),ambientOcclusion:w(1).toVar("ambientOcclusion"),reflectedLight:a,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const a0=Ne(o0);class u0 extends gr{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const Jn=new ce;class eg extends ui{static get type(){return"ViewportTextureNode"}constructor(e=ms,t=null,n=null){let s=null;n===null?(s=new Kh,s.minFilter=fs,n=s):s=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=te.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),e===null)return t;if(n.has(e)===!1){const s=t.clone();n.set(e,s)}return n.get(e)}updateReference(e){const t=e.renderer,n=t.getRenderTarget(),s=t.getCanvasTarget(),r=n||s;return this.value=this.getTextureForReference(r),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget(),s=t.getCanvasTarget(),r=n||s;r===null?t.getDrawingBufferSize(Jn):r.getDrawingBufferSize?r.getDrawingBufferSize(Jn):Jn.set(r.width,r.height);const o=this.getTextureForReference(r);(o.image.width!==Jn.width||o.image.height!==Jn.height)&&(o.image.width=Jn.width,o.image.height=Jn.height,o.needsUpdate=!0);const a=o.generateMipmaps;o.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(o),o.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const tg=Ne(eg,null,null,{generateMipmaps:!0}).setParameterLength(0,3),l0=tg(),c0=(i=ms,e=null)=>l0.sample(i,e);let Da=null;class d0 extends eg{static get type(){return"ViewportDepthTextureNode"}constructor(e=ms,t=null,n=null){n===null&&(Da===null&&(Da=new nn),n=Da),super(e,t,n)}}const h0=Ne(d0).setParameterLength(0,3);class ft extends X{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===ft.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let s=null;if(t===ft.DEPTH_BASE)n!==null&&(s=ig().assign(n));else if(t===ft.DEPTH)e.isPerspectiveCamera?s=ng($e.z,os,as):s=jr($e.z,os,as);else if(t===ft.LINEAR_DEPTH)if(n!==null)if(e.isPerspectiveCamera){const r=sg(n,os,as);s=jr(r,os,as)}else s=n;else s=jr($e.z,os,as);return s}}ft.DEPTH_BASE="depthBase";ft.DEPTH="depth";ft.LINEAR_DEPTH="linearDepth";const jr=(i,e,t)=>i.add(e).div(e.sub(t)),ng=(i,e,t)=>e.add(i).mul(t).div(t.sub(e).mul(i)),f0=(i,e,t)=>e.mul(i.add(t)).div(i.mul(e.sub(t))),sg=M(([i,e,t],n)=>n.renderer.reversedDepthBuffer===!0?e.mul(t).div(e.sub(t).mul(i).sub(e)):e.mul(t).div(t.sub(e).mul(i).sub(t))),rg=(i,e,t)=>{e=e.max(1e-6).toVar();const n=Rn(i.negate().div(e)),s=Rn(t.div(e));return n.div(s)},ig=Ne(ft,ft.DEPTH_BASE),og=O(ft,ft.DEPTH),p0=Ne(ft,ft.LINEAR_DEPTH).setParameterLength(0,1);h0();og.assign=i=>ig(i);class Pt extends X{static get type(){return"ClippingNode"}constructor(e=Pt.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:s}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===Pt.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,s):this.scope===Pt.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(n,s)}setupAlphaToCoverage(e,t){return M(()=>{const n=w().toVar("distanceToPlane"),s=w().toVar("distanceToGradient"),r=w(1).toVar("clipOpacity"),o=t.length;if(this.hardwareClipping===!1&&o>0){const u=At(t).setGroup(J);Ct(o,({i:l})=>{const c=u.element(l);n.assign($e.dot(c.xyz).negate().add(c.w)),s.assign(n.fwidth().div(2)),r.mulAssign(En(s.negate(),s,n))})}const a=e.length;if(a>0){const u=At(e).setGroup(J),l=w(1).toVar("intersectionClipOpacity");Ct(a,({i:c})=>{const d=u.element(c);n.assign($e.dot(d.xyz).negate().add(d.w)),s.assign(n.fwidth().div(2)),l.mulAssign(En(s.negate(),s,n).oneMinus())}),r.mulAssign(l.oneMinus())}xe.a.mulAssign(r),xe.a.equal(0).discard()})()}setupDefault(e,t){return M(()=>{const n=t.length;if(this.hardwareClipping===!1&&n>0){const r=At(t).setGroup(J);Ct(n,({i:o})=>{const a=r.element(o);$e.dot(a.xyz).greaterThan(a.w).discard()})}const s=e.length;if(s>0){const r=At(e).setGroup(J),o=jo(!0).toVar("clipped");Ct(s,({i:a})=>{const u=r.element(a);o.assign($e.dot(u.xyz).greaterThan(u.w).and(o))}),o.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),M(()=>{const s=At(e).setGroup(J),r=hr(t.getClipDistance());Ct(n,({i:o})=>{const a=s.element(o),u=$e.dot(a.xyz).sub(a.w).negate();r.element(o).assign(u)})})()}}Pt.ALPHA_TO_COVERAGE="alphaToCoverage";Pt.DEFAULT="default";Pt.HARDWARE="hardware";const g0=()=>new Pt,m0=()=>new Pt(Pt.ALPHA_TO_COVERAGE),y0=()=>new Pt(Pt.HARDWARE),b0=.05,md=M(([i])=>on(ue(1e4,yt(ue(17,i.x).add(ue(.1,i.y)))).mul(pt(.1,bt(yt(ue(13,i.y).add(i.x))))))),yd=M(([i])=>md(W(md(i.xy),i.z))),_0=M(([i])=>{const e=Je(wn(bp(i.xyz)),wn(_p(i.xyz))),t=w(1).div(w(b0).mul(e)).toVar("pixScale"),n=W(Qr(gs(Rn(t))),Qr(Hl(Rn(t)))),s=W(yd(gs(n.x.mul(i.xyz))),yd(gs(n.y.mul(i.xyz)))),r=on(Rn(t)),o=pt(ue(r.oneMinus(),s.x),ue(r,s.y)),a=sr(r,r.oneMinus()),u=A(o.mul(o).div(ue(2,a).mul(ct(1,a))),o.sub(ue(.5,a)).div(ct(1,a)),ct(1,ct(1,o).mul(ct(1,o)).div(ue(2,a).mul(ct(1,a))))),l=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(u.x,u.y),u.z);return jn(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class x0 extends Dp{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e),n=e.hasGeometryAttribute(t);let s;return n===!0?s=super.generate(e):s=e.generateConst(this.nodeType,new ze(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const T0=(i=0)=>new x0(i),v0=M(([i])=>ie(i.rgb.mul(i.a),i.a),{color:"vec4",return:"vec4"});class We extends dc{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(t.startsWith("_")===!0)continue;const n=this[t];n&&n.isNode===!0&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:n}of this._getNodeChildren())e.push(ur(t.slice(0,-4)),n.getCacheKey());return this.type+oi(e)}build(e){this.setup(e)}setupObserver(e){return new Yb(e)}setup(e){e.context.setupNormal=()=>Ys(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const s=this.setupVertex(e),r=Ys(this.vertexNode||s,"VERTEX");e.context.clipSpace=r,e.stack.outputNode=r,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();let o;const a=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(n!==null?n.depthBuffer===!0&&this.setupDepth(e):t.depth===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupVariants(e);const u=this.setupLighting(e);a!==null&&e.stack.addToStack(a);const l=ie(u,xe.a).max(0);o=this.setupOutput(e,l),$r.assign(o);const c=this.outputNode!==null;if(c&&(o=this.outputNode),e.context.getOutput&&(o=e.context.getOutput(o,e)),n!==null){const d=t.getMRT(),h=this.mrtNode;d!==null?(c&&$r.assign(o),o=d,h!==null&&(o=d.merge(h))):h!==null&&(o=h)}}else{let u=this.fragmentNode;u.isOutputStructNode!==!0&&(u=ie(u)),o=this.setupOutput(e,u)}e.stack.outputNode=o,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let s=null;if(t.length>0||n.length>0){const r=e.renderer.currentSamples;this.alphaToCoverage&&r>1?s=m0():e.stack.addToStack(g0())}return s}setupHardwareClipping(e){if(this.hardwareClipping=!1,e.clippingContext===null)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(y0()),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let s=this.depthNode;if(s===null){const r=t.getMRT();r&&r.has("depth")?s=r.get("depth"):t.logarithmicDepthBuffer===!0&&(n.isPerspectiveCamera?s=rg($e.z,os,as):s=jr($e.z,os,as))}s!==null&&og.assign(s).toStack()}setupPositionView(){return li.mul(Xe).xyz}setupModelViewProjection(){return Wr.mul($e)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),zv}setupPosition(e){const{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&r0(t).toStack(),t.isSkinnedMesh===!0&&Jv(t).toStack(),this.displacementMap){const s=In("displacementMap","texture"),r=In("displacementScale","float"),o=In("displacementBias","float");Xe.addAssign(an.normalize().mul(s.x.mul(r).add(o)))}return t.isBatchedMesh&&Qv(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&Kv(t).toStack(),this.positionNode!==null&&Xe.assign(Ys(this.positionNode,"POSITION","vec3")),Xe}setupDiffuseColor(e){const{object:t,geometry:n}=e;this.maskNode!==null&&jo(this.maskNode).not().discard();let s=this.colorNode?ie(this.colorNode):fv;this.vertexColors===!0&&n.hasAttribute("color")&&(s=s.mul(T0())),t.instanceColor&&(s=vo("vec3","vInstanceColor").mul(s)),t.isBatchedMesh&&t._colorsTexture&&(s=vo("vec3","vBatchColor").mul(s)),xe.assign(s);const r=this.opacityNode?w(this.opacityNode):Zp;xe.a.assign(xe.a.mul(r));let o=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(o=this.alphaTestNode!==null?w(this.alphaTestNode):hv,this.alphaToCoverage===!0?(xe.a=En(o,o.add(xp(xe.a)),xe.a),xe.a.lessThanEqual(0).discard()):xe.a.lessThanEqual(o).discard()),this.alphaHash===!0&&xe.a.lessThan(_0(Xe)).discard(),e.isOpaque()&&xe.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?A(0):xe.rgb}setupNormal(){return this.normalNode?A(this.normalNode):xv}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?In("envMap","cubeTexture"):In("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new u0(Jp)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const s=this.setupLightMap(e);s&&s.isLightingNode&&t.push(s);let r=this.aoNode;r===null&&e.material.aoMap&&(r=$v),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new i0(r));let o=this.lightsNode||e.lightsNode;return t.length>0&&(o=e.renderer.lighting.createNode([...o.getLights(),...t])),o}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:s,emissiveNode:r}=this,a=this.lights===!0||this.lightsNode!==null?this.setupLights(e):null;let u=this.setupOutgoingLight(e);if(a&&a.getScope().hasLights){const l=this.setupLightingModel(e)||null;u=a0(a,l,n,s)}else n!==null&&(u=A(s!==null?Te(u,n,s):n));return(r&&r.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(Qc.assign(A(r||gv)),u=u.add(Qc)),u}setupFog(e,t){const n=e.fogNode;return n&&($r.assign(t),t=ie(n.toVar())),t}setupPremultipliedAlpha(e,t){return v0(t)}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),this.premultipliedAlpha===!0&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const n in e){const s=e[n];this[n]===void 0&&(this[n]=s,s&&s.clone&&(this[n]=s.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const n in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,n)===void 0&&t[n].get!==void 0&&Object.defineProperty(this.constructor.prototype,n,t[n])}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{},nodes:{}});const n=dc.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:r,childNode:o}of this._getNodeChildren())n.inputNodes[r]=o.toJSON(e).uuid;function s(r){const o=[];for(const a in r){const u=r[a];delete u.metadata,o.push(u)}return o}if(t){const r=s(e.textures),o=s(e.images),a=s(e.nodes);r.length>0&&(n.textures=r),o.length>0&&(n.images=o),a.length>0&&(n.nodes=a)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const S0=new Gh;class N0 extends We{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(S0),this.setValues(e)}}const R0=new Vm;class w0 extends We{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(R0),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?w(this.offsetNode):kv,t=this.dashScaleNode?w(this.dashScaleNode):Uv,n=this.dashSizeNode?w(this.dashSizeNode):Ov,s=this.gapSizeNode?w(this.gapSizeNode):Iv;Ra.assign(n),Zc.assign(s);const r=ws(qn("lineDistance").mul(t));(e?r.add(e):r).mod(Ra.add(Zc)).greaterThan(Ra).discard()}}const E0=new km;class A0 extends We{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(E0),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?w(this.opacityNode):Zp;xe.assign(Ql(ie(ov(pe),e),xl))}}const ag=M(([i=Ip])=>{const e=i.z.atan(i.x).mul(1/(Math.PI*2)).add(.5),t=i.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return W(e,t)});class ug extends Ss{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new Vo(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,s=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new Af(5,5,5),o=ag(Ip),a=new We;a.colorNode=we(t,o,0),a.side=ot,a.blending=Nn;const u=new kt(r,a),l=new Tl;l.add(u),t.minFilter===fs&&(t.minFilter=vt);const c=new my(1,10,this),d=e.getMRT();return e.setMRT(null),c.update(e,l),e.setMRT(d),t.minFilter=n,t.generateMipmaps=s,u.geometry.dispose(),u.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,s);e.setRenderTarget(r)}}const qr=new WeakMap;class C0 extends je{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=dt(null);const t=new Vo;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=te.RENDER}updateBefore(e){const{renderer:t,material:n}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const r=s.isTextureNode?s.value:n[s.property];if(r&&r.isTexture){const o=r.mapping;if(o===Rl||o===wl){if(qr.has(r)){const a=qr.get(r);bd(a,r.mapping),this._cubeTexture=a}else{const a=r.image;if(M0(a)){const u=new ug(a.height);u.fromEquirectangularTexture(t,r),bd(u.texture,r.mapping),this._cubeTexture=u.texture,qr.set(r,u.texture),r.addEventListener("dispose",lg)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function M0(i){return i==null?!1:i.height>0}function lg(i){const e=i.target;e.removeEventListener("dispose",lg);const t=qr.get(e);t!==void 0&&(qr.delete(e),t.dispose())}function bd(i,e){e===Rl?i.mapping=yo:e===wl&&(i.mapping=bo)}const cg=Ne(C0).setParameterLength(1);class tc extends gr{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=cg(this.envNode)}}class B0 extends gr{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=w(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Ko{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class dg extends Ko{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,s=e.irradianceLightMap;n.indirectDiffuse.assign(ie(0)),s?n.indirectDiffuse.addAssign(s):n.indirectDiffuse.addAssign(ie(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(xe.rgb)}finish(e){const{material:t,context:n}=e,s=n.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case gy:s.rgb.assign(Te(s.rgb,s.rgb.mul(r.rgb),oo.mul(Pa)));break;case py:s.rgb.assign(Te(s.rgb,r.rgb,oo.mul(Pa)));break;case fy:s.rgb.addAssign(r.rgb.mul(oo.mul(Pa)));break;default:z("BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const P0=new On;class F0 extends We{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(P0),this.setValues(e)}setupNormal(){return ci(Jr)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new tc(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new B0(Jp)),t}setupOutgoingLight(){return xe.rgb}setupLightingModel(){return new dg}}const ei=M(({f0:i,f90:e,dotVH:t})=>{const n=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return i.mul(n.oneMinus()).add(e.mul(n))}),ir=M(i=>i.diffuseColor.mul(1/Math.PI)),D0=()=>w(.25),L0=M(({dotNH:i})=>nl.mul(w(.5)).add(1).mul(w(1/Math.PI)).mul(i.pow(nl))),U0=M(({lightDirection:i})=>{const e=i.add(Ae).normalize(),t=pe.dot(e).clamp(),n=Ae.dot(e).clamp(),s=ei({f0:_s,f90:1,dotVH:n}),r=D0(),o=L0({dotNH:t});return s.mul(r).mul(o)});class hg extends dg{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=pe.dot(e).clamp().mul(t);n.directDiffuse.addAssign(r.mul(ir({diffuseColor:xe.rgb}))),this.specular===!0&&n.directSpecular.addAssign(r.mul(U0({lightDirection:e})).mul(oo))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(n.mul(ir({diffuseColor:xe}))),s.indirectDiffuse.mulAssign(t)}}const O0=new Uh;class I0 extends We{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(O0),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new tc(t):null}setupLightingModel(){return new hg(!1)}}const k0=new Lm;class G0 extends We{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(k0),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new tc(t):null}setupLightingModel(){return new hg}setupVariants(){const e=(this.shininessNode?w(this.shininessNode):pv).max(1e-4);nl.assign(e);const t=this.specularNode||mv;_s.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const V0=M(i=>{if(i.geometry.hasAttribute("normal")===!1)return w(0);const e=Jr.dFdx().abs().max(Jr.dFdy().abs());return e.x.max(e.y).max(e.z)}),fg=M(i=>{const{roughness:e}=i,t=V0();let n=e.max(.0525);return n=n.add(t),n=n.min(1),n}),$0=M(({alpha:i,dotNL:e,dotNV:t})=>{const n=i.pow2(),s=e.mul(n.add(n.oneMinus().mul(t.pow2())).sqrt()),r=t.mul(n.add(n.oneMinus().mul(e.pow2())).sqrt());return rn(.5,s.add(r).max(ql))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),z0=M(({alphaT:i,alphaB:e,dotTV:t,dotBV:n,dotTL:s,dotBL:r,dotNV:o,dotNL:a})=>{const u=a.mul(A(i.mul(t),e.mul(n),o).length()),l=o.mul(A(i.mul(s),e.mul(r),a).length());return rn(.5,u.add(l).max(ql))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),W0=M(({alpha:i,dotNH:e})=>{const t=i.pow2(),n=e.pow2().mul(t.oneMinus()).oneMinus();return t.div(n.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),j0=w(1/Math.PI),q0=M(({alphaT:i,alphaB:e,dotNH:t,dotTH:n,dotBH:s})=>{const r=i.mul(e),o=A(e.mul(n),i.mul(s),r.mul(t)),a=o.dot(o),u=r.div(a);return j0.mul(r.mul(u.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),pg=M(({lightDirection:i,f0:e,f90:t,roughness:n,f:s,normalView:r=pe,USE_IRIDESCENCE:o,USE_ANISOTROPY:a})=>{const u=n.pow2(),l=i.add(Ae).normalize(),c=r.dot(i).clamp(),d=r.dot(Ae).clamp(),h=r.dot(l).clamp(),f=Ae.dot(l).clamp();let p=ei({f0:e,f90:t,dotVH:f}),g,m;if(Qu(o)&&(p=zl.mix(p,s)),Qu(a)){const y=no.dot(i),_=no.dot(Ae),T=no.dot(l),S=Ks.dot(i),N=Ks.dot(Ae),R=Ks.dot(l);g=z0({alphaT:tl,alphaB:u,dotTV:_,dotBV:N,dotTL:y,dotBL:S,dotNV:d,dotNL:c}),m=q0({alphaT:tl,alphaB:u,dotNH:h,dotTH:T,dotBH:R})}else g=$0({alpha:u,dotNL:c,dotNV:d}),m=W0({alpha:u,dotNH:h});return p.mul(g).mul(m)}),H0=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Wt=null;const Ro=M(({roughness:i,dotNV:e})=>{Wt===null&&(Wt=new Sf(H0,16,16,Jt,it),Wt.name="DFG_LUT",Wt.minFilter=vt,Wt.magFilter=vt,Wt.wrapS=Kr,Wt.wrapT=Kr,Wt.generateMipmaps=!1,Wt.needsUpdate=!0);const t=W(i,e);return we(Wt,t).rg}),X0=M(({lightDirection:i,f0:e,f90:t,roughness:n,f:s,USE_IRIDESCENCE:r,USE_ANISOTROPY:o})=>{const a=pg({lightDirection:i,f0:e,f90:t,roughness:n,f:s,USE_IRIDESCENCE:r,USE_ANISOTROPY:o}),u=pe.dot(i).clamp(),l=pe.dot(Ae).clamp(),c=Ro({roughness:n,dotNV:l}),d=Ro({roughness:n,dotNV:u}),h=e.mul(c.x).add(t.mul(c.y)),f=e.mul(d.x).add(t.mul(d.y)),p=c.x.add(c.y),g=d.x.add(d.y),m=w(1).sub(p),y=w(1).sub(g),_=e.add(e.oneMinus().mul(.047619)),T=h.mul(f).mul(_).div(w(1).sub(m.mul(y).mul(_).mul(_)).add(ql)),S=m.mul(y),N=T.mul(S);return a.add(N)}),gg=M(i=>{const{dotNV:e,specularColor:t,specularF90:n,roughness:s}=i,r=Ro({dotNV:e,roughness:s});return t.mul(r.x).add(n.mul(r.y))}),_d=M(({f:i,f90:e,dotVH:t})=>{const n=t.oneMinus().saturate(),s=n.mul(n),r=n.mul(s,s).clamp(0,.9999);return i.sub(A(e).mul(r)).div(r.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),K0=M(({roughness:i,dotNH:e})=>{const t=i.pow2(),n=w(1).div(t),r=e.pow2().oneMinus().max(.0078125);return w(2).add(n).mul(r.pow(n.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),Y0=M(({dotNV:i,dotNL:e})=>w(1).div(w(4).mul(e.add(i).sub(e.mul(i))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Q0=M(({lightDirection:i})=>{const e=i.add(Ae).normalize(),t=pe.dot(i).clamp(),n=pe.dot(Ae).clamp(),s=pe.dot(e).clamp(),r=K0({roughness:is,dotNH:s}),o=Y0({dotNV:n,dotNL:t});return wt.mul(r).mul(o)}),xd=M(({N:i,V:e,roughness:t})=>{const r=.0078125,o=i.dot(e).saturate(),a=W(t,o.oneMinus().sqrt());return a.assign(a.mul(.984375).add(r)),a}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),Z0=M(({f:i})=>{const e=i.length();return Je(e.mul(e).add(i.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Ai=M(({v1:i,v2:e})=>{const t=i.dot(e),n=t.abs().toVar(),s=n.mul(.0145206).add(.4965155).mul(n).add(.8543985).toVar(),r=n.add(4.1616724).mul(n).add(3.417594).toVar(),o=s.div(r),a=t.greaterThan(0).select(o,Je(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return i.cross(e).mul(a)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),La=M(({N:i,V:e,P:t,mInv:n,p0:s,p1:r,p2:o,p3:a})=>{const u=r.sub(s).toVar(),l=a.sub(s).toVar(),c=u.cross(l),d=A().toVar();return Se(c.dot(t.sub(s)).greaterThanEqual(0),()=>{const h=e.sub(i.mul(e.dot(i))).normalize(),f=i.cross(h).negate(),p=n.mul(Ze(h,f,i).transpose()).toVar(),g=p.mul(s.sub(t)).normalize().toVar(),m=p.mul(r.sub(t)).normalize().toVar(),y=p.mul(o.sub(t)).normalize().toVar(),_=p.mul(a.sub(t)).normalize().toVar(),T=A(0).toVar();T.addAssign(Ai({v1:g,v2:m})),T.addAssign(Ai({v1:m,v2:y})),T.addAssign(Ai({v1:y,v2:_})),T.addAssign(Ai({v1:_,v2:g})),d.assign(A(Z0({f:T})))}),d}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Yo=1/6,mg=i=>ue(Yo,ue(i,ue(i,i.negate().add(3)).sub(3)).add(1)),al=i=>ue(Yo,ue(i,ue(i,ue(3,i).sub(6))).add(4)),yg=i=>ue(Yo,ue(i,ue(i,ue(-3,i).add(3)).add(3)).add(1)),ul=i=>ue(Yo,qo(i,3)),Td=i=>mg(i).add(al(i)),vd=i=>yg(i).add(ul(i)),Sd=i=>pt(-1,al(i).div(mg(i).add(al(i)))),Nd=i=>pt(1,ul(i).div(yg(i).add(ul(i)))),Rd=(i,e,t)=>{const n=i.uvNode,s=ue(n,e.zw).add(.5),r=gs(s),o=on(s),a=Td(o.x),u=vd(o.x),l=Sd(o.x),c=Nd(o.x),d=Sd(o.y),h=Nd(o.y),f=W(r.x.add(l),r.y.add(d)).sub(.5).mul(e.xy),p=W(r.x.add(c),r.y.add(d)).sub(.5).mul(e.xy),g=W(r.x.add(l),r.y.add(h)).sub(.5).mul(e.xy),m=W(r.x.add(c),r.y.add(h)).sub(.5).mul(e.xy),y=Td(o.y).mul(pt(a.mul(i.sample(f).level(t)),u.mul(i.sample(p).level(t)))),_=vd(o.y).mul(pt(a.mul(i.sample(g).level(t)),u.mul(i.sample(m).level(t))));return y.add(_)},J0=M(([i,e])=>{const t=W(i.size(Be(e))),n=W(i.size(Be(e.add(1)))),s=rn(1,t),r=rn(1,n),o=Rd(i,ie(s,t),gs(e)),a=Rd(i,ie(r,n),Hl(e));return on(e).mix(o,a)}),wd=M(([i,e,t,n,s])=>{const r=A(Np(e.negate(),sn(i),rn(1,n))),o=A(wn(s[0].xyz),wn(s[1].xyz),wn(s[2].xyz));return sn(r).mul(t.mul(o))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),eS=M(([i,e])=>i.mul(jn(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),tS=tg(),nS=c0(),Ed=M(([i,e,t],{material:n})=>{const r=(n.side===ot?tS:nS).sample(i),o=Rn(rl.x).mul(eS(e,t));return J0(r,o)}),Ad=M(([i,e,t])=>(Se(t.notEqual(0),()=>{const n=pp(e).negate().div(t);return fp(n.negate().mul(i))}),A(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),sS=M(([i,e,t,n,s,r,o,a,u,l,c,d,h,f,p])=>{let g,m;if(p){g=ie().toVar(),m=A().toVar();const N=c.sub(1).mul(p.mul(.025)),R=A(c.sub(N),c,c.add(N));Ct({start:0,end:3},({i:v})=>{const P=R.element(v),D=wd(i,e,d,P,a),L=o.add(D),j=l.mul(u.mul(ie(L,1))),ee=W(j.xy.div(j.w)).toVar();ee.addAssign(1),ee.divAssign(2),ee.assign(W(ee.x,ee.y.oneMinus()));const re=Ed(ee,t,P);g.element(v).assign(re.element(v)),g.a.addAssign(re.a),m.element(v).assign(n.element(v).mul(Ad(wn(D),h,f).element(v)))}),g.a.divAssign(3)}else{const N=wd(i,e,d,c,a),R=o.add(N),v=l.mul(u.mul(ie(R,1))),P=W(v.xy.div(v.w)).toVar();P.addAssign(1),P.divAssign(2),P.assign(W(P.x,P.y.oneMinus())),g=Ed(P,t,c),m=n.mul(Ad(wn(N),h,f))}const y=m.rgb.mul(g.rgb),_=i.dot(e).clamp(),T=A(gg({dotNV:_,specularColor:s,specularF90:r,roughness:t})),S=m.r.add(m.g,m.b).div(3);return ie(T.oneMinus().mul(y),g.a.oneMinus().mul(S).oneMinus())}),rS=Ze(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),iS=i=>{const e=i.sqrt();return A(1).add(e).div(A(1).sub(e))},Cd=(i,e)=>i.sub(e).div(i.add(e)).pow2(),oS=(i,e)=>{const t=i.mul(2*Math.PI*1e-9),n=A(54856e-17,44201e-17,52481e-17),s=A(1681e3,1795300,2208400),r=A(43278e5,93046e5,66121e5),o=w(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(t.mul(2239900).add(e.x).cos()).mul(t.pow2().mul(-45282e5).exp());let a=n.mul(r.mul(2*Math.PI).sqrt()).mul(s.mul(t).add(e).cos()).mul(t.pow2().negate().mul(r).exp());return a=A(a.x.add(o),a.y,a.z).div(10685e-11),rS.mul(a)},Md=M(({outsideIOR:i,eta2:e,cosTheta1:t,thinFilmThickness:n,baseF0:s})=>{const r=Te(i,e,En(0,.03,n)),a=i.div(r).pow2().mul(t.pow2().oneMinus()).oneMinus();Se(a.lessThan(0),()=>A(1));const u=a.sqrt(),l=Cd(r,i),c=ei({f0:l,f90:1,dotVH:t}),d=c.oneMinus(),h=r.lessThan(i).select(Math.PI,0),f=w(Math.PI).sub(h),p=iS(s.clamp(0,.9999)),g=Cd(p,r.toVec3()),m=ei({f0:g,f90:1,dotVH:u}),y=A(p.x.lessThan(r).select(Math.PI,0),p.y.lessThan(r).select(Math.PI,0),p.z.lessThan(r).select(Math.PI,0)),_=r.mul(n,u,2),T=A(f).add(y),S=c.mul(m).clamp(1e-5,.9999),N=S.sqrt(),R=d.pow2().mul(m).div(A(1).sub(S)),P=c.add(R).toVar(),D=R.sub(d).toVar();return Ct({start:1,end:2,condition:"<=",name:"m"},({m:L})=>{D.mulAssign(N);const j=oS(w(L).mul(_),w(L).mul(T)).mul(2);P.addAssign(D.mul(j))}),P.max(A(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),wr=M(({normal:i,viewDir:e,roughness:t})=>{const n=i.dot(e).saturate(),s=t.mul(t),r=t.add(.1).reciprocal(),o=w(-1.9362).add(t.mul(1.0678)).add(s.mul(.4573)).sub(r.mul(.8469)),a=w(-.6014).add(t.mul(.5538)).sub(s.mul(.467)).sub(r.mul(.1255));return o.mul(n).add(a).exp().saturate()}),Er=A(.04),Ci=w(1);class bg extends Ko{constructor(e=!1,t=!1,n=!1,s=!1,r=!1,o=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=s,this.transmission=r,this.dispersion=o,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=A().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=A().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=A().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=A().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=A().toVar("sheenSpecularIndirect")),this.iridescence===!0){const t=pe.dot(Ae).clamp(),n=Md({outsideIOR:w(1),eta2:Ju,cosTheta1:t,thinFilmThickness:el,baseF0:_s}),s=Md({outsideIOR:w(1),eta2:Ju,cosTheta1:t,thinFilmThickness:el,baseF0:xe.rgb});this.iridescenceFresnel=Te(n,s,Gn),this.iridescenceF0Dielectric=_d({f:n,f90:1,dotVH:t}),this.iridescenceF0Metallic=_d({f:s,f90:1,dotVH:t}),this.iridescenceF0=Te(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Gn)}if(this.transmission===!0){const t=rr,n=DT.sub(rr).normalize(),s=pr,r=e.context;r.backdrop=sS(s,n,bn,Is,$s,zs,t,vs,An,Wr,so,up,cp,lp,this.dispersion?dp:null),r.backdropAlpha=sl,xe.a.mulAssign(Te(1,r.backdrop.a,sl))}super.start(e)}computeMultiscattering(e,t,n,s,r=null){const o=pe.dot(Ae).clamp(),a=Ro({roughness:bn,dotNV:o}),u=r?zl.mix(s,r):s,l=u.mul(a.x).add(n.mul(a.y)),d=a.x.add(a.y).oneMinus(),h=u.add(u.oneMinus().mul(.047619)),f=l.mul(h).div(d.mul(h).oneMinus());e.addAssign(l),t.addAssign(f.mul(d))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=pe.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(r.mul(Q0({lightDirection:e})));const o=wr({normal:pe,viewDir:Ae,roughness:is}),a=wr({normal:pe,viewDir:e,roughness:is}),u=wt.r.max(wt.g).max(wt.b).mul(o.max(a)).oneMinus();r.mulAssign(u)}if(this.clearcoat===!0){const a=us.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(a.mul(pg({lightDirection:e,f0:Er,f90:Ci,roughness:Vr,normalView:us})))}n.directDiffuse.addAssign(r.mul(ir({diffuseColor:Is}))),n.directSpecular.addAssign(r.mul(X0({lightDirection:e,f0:$s,f90:1,roughness:bn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:s,reflectedLight:r,ltc_1:o,ltc_2:a}){const u=t.add(n).sub(s),l=t.sub(n).sub(s),c=t.sub(n).add(s),d=t.add(n).add(s),h=pe,f=Ae,p=$e.toVar(),g=xd({N:h,V:f,roughness:bn}),m=o.sample(g).toVar(),y=a.sample(g).toVar(),_=Ze(A(m.x,0,m.y),A(0,1,0),A(m.z,0,m.w)).toVar(),T=$s.mul(y.x).add(zs.sub($s).mul(y.y)).toVar();if(r.directSpecular.addAssign(e.mul(T).mul(La({N:h,V:f,P:p,mInv:_,p0:u,p1:l,p2:c,p3:d}))),r.directDiffuse.addAssign(e.mul(Is).mul(La({N:h,V:f,P:p,mInv:Ze(1,0,0,0,1,0,0,0,1),p0:u,p1:l,p2:c,p3:d}))),this.clearcoat===!0){const S=us,N=xd({N:S,V:f,roughness:Vr}),R=o.sample(N),v=a.sample(N),P=Ze(A(R.x,0,R.y),A(0,1,0),A(R.z,0,R.w)),D=Er.mul(v.x).add(Ci.sub(Er).mul(v.y));this.clearcoatSpecularDirect.addAssign(e.mul(D).mul(La({N:S,V:f,P:p,mInv:P,p0:u,p1:l,p2:c,p3:d})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context,s=t.mul(ir({diffuseColor:Is})).toVar();if(this.sheen===!0){const r=wr({normal:pe,viewDir:Ae,roughness:is}),o=wt.r.max(wt.g).max(wt.b).mul(r).oneMinus();s.mulAssign(o)}n.indirectDiffuse.addAssign(s)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:s}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(n.mul(wt,wr({normal:pe,viewDir:Ae,roughness:is}))),this.clearcoat===!0){const m=us.dot(Ae).clamp(),y=gg({dotNV:m,specularColor:Er,specularF90:Ci,roughness:Vr});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(y))}const r=A().toVar("singleScatteringDielectric"),o=A().toVar("multiScatteringDielectric"),a=A().toVar("singleScatteringMetallic"),u=A().toVar("multiScatteringMetallic");this.computeMultiscattering(r,o,zs,_s,this.iridescenceF0Dielectric),this.computeMultiscattering(a,u,zs,xe.rgb,this.iridescenceF0Metallic);const l=Te(r,a,Gn),c=Te(o,u,Gn),d=r.add(o),h=Is.mul(d.oneMinus()),f=n.mul(1/Math.PI),p=t.mul(l).add(c.mul(f)).toVar(),g=h.mul(f).toVar();if(this.sheen===!0){const m=wr({normal:pe,viewDir:Ae,roughness:is}),y=wt.r.max(wt.g).max(wt.b).mul(m).oneMinus();p.mulAssign(y),g.mulAssign(y)}s.indirectSpecular.addAssign(p),s.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,r=pe.dot(Ae).clamp().add(t),o=bn.mul(-16).oneMinus().negate().exp2(),a=t.sub(r.pow(o).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(a)}finish({context:e}){const{outgoingLight:t}=e;if(this.clearcoat===!0){const n=us.dot(Ae).clamp(),s=ei({dotVH:n,f0:Er,f90:Ci}),r=t.mul(Zu.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Zu));t.assign(r)}if(this.sheen===!0){const n=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(n)}}}const Bd=w(1),ll=w(-2),Mi=w(.8),Ua=w(-1),Bi=w(.4),Oa=w(2),Pi=w(.305),Ia=w(3),Pd=w(.21),aS=w(4),Fd=w(4),uS=w(16),lS=M(([i])=>{const e=A(bt(i)).toVar(),t=w(-1).toVar();return Se(e.x.greaterThan(e.z),()=>{Se(e.x.greaterThan(e.y),()=>{t.assign(Tt(i.x.greaterThan(0),0,3))}).Else(()=>{t.assign(Tt(i.y.greaterThan(0),1,4))})}).Else(()=>{Se(e.z.greaterThan(e.y),()=>{t.assign(Tt(i.z.greaterThan(0),2,5))}).Else(()=>{t.assign(Tt(i.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),cS=M(([i,e])=>{const t=W().toVar();return Se(e.equal(0),()=>{t.assign(W(i.z,i.y).div(bt(i.x)))}).ElseIf(e.equal(1),()=>{t.assign(W(i.x.negate(),i.z.negate()).div(bt(i.y)))}).ElseIf(e.equal(2),()=>{t.assign(W(i.x.negate(),i.y).div(bt(i.z)))}).ElseIf(e.equal(3),()=>{t.assign(W(i.z.negate(),i.y).div(bt(i.x)))}).ElseIf(e.equal(4),()=>{t.assign(W(i.x.negate(),i.z).div(bt(i.y)))}).Else(()=>{t.assign(W(i.x,i.y).div(bt(i.z)))}),ue(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),dS=M(([i])=>{const e=w(0).toVar();return Se(i.greaterThanEqual(Mi),()=>{e.assign(Bd.sub(i).mul(Ua.sub(ll)).div(Bd.sub(Mi)).add(ll))}).ElseIf(i.greaterThanEqual(Bi),()=>{e.assign(Mi.sub(i).mul(Oa.sub(Ua)).div(Mi.sub(Bi)).add(Ua))}).ElseIf(i.greaterThanEqual(Pi),()=>{e.assign(Bi.sub(i).mul(Ia.sub(Oa)).div(Bi.sub(Pi)).add(Oa))}).ElseIf(i.greaterThanEqual(Pd),()=>{e.assign(Pi.sub(i).mul(aS.sub(Ia)).div(Pi.sub(Pd)).add(Ia))}).Else(()=>{e.assign(w(-2).mul(Rn(ue(1.16,i))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),hS=M(([i,e])=>{const t=i.toVar();t.assign(ue(2,t).sub(1));const n=A(t,1).toVar();return Se(e.equal(0),()=>{n.assign(n.zyx)}).ElseIf(e.equal(1),()=>{n.assign(n.xzy),n.xz.mulAssign(-1)}).ElseIf(e.equal(2),()=>{n.x.mulAssign(-1)}).ElseIf(e.equal(3),()=>{n.assign(n.zyx),n.xz.mulAssign(-1)}).ElseIf(e.equal(4),()=>{n.assign(n.xzy),n.xy.mulAssign(-1)}).ElseIf(e.equal(5),()=>{n.z.mulAssign(-1)}),n}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),fS=M(([i,e,t,n,s,r])=>{const o=w(t),a=A(e),u=jn(dS(o),ll,r),l=on(u),c=gs(u),d=A(ti(i,a,c,n,s,r)).toVar();return Se(l.notEqual(0),()=>{const h=A(ti(i,a,c.add(1),n,s,r)).toVar();d.assign(Te(d,h,l))}),d}),ti=M(([i,e,t,n,s,r])=>{const o=w(t).toVar(),a=A(e),u=w(lS(a)).toVar(),l=w(Je(Fd.sub(o),0)).toVar();o.assign(Je(o,Fd));const c=w(Qr(o)).toVar(),d=W(cS(a,u).mul(c.sub(2)).add(1)).toVar();return Se(u.greaterThan(2),()=>{d.y.addAssign(c),u.subAssign(3)}),d.x.addAssign(u.mul(c)),d.x.addAssign(l.mul(ue(3,uS))),d.y.addAssign(ue(4,Qr(r).sub(c))),d.x.mulAssign(n),d.y.mulAssign(s),i.sample(d).grad(W(),W())}),ka=M(({envMap:i,mipInt:e,outputDirection:t,theta:n,axis:s,CUBEUV_TEXEL_WIDTH:r,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const u=Kt(n),l=t.mul(u).add(s.cross(t).mul(yt(n))).add(s.mul(s.dot(t).mul(u.oneMinus())));return ti(i,l,e,r,o,a)}),pS=M(({n:i,latitudinal:e,poleAxis:t,outputDirection:n,weights:s,samples:r,dTheta:o,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d})=>{const h=A(Tt(e,t,Ts(t,n))).toVar();Se(h.equal(A(0)),()=>{h.assign(A(n.z,0,n.x.negate()))}),h.assign(sn(h));const f=A().toVar();return f.addAssign(s.element(0).mul(ka({theta:0,axis:h,outputDirection:n,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d}))),Ct({start:Be(1),end:i},({i:p})=>{Se(p.greaterThanEqual(r),()=>{t0()});const g=w(o.mul(w(p))).toVar();f.addAssign(s.element(p).mul(ka({theta:g.mul(-1),axis:h,outputDirection:n,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d}))),f.addAssign(s.element(p).mul(ka({theta:g,axis:h,outputDirection:n,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d})))}),ie(f,1)}),gS=M(([i])=>{const e=de(i).toVar();return e.assign(e.shiftLeft(de(16)).bitOr(e.shiftRight(de(16)))),e.assign(e.bitAnd(de(1431655765)).shiftLeft(de(1)).bitOr(e.bitAnd(de(2863311530)).shiftRight(de(1)))),e.assign(e.bitAnd(de(858993459)).shiftLeft(de(2)).bitOr(e.bitAnd(de(3435973836)).shiftRight(de(2)))),e.assign(e.bitAnd(de(252645135)).shiftLeft(de(4)).bitOr(e.bitAnd(de(4042322160)).shiftRight(de(4)))),e.assign(e.bitAnd(de(16711935)).shiftLeft(de(8)).bitOr(e.bitAnd(de(4278255360)).shiftRight(de(8)))),w(e).mul(23283064365386963e-26)}),mS=M(([i,e])=>W(w(i).div(w(e)),gS(i))),yS=M(([i,e,t])=>{const n=t.mul(t).toConst(),s=A(1,0,0).toConst(),r=Ts(e,s).toConst(),o=Wn(i.x).toConst(),a=ue(2,3.14159265359).mul(i.y).toConst(),u=o.mul(Kt(a)).toConst(),l=o.mul(yt(a)).toVar(),c=ue(.5,e.z.add(1)).toConst();l.assign(c.oneMinus().mul(Wn(u.mul(u).oneMinus())).add(c.mul(l)));const d=s.mul(u).add(r.mul(l)).add(e.mul(Wn(Je(0,u.mul(u).add(l.mul(l)).oneMinus()))));return sn(A(n.mul(d.x),n.mul(d.y),Je(0,d.z)))}),bS=M(({roughness:i,mipInt:e,envMap:t,N_immutable:n,GGX_SAMPLES:s,CUBEUV_TEXEL_WIDTH:r,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const u=A(n).toVar(),l=A(0).toVar(),c=w(0).toVar();return Se(i.lessThan(.001),()=>{l.assign(ti(t,u,e,r,o,a))}).Else(()=>{const d=Tt(bt(u.z).lessThan(.999),A(0,0,1),A(1,0,0)),h=sn(Ts(d,u)).toVar(),f=Ts(u,h).toVar();Ct({start:de(0),end:s},({i:p})=>{const g=mS(p,s),m=yS(g,A(0,0,1),i),y=sn(h.mul(m.x).add(f.mul(m.y)).add(u.mul(m.z))),_=sn(y.mul(xs(u,y).mul(2)).sub(u)),T=Je(xs(u,_),0);Se(T.greaterThan(0),()=>{const S=ti(t,_,e,r,o,a);l.addAssign(S.mul(T)),c.addAssign(T)})}),Se(c.greaterThan(0),()=>{l.assign(l.div(c))})}),ie(l,1)}),Vn=4,Dd=[.125,.215,.35,.446,.526,.582],ls=20,_S=512,Ar=new El(-1,1,1,-1,0,1),xS=new Hr(90,1),Ld=new Dt;let Ga=null,Va=0,$a=0;const TS=new V,wo=new WeakMap,vS=[3,1,5,0,4,2],za=hS(dr(),qn("faceIndex")).normalize(),Qo=A(za.x,za.y,za.z);class SS{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,s=100,r={}){const{size:o=256,position:a=TS,renderTarget:u=null}=r;if(this._setSize(o),this._hasInitialized===!1){z('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const c=u||this._allocateTarget();return r.renderTarget=c,this.fromSceneAsync(e,t,n,s,r),c}Ga=this._renderer.getRenderTarget(),Va=this._renderer.getActiveCubeFace(),$a=this._renderer.getActiveMipmapLevel();const l=u||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,n,s,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,s=100,r={}){return Oe('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,s,r)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1){z('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromEquirectangularAsync(e,n),n}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Oe('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1){z("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromCubemapAsync(e,t),n}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Oe('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Od(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Id(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===yo||e.mapping===bo?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Ga,Va,$a),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Ga=this._renderer.getRenderTarget(),Va=this._renderer.getActiveCubeFace(),$a=this._renderer.getActiveMipmapLevel();const n=t||this._allocateTarget();return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize;return Ud(e,t)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Ud(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=NS(t)),this._blurMaterial=RS(t,e.width,e.height),this._ggxMaterial=wS(t,e.width,e.height)}}async _compileMaterial(e){const t=new kt(new si,e);await this._renderer.compile(t,Ar)}_sceneToCubeUV(e,t,n,s,r){const o=xS;o.near=t,o.far=n;const a=[1,1,1,1,-1,1],u=[1,-1,1,-1,1,-1],l=this._renderer,c=l.autoClear;l.getClearColor(Ld),l.autoClear=!1,this._backgroundBox===null&&(this._backgroundBox=new kt(new Af,new On({name:"PMREM.Background",side:ot,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,h=d.material;let f=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,f=!0):(h.color.copy(Ld),f=!0),l.setRenderTarget(s),l.clear(),f&&l.render(d,o);for(let g=0;g<6;g++){const m=g%3;m===0?(o.up.set(0,a[g],0),o.position.set(r.x,r.y,r.z),o.lookAt(r.x+u[g],r.y,r.z)):m===1?(o.up.set(0,0,a[g]),o.position.set(r.x,r.y,r.z),o.lookAt(r.x,r.y+u[g],r.z)):(o.up.set(0,a[g],0),o.position.set(r.x,r.y,r.z),o.lookAt(r.x,r.y,r.z+u[g]));const y=this._cubeSize;this._setViewport(s,m*y,g>2?y:0,y,y),l.render(e,o)}l.autoClear=c,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===yo||e.mapping===bo;s?this._cubemapMaterial===null&&(this._cubemapMaterial=Od(e)):this._equirectMaterial===null&&(this._equirectMaterial=Id(e));const r=s?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const o=this._lodMeshes[0];o.material=r;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(o,Ar)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const s=this._renderer,r=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const u=wo.get(o),l=n/(this._lodMeshes.length-1),c=t/(this._lodMeshes.length-1),d=Math.sqrt(l*l-c*c),h=0+l*1.25,f=d*h,{_lodMax:p}=this,g=this._sizeLods[n],m=3*g*(n>p-Vn?n-p+Vn:0),y=4*(this._cubeSize-g);e.texture.frame=(e.texture.frame||0)+1,u.envMap.value=e.texture,u.roughness.value=f,u.mipInt.value=p-t,this._setViewport(r,m,y,3*g,2*g),s.setRenderTarget(r),s.render(a,Ar),r.texture.frame=(r.texture.frame||0)+1,u.envMap.value=r.texture,u.roughness.value=0,u.mipInt.value=p-n,this._setViewport(e,m,y,3*g,2*g),s.setRenderTarget(e),s.render(a,Ar)}_blur(e,t,n,s,r){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,s,"latitudinal",r),this._halfBlur(o,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,o,a){const u=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&k("blur direction must be either latitudinal or longitudinal!");const c=3,d=this._lodMeshes[s];d.material=l;const h=wo.get(l),f=this._sizeLods[n]-1,p=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*ls-1),g=r/p,m=isFinite(r)?1+Math.floor(c*g):ls;m>ls&&z(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${ls}`);const y=[];let _=0;for(let v=0;v<ls;++v){const P=v/g,D=Math.exp(-P*P/2);y.push(D),v===0?_+=D:v<m&&(_+=2*D)}for(let v=0;v<y.length;v++)y[v]=y[v]/_;e.texture.frame=(e.texture.frame||0)+1,h.envMap.value=e.texture,h.samples.value=m,h.weights.array=y,h.latitudinal.value=o==="latitudinal"?1:0,a&&(h.poleAxis.value=a);const{_lodMax:T}=this;h.dTheta.value=p,h.mipInt.value=T-n;const S=this._sizeLods[s],N=3*S*(s>T-Vn?s-T+Vn:0),R=4*(this._cubeSize-S);this._setViewport(t,N,R,3*S,2*S),u.setRenderTarget(t),u.render(d,Ar)}_setViewport(e,t,n,s,r){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-r-n,s,r),e.scissor.set(t,e.height-r-n,s,r)):(e.viewport.set(t,n,s,r),e.scissor.set(t,n,s,r))}}function NS(i){const e=[],t=[],n=[];let s=i;const r=i-Vn+1+Dd.length;for(let o=0;o<r;o++){const a=Math.pow(2,s);e.push(a);let u=1/a;o>i-Vn?u=Dd[o-i+Vn-1]:o===0&&(u=0),t.push(u);const l=1/(a-2),c=-l,d=1+l,h=[c,c,d,c,d,d,c,c,d,d,c,d],f=6,p=6,g=3,m=2,y=1,_=new Float32Array(g*p*f),T=new Float32Array(m*p*f),S=new Float32Array(y*p*f);for(let R=0;R<f;R++){const v=R%3*2/3-1,P=R>2?0:-1,D=[v,P,0,v+2/3,P,0,v+2/3,P+1,0,v,P,0,v+2/3,P+1,0,v,P+1,0],L=vS[R];_.set(D,g*p*L),T.set(h,m*p*L);const j=[L,L,L,L,L,L];S.set(j,y*p*L)}const N=new si;N.setAttribute("position",new Yi(_,g)),N.setAttribute("uv",new Yi(T,m)),N.setAttribute("faceIndex",new Yi(S,y)),n.push(new kt(N,null)),s>Vn&&s--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function Ud(i,e){const t={magFilter:vt,minFilter:vt,generateMipmaps:!1,type:it,format:It,colorSpace:wy},n=new Ss(i,e,t);return n.texture.mapping=yu,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function Zo(i){const e=new We;return e.depthTest=!1,e.depthWrite=!1,e.blending=Nn,e.name=`PMREM_${i}`,e}function RS(i,e,t){const n=At(new Array(ls).fill(0)),s=Y(new V(0,1,0)),r=Y(0),o=w(ls),a=Y(0),u=Y(1),l=we(),c=Y(0),d=w(1/e),h=w(1/t),f=w(i),p={n:o,latitudinal:a,weights:n,poleAxis:s,outputDirection:Qo,dTheta:r,samples:u,envMap:l,mipInt:c,CUBEUV_TEXEL_WIDTH:d,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:f},g=Zo("blur");return g.fragmentNode=pS({...p,latitudinal:a.equal(1)}),wo.set(g,p),g}function wS(i,e,t){const n=we(),s=Y(0),r=Y(0),o=w(1/e),a=w(1/t),u=w(i),l={envMap:n,roughness:s,mipInt:r,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:u},c=Zo("ggx");return c.fragmentNode=bS({...l,N_immutable:Qo,GGX_SAMPLES:de(_S)}),wo.set(c,l),c}function Od(i){const e=Zo("cubemap");return e.fragmentNode=dt(i,Qo),e}function Id(i){const e=Zo("equirect");return e.fragmentNode=we(i,ag(Qo),0),e}const kd=new WeakMap;function ES(i){const e=Math.log2(i)-2,t=1/i;return{texelWidth:1/(3*Math.max(Math.pow(2,e),112)),texelHeight:t,maxMip:e}}function AS(i,e,t){const n=CS(e);let s=n.get(i);if((s!==void 0?s.pmremVersion:-1)!==i.pmremVersion){const o=i.image;if(i.isCubeTexture)if(BS(o))s=t.fromCubemap(i,s);else return null;else if(PS(o))s=t.fromEquirectangular(i,s);else return null;s.pmremVersion=i.pmremVersion,n.set(i,s)}return s.texture}function CS(i){let e=kd.get(i);return e===void 0&&(e=new WeakMap,kd.set(i,e)),e}class MS extends je{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const s=new Ml;s.isRenderTargetTexture=!0,this._texture=we(s),this._width=Y(0),this._height=Y(0),this._maxMip=Y(0),this.updateBeforeType=te.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=ES(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const n=t?t.pmremVersion:-1,s=this._value;n!==s.pmremVersion&&(s.isPMREMTexture===!0?t=s:t=AS(s,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new SS(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this,e)),t=$p.mul(A(t.x,t.y.negate(),t.z));let n=this.levelNode;return n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),fS(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function BS(i){if(i==null)return!1;let e=0;const t=6;for(let n=0;n<t;n++)i[n]!==void 0&&e++;return e===t}function PS(i){return i==null?!1:i.height>0}const _g=Ne(MS).setParameterLength(1,3),Gd=new WeakMap;class FS extends gr{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const d=n.isTextureNode?n.value:t[n.property],h=this._getPMREMNodeCache(e.renderer);let f=h.get(d);f===void 0&&(f=_g(d),h.set(d,f)),n=f}const r=t.useAnisotropy===!0||t.anisotropy>0?iv:pe,o=n.context(Vd(bn,r)).mul(Ba),a=n.context(DS(pr)).mul(Math.PI).mul(Ba),u=zr(o),l=zr(a);e.context.radiance.addAssign(u),e.context.iblIrradiance.addAssign(l);const c=e.context.lightingModel.clearcoatRadiance;if(c){const d=n.context(Vd(Vr,us)).mul(Ba),h=zr(d);c.addAssign(h)}}_getPMREMNodeCache(e){let t=Gd.get(e);return t===void 0&&(t=new WeakMap,Gd.set(e,t)),t}}const Vd=(i,e)=>{let t=null;return{getUV:()=>(t===null&&(t=Ae.negate().reflect(e),t=vp(i).mix(t,e).normalize(),t=t.transformDirection(An)),t),getTextureLevel:()=>i}},DS=i=>({getUV:()=>i,getTextureLevel:()=>w(1)}),LS=new Um;class xg extends We{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(LS),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new FS(t):null}setupLightingModel(){return new bg}setupSpecular(){const e=Te(A(.04),xe.rgb,Gn);_s.assign(A(.04)),$s.assign(e),zs.assign(1)}setupVariants(){const e=this.metalnessNode?w(this.metalnessNode):_v;Gn.assign(e);let t=this.roughnessNode?w(this.roughnessNode):bv;t=fg({roughness:t}),bn.assign(t),this.setupSpecular(),Is.assign(xe.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const US=new Om;class OS extends xg{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(US),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}setupSpecular(){const e=this.iorNode?w(this.iorNode):Fv;so.assign(e),_s.assign(sr(Tp(so.sub(1).div(so.add(1))).mul(yv),A(1)).mul(hd)),$s.assign(Te(_s,xe.rgb,Gn)),zs.assign(Te(hd,1,Gn))}setupLightingModel(){return new bg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?w(this.clearcoatNode):Tv,n=this.clearcoatRoughnessNode?w(this.clearcoatRoughnessNode):vv;Zu.assign(t),Vr.assign(fg({roughness:n}))}if(this.useSheen){const t=this.sheenNode?A(this.sheenNode):Rv,n=this.sheenRoughnessNode?w(this.sheenRoughnessNode):wv;wt.assign(t),is.assign(n)}if(this.useIridescence){const t=this.iridescenceNode?w(this.iridescenceNode):Av,n=this.iridescenceIORNode?w(this.iridescenceIORNode):Cv,s=this.iridescenceThicknessNode?w(this.iridescenceThicknessNode):Mv;zl.assign(t),Ju.assign(n),el.assign(s)}if(this.useAnisotropy){const t=(this.anisotropyNode?W(this.anisotropyNode):Ev).toVar();ss.assign(t.length()),Se(ss.equal(0),()=>{t.assign(W(1,0))}).Else(()=>{t.divAssign(W(ss)),ss.assign(ss.saturate())}),tl.assign(ss.pow2().mix(bn.pow2(),1)),no.assign(Lr[0].mul(t.x).add(Lr[1].mul(t.y))),Ks.assign(Lr[1].mul(t.x).sub(Lr[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?w(this.transmissionNode):Bv,n=this.thicknessNode?w(this.thicknessNode):Pv,s=this.attenuationDistanceNode?w(this.attenuationDistanceNode):Dv,r=this.attenuationColorNode?A(this.attenuationColorNode):Lv;if(sl.assign(t),up.assign(n),lp.assign(s),cp.assign(r),this.useDispersion){const o=this.dispersionNode?w(this.dispersionNode):Vv;dp.assign(o)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?A(this.clearcoatNormalNode):Sv}setup(e){e.context.setupClearcoatNormal=()=>Ys(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const IS=M(({normal:i,lightDirection:e,builder:t})=>{const n=i.dot(e),s=W(n.mul(.5).add(.5),0);if(t.material.gradientMap){const r=In("gradientMap","texture").context({getUV:()=>s});return A(r.r)}else{const r=s.fwidth().mul(.5);return Te(A(.7),A(1),En(w(.7).sub(r.x),w(.7).add(r.x),s.x))}});class kS extends Ko{direct({lightDirection:e,lightColor:t,reflectedLight:n},s){const r=IS({normal:Gp,lightDirection:e,builder:s}).mul(t);n.directDiffuse.addAssign(r.mul(ir({diffuseColor:xe.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(n.mul(ir({diffuseColor:xe}))),s.indirectDiffuse.mulAssign(t)}}const GS=new Im;class VS extends We{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(GS),this.setValues(e)}setupLightingModel(){return new kS}}const $S=M(()=>{const i=A(Ae.z,0,Ae.x.negate()).normalize(),e=Ae.cross(i);return W(i.dot(pe),e.dot(pe)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),zS=new Gm;class WS extends We{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(zS),this.setValues(e)}setupVariants(e){const t=$S;let n;e.material.matcap?n=In("matcap","texture").context({getUV:()=>t}):n=A(Te(.2,.8,t.y)),xe.rgb.mulAssign(n.rgb)}}class jS extends je{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if(this.getNodeType(e)==="vec2"){const r=t.cos(),o=t.sin();return $l(r,o,o.negate(),r).mul(n)}else{const r=t,o=ps(ie(1,0,0,0),ie(0,Kt(r.x),yt(r.x).negate(),0),ie(0,yt(r.x),Kt(r.x),0),ie(0,0,0,1)),a=ps(ie(Kt(r.y),0,yt(r.y),0),ie(0,1,0,0),ie(yt(r.y).negate(),0,Kt(r.y),0),ie(0,0,0,1)),u=ps(ie(Kt(r.z),yt(r.z).negate(),0,0),ie(yt(r.z),Kt(r.z),0,0),ie(0,0,1,0),ie(0,0,0,1));return o.mul(a).mul(u).mul(ie(n,1)).xyz}}}const Tg=Ne(jS).setParameterLength(2),qS=new zm;class vg extends We{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(qS),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:s,rotationNode:r,scaleNode:o,sizeAttenuation:a}=this,u=li.mul(A(s||0));let l=W(vs[0].xyz.length(),vs[1].xyz.length());o!==null&&(l=l.mul(W(o))),n.isPerspectiveCamera&&a===!1&&(l=l.mul(u.z.negate()));let c=Xo.xy;if(t.center&&t.center.isVector2===!0){const f=nT("center","vec2",t);c=c.sub(f.sub(.5))}c=c.mul(l);const d=w(r||Nv),h=Tg(c,d);return ie(u.xy.add(h),u.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const HS=new $m,XS=new ce;class KS extends vg{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(HS),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return li.mul(A(e||Xe)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:s,scaleNode:r,sizeNode:o,sizeAttenuation:a}=this;let u=super.setupVertex(e);if(t.isNodeMaterial!==!0)return u;let l=o!==null?W(o):Gv;l=l.mul(BT),n.isPerspectiveCamera&&a===!0&&(l=l.mul(YS.div($e.z.negate()))),r&&r.isNode&&(l=l.mul(W(r)));let c=Xo.xy;if(s&&s.isNode){const d=w(s);c=Tg(c,d)}return c=c.mul(l),c=c.div(PT.div(2)),c=c.mul(u.w),u=u.add(ie(c,0,0)),u}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const YS=Y(1).onFrameUpdate(function({renderer:i}){const e=i.getSize(XS);this.value=.5*e.y});class QS extends Ko{constructor(){super(),this.shadowNode=w(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){xe.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(xe.rgb)}}const ZS=new Wm;class JS extends We{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(ZS),this.setValues(e)}setupLightingModel(){return new QS}}zn("vec3");zn("vec3");zn("vec3");class eN{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context=typeof self<"u"?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),this._animationLoop!==null&&this._animationLoop(t,n),this.renderer._inspector.finish()};e()}stop(){this._context!==null&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class Hn{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let n=this.weakMaps[t];return n===void 0&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return;return t.get(e[e.length-1])}set(e,t){let n=this._getWeakMap(e);for(let s=0;s<e.length-1;s++){const r=e[s];n.has(r)===!1&&n.set(r,new WeakMap),n=n.get(r)}return n.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return!1;return t.delete(e[e.length-1])}}let tN=0;function nN(i){const e=Object.keys(i);let t=Object.getPrototypeOf(i);for(;t;){const n=Object.getOwnPropertyDescriptors(t);for(const s in n)if(n[s]!==void 0){const r=n[s];r&&typeof r.get=="function"&&e.push(s)}t=Object.getPrototypeOf(t)}return e}class sN{constructor(e,t,n,s,r,o,a,u,l,c){this.id=tN++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=s,this.material=r,this.scene=o,this.camera=a,this.lightsNode=u,this.context=l,this.geometry=s.geometry,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=c,this.clippingContextCacheKey=c!==null?c.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.material.hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(this.attributes!==null)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],s=new Set,r={};for(const o of e){let a;if(o.node&&o.node.attribute?a=o.node.attribute:(a=t.getAttribute(o.name),r[o.name]=a.id),a===void 0)continue;n.push(a);const u=a.isInterleavedBufferAttribute?a.data:a;s.add(u)}return this.attributes=n,this.attributesId=r,this.vertexBuffers=Array.from(s.values()),n}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:s,drawRange:r}=this,o=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),u=a!==null;let l=1;if(n.isInstancedBufferGeometry===!0?l=n.instanceCount:e.count!==void 0&&(l=Math.max(0,e.count)),l===0)return null;if(o.instanceCount=l,e.isBatchedMesh===!0)return o;let c=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(c=2);let d=r.start*c,h=(r.start+r.count)*c;s!==null&&(d=Math.max(d,s.start*c),h=Math.min(h,(s.start+s.count)*c));const f=n.attributes.position;let p=1/0;u?p=a.count:f!=null&&(p=f.count),d=Math.max(d,0),h=Math.min(h,p);const g=h-d;return g<0||g===1/0?null:(o.vertexCount=g,o.firstVertex=d,o)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const s=e.attributes[n];t+=n+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[n];t+="morph-"+n+",";for(let r=0,o=s.length;r<o;r++){const a=s[r];t+=a.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:n}=this;let s=t.customProgramCacheKey();for(const r of nN(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(r))continue;const o=t[r];let a;if(o!==null){const u=typeof o;u==="number"?a=o!==0?"1":"0":u==="object"?(a="{",o.isTexture&&(a+=o.mapping,n.backend.isWebGPUBackend===!0&&(a+=o.magFilter,a+=o.minFilter,a+=o.wrapS,a+=o.wrapT,a+=o.wrapR)),a+="}"):a=String(o)}else a=String(o);s+=a+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(s+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(s+=e.uuid+","),s+=this.context.id+",",s+=e.receiveShadow+",",ur(s)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(this.attributes!==null){const e=this.attributesId;for(const t in e){const n=this.geometry.getAttribute(t);if(n===void 0||e[t]!==n.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=kr(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=kr(e,1)),e=kr(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const jt=[];class rN{constructor(e,t,n,s,r,o){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=s,this.bindings=r,this.info=o,this.chainMaps={}}get(e,t,n,s,r,o,a,u){const l=this.getChainMap(u);jt[0]=e,jt[1]=t,jt[2]=o,jt[3]=r;let c=l.get(jt);return c===void 0?(c=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,s,r,o,a,u),l.set(jt,c)):(c.camera=s,c.updateClipping(a),c.needsGeometryUpdate&&c.setGeometry(e.geometry),(c.version!==t.version||c.needsUpdate)&&(c.initialCacheKey!==c.getCacheKey()?(c.dispose(),c=this.get(e,t,n,s,r,o,a,u)):c.version=t.version)),jt[0]=null,jt[1]=null,jt[2]=null,jt[3]=null,c}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Hn)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,s,r,o,a,u,l,c,d){const h=this.getChainMap(d),f=new sN(e,t,n,s,r,o,a,u,l,c);return f.onDispose=()=>{this.pipelines.delete(f),this.bindings.deleteForRender(f),this.nodes.delete(f),h.delete(f.getChainArray())},f}}class Xn{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const Bt={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},kn=16,iN=211,oN=212;class aN extends Xn{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return t!==null&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const n=this.get(e);if(n.version===void 0)t===Bt.VERTEX?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Bt.INDEX?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===Bt.STORAGE?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===Bt.INDIRECT&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),n.version=this._getBufferAttribute(e).version;else{const s=this._getBufferAttribute(e);(n.version<s.version||s.usage===lo)&&(this.backend.updateAttribute(e),n.version=s.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function Sg(i){return i.index!==null?i.index.version:i.attributes.position.version}function Ng(i){return i.index!==null?i.index.id:i.attributes.position.id}function $d(i){const e=[],t=i.index,n=i.attributes.position;if(t!==null){const r=t.array;for(let o=0,a=r.length;o<a;o+=3){const u=r[o+0],l=r[o+1],c=r[o+2];e.push(u,l,l,c,c,u)}}else{const r=n.array;for(let o=0,a=r.length/3-1;o<a;o+=3){const u=o+0,l=o+1,c=o+2;e.push(u,l,l,c,c,u)}}const s=new(n.count>=65535?Hm:Xm)(e,1);return s.version=Sg(i),s.__id=Ng(i),s}class uN extends Xn{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&this.get(t).initialized===!0}updateForRender(e){this.has(e)===!1&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry,n=this.get(t);n.initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const r=t.index,o=e.getAttributes();r!==null&&this.attributes.delete(r);for(const u of o)this.attributes.delete(u);const a=this.wireframes.get(t);a!==void 0&&this.attributes.delete(a),t.removeEventListener("dispose",s),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",s),this._geometryDisposeListeners.set(t,s)}updateAttributes(e){const t=e.getAttributes();for(const r of t)r.isStorageBufferAttribute||r.isStorageInstancedBufferAttribute?this.updateAttribute(r,Bt.STORAGE):this.updateAttribute(r,Bt.VERTEX);const n=this.getIndex(e);n!==null&&this.updateAttribute(n,Bt.INDEX);const s=e.geometry.indirect;s!==null&&this.updateAttribute(s,Bt.INDIRECT)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:n}=e;let s=t.index;if(n.wireframe===!0){const r=this.wireframes;let o=r.get(t);o===void 0?(o=$d(t),r.set(t,o)):(o.version!==Sg(t)||o.__id!==Ng(t))&&(this.attributes.delete(o),o=$d(t),r.set(t,o)),s=o}return s}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class lN{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):k("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const n=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:n,type:t}),this.memory[t]++,this.memory.total+=n,this.memory[t+"Size"]+=n}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===Ws||e.type===ht?t=1:e.type===js||e.type===ds||e.type===it?t=2:(e.type===st||e.type===Ve||e.type===rt)&&(t=4);let n=4;e.format===jh||e.format===Fo||e.format===Do||e.format===Tn||e.format===vn?n=1:e.format===Jt||e.format===Lo?n=2:(e.format===Uo||e.format===qh)&&(n=3);let s=t*n;e.type===Hh||e.type===Xh?s=2:(e.type===Sn||e.type===Sl||e.type===Nl)&&(s=4);const r=e.width||1,o=e.height||1,a=e.isCubeTexture?6:e.depth||1;let u=r*o*a*s;const l=e.mipmaps;if(l&&l.length>0){let c=0;for(let d=0;d<l.length;d++){const h=l[d];if(h.data)c+=h.data.byteLength;else{const f=h.width||Math.max(1,r>>d),p=h.height||Math.max(1,o>>d);c+=f*p*a*s}}u+=c}else e.generateMipmaps&&(u=u*1.333);return Math.round(u)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class Rg{constructor(e){this.cacheKey=e,this.usedTimes=0}}class cN extends Rg{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class dN extends Rg{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let hN=0;class Wa{constructor(e,t,n,s=null,r=null){this.id=hN++,this.code=e,this.stage=t,this.name=n,this.transforms=s,this.attributes=r,this.usedTimes=0}}class fN extends Xn{constructor(e,t,n){super(),this.backend=e,this.nodes=t,this.info=n,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:n}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const r=s.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const o=this.nodes.getForCompute(e);let a=this.programs.compute.get(o.computeShader);a===void 0&&(r&&r.computeProgram.usedTimes===0&&this._releaseProgram(r.computeProgram),a=new Wa(o.computeShader,"compute",e.name,o.transforms,o.nodeAttributes),this.programs.compute.set(o.computeShader,a),n.createProgram(a),this.info.createProgram(a));const u=this._getComputeCacheKey(e,a);let l=this.caches.get(u);l===void 0&&(r&&r.usedTimes===0&&this._releasePipeline(r),l=this._getComputePipeline(e,a,u,t)),l.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=l}return s.pipeline}getForRender(e,t=null){const{backend:n}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const r=s.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const o=e.getNodeBuilderState(),a=e.material?e.material.name:"";let u=this.programs.vertex.get(o.vertexShader);u===void 0&&(r&&r.vertexProgram.usedTimes===0&&this._releaseProgram(r.vertexProgram),u=new Wa(o.vertexShader,"vertex",a),this.programs.vertex.set(o.vertexShader,u),n.createProgram(u),this.info.createProgram(u));let l=this.programs.fragment.get(o.fragmentShader);l===void 0&&(r&&r.fragmentProgram.usedTimes===0&&this._releaseProgram(r.fragmentProgram),l=new Wa(o.fragmentShader,"fragment",a),this.programs.fragment.set(o.fragmentShader,l),n.createProgram(l),this.info.createProgram(l));const c=this._getRenderCacheKey(e,u,l);let d=this.caches.get(c);d===void 0?(r&&r.usedTimes===0&&this._releasePipeline(r),d=this._getRenderPipeline(e,u,l,c,t)):e.pipeline=d,d.usedTimes++,u.usedTimes++,l.usedTimes++,s.pipeline=d}return s.pipeline}isReady(e){const n=this.get(e).pipeline;if(n===void 0)return!1;const s=this.backend.get(n);return s.pipeline!==void 0&&s.pipeline!==null}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,s){n=n||this._getComputeCacheKey(e,t);let r=this.caches.get(n);return r===void 0&&(r=new dN(n,t),this.caches.set(n,r),this.backend.createComputePipeline(r,s)),r}_getRenderPipeline(e,t,n,s,r){s=s||this._getRenderCacheKey(e,t,n);let o=this.caches.get(s);return o===void 0&&(o=new cN(s,t,n),this.caches.set(s,o),e.pipeline=o,this.backend.createRenderPipeline(e,r)),o}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){const t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}}class pN extends Xn{constructor(e,t,n,s,r,o){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=s,this.nodes=t,this.info=o,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const n of t){const s=this.get(n);s.bindGroup===void 0&&(this._init(n),this.backend.createBindings(n,t,0),s.bindGroup=n)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const n of t){const s=this.get(n);s.bindGroup===void 0&&(this._init(n),this.backend.createBindings(n,t,0),s.bindGroup=n)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const n of t)this.backend.deleteBindGroupData(n),this.delete(n)}deleteForRender(e){const t=e.getBindings();for(const n of t)this.backend.deleteBindGroupData(n),this.delete(n)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const n=t.attribute,s=n.isIndirectStorageBufferAttribute?Bt.INDIRECT:Bt.STORAGE;this.attributes.update(n,s)}}_update(e,t){const{backend:n}=this;let s=!1,r=!0,o=0,a=0;for(const u of e.bindings)if(this.nodes.updateGroup(u)!==!1){if(u.isStorageBuffer){const c=u.attribute,d=c.isIndirectStorageBufferAttribute?Bt.INDIRECT:Bt.STORAGE,h=n.get(u);this.attributes.update(c,d),h.attribute!==c&&(h.attribute=c,s=!0)}if(u.isUniformBuffer)u.update()&&n.updateBinding(u);else if(u.isSampledTexture){const c=u.update(),d=u.texture,h=this.textures.get(d);if(c&&(this.textures.updateTexture(d),u.generation!==h.generation&&(u.generation=h.generation,s=!0),h.bindGroups.add(e)),n.get(d).externalTexture!==void 0||h.isDefaultTexture?r=!1:(o=o*10+d.id,a+=d.version),d.isStorageTexture===!0&&d.mipmapsAutoUpdate===!0){const p=this.get(d);u.store===!0?p.needsMipmap=!0:this.textures.needsMipmaps(d)&&p.needsMipmap===!0&&(this.backend.generateMipmaps(d),p.needsMipmap=!1)}}else if(u.isSampler&&u.update()){const d=this.textures.updateSampler(u.texture);u.samplerKey!==d&&(u.samplerKey=d,s=!0)}u.isBuffer&&u.updateRanges.length>0&&u.clearUpdateRanges()}s===!0&&this.backend.updateBindings(e,t,r?o:0,a)}}function gN(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?i.z-e.z:i.id-e.id}function zd(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Wd(i){return(i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode)&&i.side===xn&&i.forceSinglePass===!1}class mN{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,n),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,s,r,o,a){let u=this.renderItems[this.renderItemsIndex];return u===void 0?(u={id:e.id,object:e,geometry:t,material:n,groupOrder:s,renderOrder:e.renderOrder,z:r,group:o,clippingContext:a},this.renderItems[this.renderItemsIndex]=u):(u.id=e.id,u.object=e,u.geometry=t,u.material=n,u.groupOrder=s,u.renderOrder=e.renderOrder,u.z=r,u.group=o,u.clippingContext=a),this.renderItemsIndex++,u}push(e,t,n,s,r,o,a){const u=this.getNextRenderItem(e,t,n,s,r,o,a);e.occlusionTest===!0&&this.occlusionQueryCount++,n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Wd(n)&&this.transparentDoublePass.push(u),this.transparent.push(u)):this.opaque.push(u)}unshift(e,t,n,s,r,o,a){const u=this.getNextRenderItem(e,t,n,s,r,o,a);n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Wd(n)&&this.transparentDoublePass.unshift(u),this.transparent.unshift(u)):this.opaque.unshift(u)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||gN),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||zd),this.transparent.length>1&&this.transparent.sort(t||zd)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const n=this.renderItems[e];if(n.id===null)break;n.id=null,n.object=null,n.geometry=null,n.material=null,n.groupOrder=null,n.renderOrder=null,n.z=null,n.group=null,n.clippingContext=null}}}const Fs=[];class yN{constructor(e){this.lighting=e,this.lists=new Hn}get(e,t){const n=this.lists;Fs[0]=e,Fs[1]=t;let s=n.get(Fs);return s===void 0&&(s=new mN(this.lighting,e,t),n.set(Fs,s)),Fs[0]=null,Fs[1]=null,s}dispose(){this.lists=new Hn}}let bN=0;class _N{constructor(){this.id=bN++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new ze,this.scissor=!1,this.scissorValue=new ze,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return wg(this)}}function wg(i){const{textures:e,activeCubeFace:t,activeMipmapLevel:n}=i,s=[t,n];for(const r of e)s.push(r.id);return oi(s)}class xN{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let s;if(e===null)s="default";else{const u=e.texture.format,l=e.texture.type;s=`${e.textures.length}:${u}:${l}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const r=t!==null?t.id:"default",o=s+"-"+r+"-"+n;let a=this._renderContexts[o];return a===void 0&&(a=new _N,a.mrt=t,this._renderContexts[o]=a),e!==null&&(a.sampleCount=e.samples===0?1:e.samples),a.clearDepthValue=this.renderer.getClearDepth(),a.clearStencilValue=this.renderer.getClearStencil(),a}dispose(){this._renderContexts={}}}const TN=new V;class vN extends Xn{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const n=this.get(e),s=e.samples===0?1:e.samples,r=n.depthTextureMips||(n.depthTextureMips={}),o=e.textures,a=this.getSize(o[0]),u=a.width>>t,l=a.height>>t;let c=e.depthTexture||r[t];const d=e.depthBuffer===!0||e.stencilBuffer===!0;let h=!1;c===void 0&&d&&(c=new nn,c.format=e.stencilBuffer?vn:Tn,c.type=e.stencilBuffer?Sn:Ve,c.image.width=u,c.image.height=l,c.image.depth=a.depth,c.renderTarget=e,c.isArrayTexture=e.multiview===!0&&a.depth>1,r[t]=c),(n.width!==a.width||a.height!==n.height)&&(h=!0,c&&(c.needsUpdate=!0,c.image.width=u,c.image.height=l,c.image.depth=c.isArrayTexture?c.image.depth:1)),n.width=a.width,n.height=a.height,n.textures=o,n.depthTexture=c||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==s&&(h=!0,c&&(c.needsUpdate=!0),n.sampleCount=s);const f={sampleCount:s};if(e.isXRRenderTarget!==!0){for(let p=0;p<o.length;p++){const g=o[p];h&&(g.needsUpdate=!0),this.updateTexture(g,f)}c&&this.updateTexture(c,f)}n.initialized!==!0&&(n.initialized=!0,this.info.memory.renderTargets++,n.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}updateTexture(e,t={}){const n=this.get(e);if(n.initialized===!0&&n.version===e.version)return;const s=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(s&&n.initialized===!0&&r.destroyTexture(e),e.isFramebufferTexture){const l=this.renderer.getRenderTarget();l?e.type=l.texture.type:e.type=ht}if(e.isHTMLTexture&&e.image){const l=this.renderer.domElement;if("requestPaint"in l){if(l.hasAttribute("layoutsubtree")||l.setAttribute("layoutsubtree","true"),e.image.parentNode!==l&&l.appendChild(e.image),this._htmlTextures.size===0){const c=this._htmlTextures;l.onpaint=d=>{const h=d&&d.changedElements;for(const f of c)(!h||h.includes(f.image))&&(f.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:o,height:a,depth:u}=this.getSize(e);if(t.width=o,t.height=a,t.depth=u,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,o,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,s||e.isStorageTexture===!0||e.isExternalTexture===!0)r.createTexture(e,t),n.generation=e.version;else if(e.version>0){const l=e.image;if(l===void 0)z("Renderer: Texture marked for update but image is undefined.");else if(l.complete===!1)z("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const d=[];for(const h of e.images)d.push(h);t.images=d}else t.image=l;(n.isDefaultTexture===void 0||n.isDefaultTexture===!0)&&(r.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),e.source.dataReady===!0&&r.updateTexture(e,t);const c=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!c&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;n.initialized!==!0&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&Ge.enabled===!0&&Ge.getTransfer(e.colorSpace)!==ae&&z("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=TN){let n=e.images?e.images[0]:e.image;return n?(n.image!==void 0&&(n=n.image),e.isHTMLTexture?(t.width=n.offsetWidth||1,t.height=n.offsetHeight||1,t.depth=1):typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):typeof VideoFrame<"u"&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let s;return e.mipmaps.length>0?s=e.mipmaps.length:e.isCompressedTexture===!0?s=1:s=Math.floor(Math.log2(Math.max(t,n)))+1,s}needsMipmaps(e){return e.generateMipmaps===!0||e.mipmaps.length>0}_destroyRenderTarget(e){if(this.has(e)===!0){const t=this.get(e),n=t.textures,s=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let r=0;r<n.length;r++)this._destroyTexture(n[r]);s&&this._destroyTexture(s),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(this.has(e)===!0){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const n=t.isDefaultTexture;if(this.backend.destroyTexture(e,n),t.bindGroups)for(const s of t.bindGroups){const r=this.backend.get(s);r.groups=void 0,r.versions=void 0}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class nc extends Dt{constructor(e,t,n,s=1){super(e,t,n),this.a=s}set(e,t,n,s=1){return this.a=s,super.set(e,t,n)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class SN extends ye{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const n=this.getNodeType(e),s=e.getStructTypeNode(n);let r;return s!==null?r=s.getMemberType(e,t):(k(`TSL: Member "${t}" not found in struct "${n}".`,new at),r="float"),r}getHash(){return String(this.id)}generate(){return this.name}}class NN extends X{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput(e)?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.hasOutput(e)?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput(e)?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return e.isNode!==!0?(k("TSL: Invalid node added to stack.",new at),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const n=new Dr(t);return this._currentCond=Tt(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){const n=new Dr(t),s=Tt(e,n);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new Dr(e),this}Switch(e){return this._expressionNode=q(e),this}Case(...e){const t=[];if(e.length>=2)for(let a=0;a<e.length-1;a++)t.push(this._expressionNode.equal(q(e[a])));else k("TSL: Invalid parameter length. Case() requires at least two parameters.",new at);const n=e[e.length-1],s=new Dr(n);let r=t[0];for(let a=1;a<t.length;a++)r=r.or(t[a]);const o=Tt(r,s);return this._currentCond===null?(this._currentCond=o,this.addToStack(this._currentCond)):(this._currentCond.elseNode=o,this._currentCond=o,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const s of this.getChildren())s.isVarNode&&s.isIntent(e)&&s.isAssign(e)!==!0||(t["node"+n++]=s);return t.outputNode||null}hasOutput(e){return this.outputNode&&this.outputNode.isNode&&this.outputNode.getNodeType(e)!=="void"}build(e,...t){const n=tp(),s=e.buildStage;To(this),e.setActiveStack(this);const r=l=>{if(this._currentNode=l,!(l.isVarNode&&l.isIntent(e)&&l.isAssign(e)!==!0)){if(s==="setup")l.build(e);else if(s==="analyze")l.build(e,this);else if(s==="generate"){const c=e.getDataFromNode(l,"any").stages,d=c&&c[e.shaderStage];if(l.isVarNode&&d&&d.length===1&&d[0]&&d[0].isStackNode)return;l.build(e,"void")}}},o=[...this.nodes];for(const l of o)r(l);this._currentNode=null;const a=this.nodes.filter(l=>o.indexOf(l)===-1);for(const l of a)r(l);let u;return this.hasOutput(e)?u=this.outputNode.build(e,...t):u=super.build(e,...t),To(n),e.removeActiveStack(this),u}}const ja=Ne(NN).setParameterLength(0,1);class Eg extends je{static get type(){return"BitcastNode"}constructor(e,t,n=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=n,this.isBitcastNode=!0}generateNodeType(e){if(this.inputType!==null){const t=this.valueNode.getNodeType(e),n=e.getTypeLength(t);return e.getTypeFromLength(n,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let n="";if(this.inputType!==null){const s=this.valueNode.getNodeType(e);n=e.getTypeLength(s)===1?this.inputType:e.changeComponentType(s,this.inputType)}else n=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,n)}( ${this.valueNode.build(e,n)} )`}}const RN=$(Eg).setParameterLength(2),wN=i=>new Eg(i,"uint","float"),Fi={};class ys extends x{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){n==="int"?t.assign(RN(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return de;case"int":return Be;case"uvec2":return sp;case"uvec3":return ip;case"uvec4":return ap;case"ivec2":return Xt;case"ivec3":return rp;case"ivec4":return op}}_createTrailingZerosBaseLayout(e,t){const n=this._returnDataNode(t);return M(([r])=>{const o=de(0);this._resolveElementType(r,o,t);const a=w(o.bitAnd(yp(o))),l=wN(a).shiftRight(23).sub(127);return n(l)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const n=this._returnDataNode(t);return M(([r])=>{Se(r.equal(de(0)),()=>de(32));const o=de(0),a=de(0);return this._resolveElementType(r,o,t),Se(o.shiftRight(16).equal(0),()=>{a.addAssign(16),o.shiftLeftAssign(16)}),Se(o.shiftRight(24).equal(0),()=>{a.addAssign(8),o.shiftLeftAssign(8)}),Se(o.shiftRight(28).equal(0),()=>{a.addAssign(4),o.shiftLeftAssign(4)}),Se(o.shiftRight(30).equal(0),()=>{a.addAssign(2),o.shiftLeftAssign(2)}),Se(o.shiftRight(31).equal(0),()=>{a.addAssign(1)}),n(a)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const n=this._returnDataNode(t);return M(([r])=>{const o=de(0);this._resolveElementType(r,o,t),o.assign(o.sub(o.shiftRight(de(1)).bitAnd(de(1431655765)))),o.assign(o.bitAnd(de(858993459)).add(o.shiftRight(de(2)).bitAnd(de(858993459))));const a=o.add(o.shiftRight(de(4))).bitAnd(de(252645135)).mul(de(16843009)).shiftRight(de(24));return n(a)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,n,s){const r=this._returnDataNode(t);return M(([a])=>{if(n===1)return r(s(a));{const u=r(0),l=["x","y","z","w"];for(let c=0;c<n;c++){const d=l[c];u[d].assign(s(a[d]))}return u}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){const{method:t,aNode:n}=this,{renderer:s}=e;if(s.backend.isWebGPUBackend)return super.setup(e);const r=this.getInputType(e),o=e.getElementType(r),a=e.getTypeLength(r),u=`${t}_base_${o}`,l=`${t}_${r}`;let c=Fi[u];if(c===void 0){switch(t){case ys.COUNT_LEADING_ZEROS:{c=this._createLeadingZerosBaseLayout(u,o);break}case ys.COUNT_TRAILING_ZEROS:{c=this._createTrailingZerosBaseLayout(u,o);break}case ys.COUNT_ONE_BITS:{c=this._createOneBitsBaseLayout(u,o);break}}Fi[u]=c}let d=Fi[l];return d===void 0&&(d=this._createMainLayout(l,r,a,c),Fi[l]=d),M(()=>d(n))()}}ys.COUNT_TRAILING_ZEROS="countTrailingZeros";ys.COUNT_LEADING_ZEROS="countLeadingZeros";ys.COUNT_ONE_BITS="countOneBits";new St;const EN=new Ss;ms.flipX();EN.depthTexture=new nn(1,1);const qa=new El(-1,1,1,-1,0,1);class AN extends si{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new go([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new go(t,2))}}const CN=new AN;class Ag extends kt{constructor(e=null){super(CN,e),this.camera=qa,this.isQuadMesh=!0}async renderAsync(e){Oe('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,qa)}render(e){e.render(this,qa)}}const Cg=M(([i])=>on(w(52.9829189).mul(on(xs(i,W(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),Qt=M(([i,e,t])=>{const n=w(2.399963229728653),s=Wn(w(i).add(.5).div(w(e))),r=w(i).mul(n).add(t);return W(Kt(r),yt(r)).mul(s)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class _t extends X{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===_t.OBJECT?this.updateType=te.OBJECT:e===_t.MATERIAL?this.updateType=te.RENDER:e===_t.FRAME?this.updateType=te.FRAME:e===_t.BEFORE_OBJECT?this.updateBeforeType=te.OBJECT:e===_t.BEFORE_MATERIAL?this.updateBeforeType=te.RENDER:e===_t.BEFORE_FRAME&&(this.updateBeforeType=te.FRAME)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}_t.OBJECT="object";_t.MATERIAL="material";_t.FRAME="frame";_t.BEFORE_OBJECT="beforeObject";_t.BEFORE_MATERIAL="beforeMaterial";_t.BEFORE_FRAME="beforeFrame";const Ha=new St,MN=Y(0).setGroup(J).onRenderUpdate(({scene:i})=>i.backgroundBlurriness),jd=Y(1).setGroup(J).onRenderUpdate(({scene:i})=>i.backgroundIntensity),BN=Y(new St).setGroup(J).onRenderUpdate(({scene:i})=>{const e=i.background;return e!==null&&e.isTexture&&e.mapping!==qm?Ha.makeRotationFromEuler(i.backgroundRotation).transpose():Ha.identity(),Ha});M(({texture:i,uv:e})=>{const n=A().toVar();return Se(e.x.lessThan(1e-4),()=>{n.assign(A(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{n.assign(A(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{n.assign(A(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{n.assign(A(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{n.assign(A(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{n.assign(A(0,0,-1))}).Else(()=>{const r=i.sample(e.add(A(-.01,0,0))).r.sub(i.sample(e.add(A(.01,0,0))).r),o=i.sample(e.add(A(0,-.01,0))).r.sub(i.sample(e.add(A(0,.01,0))).r),a=i.sample(e.add(A(0,0,-.01))).r.sub(i.sample(e.add(A(0,0,.01))).r);n.assign(A(r,o,a))}),n.normalize()});M(([i,e])=>i.mul(e).floor().div(e));const Di=new ce;class PN extends ui{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){const t=e.getNodeProperties(this);return t.passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class qd extends PN{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class Jo extends je{static get type(){return"PassNode"}constructor(e,t,n,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=s,this._pixelRatio=1,this._width=1,this._height=1;const r=new nn;r.isRenderTargetTexture=!0,r.name="depth";const o=new Ss(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:it,...s});o.texture.name="output",o.depthTexture=r,this.renderTarget=o,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:o.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Y(0),this._cameraFar=Y(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=te.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return z("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return z("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];return t===void 0&&(t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)),t}getPreviousTexture(e){let t=this._previousTextures[e];return t===void 0&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(t!==void 0){const n=this._textures[e],s=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return t===void 0&&(t=new qd(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return t===void 0&&(this._textureNodes[e]===void 0&&this.getTextureNode(e),t=new qd(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(t===void 0){const n=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=sg(this.getTextureNode(e),n,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(t===void 0){const n=this._cameraNear,s=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=jr(r,n,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),n=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(n)}setup({renderer:e}){return this.renderTarget.samples=this.options.samples===void 0?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),e.reversedDepthBuffer===!0&&(this.renderTarget.depthTexture.type=rt),this.scope===Jo.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let s,r;const o=t.getOutputRenderTarget();o&&o.isXRRenderTarget===!0?(r=1,s=t.xr.getCamera(),t.xr.updateCamera(s),Di.set(o.width,o.height)):(s=this.camera,r=t.getPixelRatio(),t.getSize(Di)),this._pixelRatio=r,this.setSize(Di.width,Di.height);const a=t.getRenderTarget(),u=t.getMRT(),l=t.autoClear,c=t.transparent,d=t.opaque,h=s.layers.mask,f=t.contextNode,p=n.overrideMaterial;this._cameraNear.value=s.near,this._cameraFar.value=s.far,this._layers!==null&&(s.layers.mask=this._layers.mask);for(const m in this._previousTextures)this.toggleTexture(m);this.overrideMaterial!==null&&(n.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,this.contextNode!==null&&((this._contextNodeCache===null||this._contextNodeCache.version!==this.version)&&(this._contextNodeCache={version:this.version,context:Rs({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const g=n.name;n.name=this.name?this.name:n.name,t.render(n,s),n.name=g,n.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(u),t.autoClear=l,t.transparent=c,t.opaque=d,t.contextNode=f,s.layers.mask=h}setSize(e,t){this._width=e,this._height=t;const n=Math.floor(this._width*this._pixelRatio*this._resolutionScale),s=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(n,s),this._scissor!==null?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,this._viewport!==null&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,n,s){e===null?this._scissor=null:(this._scissor===null&&(this._scissor=new ze),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,s))}setViewport(e,t,n,s){e===null?this._viewport=null:(this._viewport===null&&(this._viewport=new ze),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,s))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Jo.COLOR="color";Jo.DEPTH="depth";const FN=M(([i,e])=>i.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),DN=M(([i,e])=>(i=i.mul(e),i.div(i.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),LN=M(([i,e])=>{i=i.mul(e),i=i.sub(.004).max(0);const t=i.mul(i.mul(6.2).add(.5)),n=i.mul(i.mul(6.2).add(1.7)).add(.06);return t.div(n).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),UN=M(([i])=>{const e=i.mul(i.add(.0245786)).sub(90537e-9),t=i.mul(i.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),ON=M(([i,e])=>{const t=Ze(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),n=Ze(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return i=i.mul(e).div(.6),i=t.mul(i),i=UN(i),i=n.mul(i),i.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),IN=Ze(A(1.6605,-.1246,-.0182),A(-.5876,1.1329,-.1006),A(-.0728,-.0083,1.1187)),kN=Ze(A(.6274,.0691,.0164),A(.3293,.9195,.088),A(.0433,.0113,.8956)),GN=M(([i])=>{const e=A(i).toVar(),t=A(e.mul(e)).toVar(),n=A(t.mul(t)).toVar();return w(15.5).mul(n.mul(t)).sub(ue(40.14,n.mul(e))).add(ue(31.96,n).sub(ue(6.868,t.mul(e))).add(ue(.4298,t).add(ue(.1191,e).sub(.00232))))}),VN=M(([i,e])=>{const t=A(i).toVar(),n=Ze(A(.856627153315983,.137318972929847,.11189821299995),A(.0951212405381588,.761241990602591,.0767994186031903),A(.0482516061458583,.101439036467562,.811302368396859)),s=Ze(A(1.1271005818144368,-.1413297634984383,-.14132976349843826),A(-.11060664309660323,1.157823702216272,-.11060664309660294),A(-.016493938717834573,-.016493938717834257,1.2519364065950405)),r=w(-12.47393),o=w(4.026069);return t.mulAssign(e),t.assign(kN.mul(t)),t.assign(n.mul(t)),t.assign(Je(t,1e-10)),t.assign(Rn(t)),t.assign(t.sub(r).div(o.sub(r))),t.assign(jn(t,0,1)),t.assign(GN(t)),t.assign(s.mul(t)),t.assign(qo(Je(A(0),t),A(2.2))),t.assign(IN.mul(t)),t.assign(jn(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),$N=M(([i,e])=>{const t=w(.76),n=w(.15);i=i.mul(e);const s=sr(i.r,sr(i.g,i.b)),r=Tt(s.lessThan(.08),s.sub(ue(6.25,s.mul(s))),.04);i.subAssign(r);const o=Je(i.r,Je(i.g,i.b));Se(o.lessThan(t),()=>i);const a=ct(1,t),u=ct(1,a.mul(a).div(o.add(a.sub(t))));i.mulAssign(u.div(o));const l=ct(1,rn(1,n.mul(o.sub(u)).add(1)));return Te(i,A(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Ke extends X{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class zN extends Ke{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return n===void 0&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),s=n.name,r=n.type,o=e.getCodeFromNode(this,r);s!==""&&(o.name=s);const a=e.getPropertyName(o),u=this.getNodeFunction(e).getCode(a);return o.code=u+`
|
|
539
|
-
`,t==="property"?a:e.format(`${a}()`,r,t)}}function sc(i){let e;const t=i.context.getViewZ;return t!==void 0&&(e=t(this)),(e||$e.z).negate()}const WN=M(([i,e],t)=>{const n=sc(t);return En(i,e,n)}),jN=M(([i],e)=>{const t=sc(e);return i.mul(i,t,t).negate().exp().oneMinus()});M(([i,e],t)=>{const n=sc(t),r=e.sub(rr.y).max(0).toConst().mul(n).toConst();return i.mul(i,r,r).negate().exp().oneMinus()});const Hd=M(([i,e])=>ie(e.toFloat().mix($r.rgb,i.toVec3()),$r.a));class qN extends X{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:n}=e;n.backend.isWebGLBackend===!0?e.addFlowCode(` // ${t}Barrier
|
|
540
|
-
`):e.addLineFlowCode(`${t}Barrier()`,this)}}Ne(qN);class ln extends X{static get type(){return"AtomicFunctionNode"}constructor(e,t,n){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),n=t.parents,s=this.method,r=this.getNodeType(e),o=this.getInputType(e),a=this.pointerNode,u=this.valueNode,l=[];l.push(`&${a.build(e,o)}`),u!==null&&l.push(u.build(e,o));const c=`${e.getMethod(s,r)}( ${l.join(", ")} )`;if(n?n.length===1&&n[0].isStackNode===!0:!1)e.addLineFlowCode(c,this);else return t.constNode===void 0&&(t.constNode=Yt(c,r).toConst()),t.constNode.build(e)}}ln.ATOMIC_LOAD="atomicLoad";ln.ATOMIC_STORE="atomicStore";ln.ATOMIC_ADD="atomicAdd";ln.ATOMIC_SUB="atomicSub";ln.ATOMIC_MAX="atomicMax";ln.ATOMIC_MIN="atomicMin";ln.ATOMIC_AND="atomicAnd";ln.ATOMIC_OR="atomicOr";ln.ATOMIC_XOR="atomicXor";Ne(ln);class ge extends je{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,n=null){super(),this.method=e,this.aNode=t,this.bNode=n}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,n=this.bNode?this.bNode.getNodeType(e):null,s=e.isMatrix(t)?0:e.getTypeLength(t),r=e.isMatrix(n)?0:e.getTypeLength(n);return s>r?t:n}generateNodeType(e){const t=this.method;return t===ge.SUBGROUP_ELECT?"bool":t===ge.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const n=this.method,s=this.getNodeType(e),r=this.getInputType(e),o=this.aNode,a=this.bNode,u=[];if(n===ge.SUBGROUP_BROADCAST||n===ge.SUBGROUP_SHUFFLE||n===ge.QUAD_BROADCAST){const c=a.getNodeType(e);u.push(o.build(e,s),a.build(e,c==="float"?"int":s))}else n===ge.SUBGROUP_SHUFFLE_XOR||n===ge.SUBGROUP_SHUFFLE_DOWN||n===ge.SUBGROUP_SHUFFLE_UP?u.push(o.build(e,s),a.build(e,"uint")):(o!==null&&u.push(o.build(e,r)),a!==null&&u.push(a.build(e,r)));const l=u.length===0?"()":`( ${u.join(", ")} )`;return e.format(`${e.getMethod(n,s)}${l}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}ge.SUBGROUP_ELECT="subgroupElect";ge.SUBGROUP_BALLOT="subgroupBallot";ge.SUBGROUP_ADD="subgroupAdd";ge.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd";ge.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd";ge.SUBGROUP_MUL="subgroupMul";ge.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul";ge.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul";ge.SUBGROUP_AND="subgroupAnd";ge.SUBGROUP_OR="subgroupOr";ge.SUBGROUP_XOR="subgroupXor";ge.SUBGROUP_MIN="subgroupMin";ge.SUBGROUP_MAX="subgroupMax";ge.SUBGROUP_ALL="subgroupAll";ge.SUBGROUP_ANY="subgroupAny";ge.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst";ge.QUAD_SWAP_X="quadSwapX";ge.QUAD_SWAP_Y="quadSwapY";ge.QUAD_SWAP_DIAGONAL="quadSwapDiagonal";ge.SUBGROUP_BROADCAST="subgroupBroadcast";ge.SUBGROUP_SHUFFLE="subgroupShuffle";ge.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor";ge.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp";ge.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown";ge.QUAD_BROADCAST="quadBroadcast";let Li;function ea(i){Li=Li||new WeakMap;let e=Li.get(i);return e===void 0&&Li.set(i,e={}),e}function rc(i){const e=ea(i);return e.shadowMatrix||(e.shadowMatrix=Y("mat4").setGroup(J).onRenderUpdate(t=>((i.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&(i.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(i.shadow.camera.coordinateSystem=t.camera.coordinateSystem,i.shadow.camera.updateProjectionMatrix()),i.shadow.updateMatrices(i)),i.shadow.matrix)))}function HN(i,e=rr){const t=rc(i).mul(e);return t.xyz.div(t.w)}function Mg(i){const e=ea(i);return e.position||(e.position=Y(new V).setGroup(J).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(i.matrixWorld)))}function XN(i){const e=ea(i);return e.targetPosition||(e.targetPosition=Y(new V).setGroup(J).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(i.target.matrixWorld)))}function Bg(i){const e=ea(i);return e.viewPosition||(e.viewPosition=Y(new V).setGroup(J).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new V,n.value.setFromMatrixPosition(i.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}const Pg=i=>An.transformDirection(Mg(i).sub(XN(i))),KN=i=>i.sort((e,t)=>e.id-t.id),YN=(i,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===i)return t;return null},Xa=new WeakMap,Cr=[];class Fg extends X{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=zn("vec3","totalDiffuse"),this.totalSpecularNode=zn("vec3","totalSpecular"),this.outgoingLightNode=zn("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let n=0;n<e.length;n++){const s=e[n];if(Cr.push(s.id),Cr.push(s.castShadow?1:0),s.isSpotLight===!0){const r=s.map!==null?s.map.id:-1,o=s.colorNode?s.colorNode.getCacheKey():-1;Cr.push(r,o)}}const t=oi(Cr);return Cr.length=0,t}getHash(e){if(this._lightNodesHash===null){this._lightNodes===null&&this.setupLightsNode(e);const t=[];for(const n of this._lightNodes)t.push(n.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],n=this._lightNodes,s=KN(this._lights),r=e.renderer.library;for(const o of s)if(o.isNode)t.push(q(o));else{let a=null;if(n!==null&&(a=YN(o.id,n)),a===null){const u=r.getLightNodeClass(o.constructor);if(u===null){z(`LightsNode.setupNodeLights: Light node not found for ${o.constructor.name}`);continue}Xa.has(o)===!1&&Xa.set(o,new u(o)),a=Xa.get(o)}t.push(a)}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:s,reflectedLight:r}=e.context;s.direct({...n,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:s,reflectedLight:r}=e.context;s.directRectArea({...n,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return this._lightNodes===null&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const s=e.context,r=s.lightingModel,o=e.getNodeProperties(this);if(r){const{totalDiffuseNode:a,totalSpecularNode:u}=this;s.outgoingLight=n;const l=e.addStack();o.nodes=l.nodes,r.start(e);const{backdrop:c,backdropAlpha:d}=s,{directDiffuse:h,directSpecular:f,indirectDiffuse:p,indirectSpecular:g}=s.reflectedLight;let m=h.add(p);c!==null&&(d!==null?m=A(d.mix(m,c)):m=A(c)),a.assign(m),u.assign(f.add(g)),n.assign(a.add(u)),r.finish(e),n=n.bypass(e.removeStack())}else o.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class QN extends X{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=te.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Dg.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||rr)}}const Dg=zn("vec3","shadowPositionWorld");function ZN(i,e={}){return e.toneMapping=i.toneMapping,e.toneMappingExposure=i.toneMappingExposure,e.outputColorSpace=i.outputColorSpace,e.renderTarget=i.getRenderTarget(),e.activeCubeFace=i.getActiveCubeFace(),e.activeMipmapLevel=i.getActiveMipmapLevel(),e.renderObjectFunction=i.getRenderObjectFunction(),e.pixelRatio=i.getPixelRatio(),e.mrt=i.getMRT(),e.clearColor=i.getClearColor(e.clearColor||new Dt),e.clearAlpha=i.getClearAlpha(),e.autoClear=i.autoClear,e.scissorTest=i.getScissorTest(),e}function JN(i,e){return e=ZN(i,e),i.setMRT(null),i.setRenderObjectFunction(null),i.setClearColor(0,1),i.autoClear=!0,e}function eR(i,e){i.toneMapping=e.toneMapping,i.toneMappingExposure=e.toneMappingExposure,i.outputColorSpace=e.outputColorSpace,i.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),i.setRenderObjectFunction(e.renderObjectFunction),i.setPixelRatio(e.pixelRatio),i.setMRT(e.mrt),i.setClearColor(e.clearColor,e.clearAlpha),i.autoClear=e.autoClear,i.setScissorTest(e.scissorTest)}function tR(i,e={}){return e.background=i.background,e.backgroundNode=i.backgroundNode,e.overrideMaterial=i.overrideMaterial,e}function nR(i,e){return e=tR(i,e),i.background=null,i.backgroundNode=null,i.overrideMaterial=null,e}function sR(i,e){i.background=e.background,i.backgroundNode=e.backgroundNode,i.overrideMaterial=e.overrideMaterial}function rR(i,e,t){return t=JN(i,t),t=nR(e,t),t}function iR(i,e,t){eR(i,t),sR(e,t)}const Eo=new WeakMap,oR=M(({depthTexture:i,shadowCoord:e,depthLayer:t})=>{let n=we(i,e.xy).setName("t_basic");return i.isArrayTexture&&(n=n.depth(t)),n.compare(e.z)}),aR=M(({depthTexture:i,shadowCoord:e,shadow:t,depthLayer:n})=>{const s=(c,d)=>{let h=we(i,c);return i.isArrayTexture&&(h=h.depth(n)),h.compare(d)},r=Pe("mapSize","vec2",t).setGroup(J),o=Pe("radius","float",t).setGroup(J),a=W(1).div(r),u=o.mul(a.x),l=Cg(fr.xy).mul(6.28318530718);return pt(s(e.xy.add(Qt(0,5,l).mul(u)),e.z),s(e.xy.add(Qt(1,5,l).mul(u)),e.z),s(e.xy.add(Qt(2,5,l).mul(u)),e.z),s(e.xy.add(Qt(3,5,l).mul(u)),e.z),s(e.xy.add(Qt(4,5,l).mul(u)),e.z)).mul(1/5)}),uR=M(({depthTexture:i,shadowCoord:e,shadow:t,depthLayer:n})=>{const s=(d,h)=>{let f=we(i,d);return i.isArrayTexture&&(f=f.depth(n)),f.compare(h)},r=Pe("mapSize","vec2",t).setGroup(J),o=W(1).div(r),a=o.x,u=o.y,l=e.xy,c=on(l.mul(r).add(.5));return l.subAssign(c.mul(o)),pt(s(l,e.z),s(l.add(W(a,0)),e.z),s(l.add(W(0,u)),e.z),s(l.add(o),e.z),Te(s(l.add(W(a.negate(),0)),e.z),s(l.add(W(a.mul(2),0)),e.z),c.x),Te(s(l.add(W(a.negate(),u)),e.z),s(l.add(W(a.mul(2),u)),e.z),c.x),Te(s(l.add(W(0,u.negate())),e.z),s(l.add(W(0,u.mul(2))),e.z),c.y),Te(s(l.add(W(a,u.negate())),e.z),s(l.add(W(a,u.mul(2))),e.z),c.y),Te(Te(s(l.add(W(a.negate(),u.negate())),e.z),s(l.add(W(a.mul(2),u.negate())),e.z),c.x),Te(s(l.add(W(a.negate(),u.mul(2))),e.z),s(l.add(W(a.mul(2),u.mul(2))),e.z),c.x),c.y)).mul(1/9)}),lR=M(({depthTexture:i,shadowCoord:e,depthLayer:t},n)=>{let s=we(i).sample(e.xy);i.isArrayTexture&&(s=s.depth(t)),s=s.rg;const r=s.x,o=Je(1e-7,s.y.mul(s.y)),a=n.renderer.reversedDepthBuffer?Zr(r,e.z):Zr(e.z,r),u=w(1).toVar();return Se(a.notEqual(1),()=>{const l=e.z.sub(r);let c=o.div(o.add(l.mul(l)));c=jn(ct(c,.3).div(.65)),u.assign(Je(a,c))}),u}),cR=i=>{let e=Eo.get(i);return e===void 0&&(e=new We,e.colorNode=ie(0,0,0,1),e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.blending=Nn,e.fog=!1,Eo.set(i,e)),e},dR=i=>{const e=Eo.get(i);e!==void 0&&(e.dispose(),Eo.delete(i))},Xd=new Hn,Ds=[],hR=(i,e,t,n)=>{Ds[0]=i,Ds[1]=e;let s=Xd.get(Ds);return(s===void 0||s.shadowType!==t||s.useVelocity!==n)&&(s=(r,o,a,u,l,c,...d)=>{(r.castShadow===!0||r.receiveShadow&&t===Or)&&(n&&(Qf(r).useVelocity=!0),r.onBeforeShadow(i,r,a,e.camera,u,o.overrideMaterial,c),i.renderObject(r,o,a,u,l,c,...d),r.onAfterShadow(i,r,a,e.camera,u,o.overrideMaterial,c))},s.shadowType=t,s.useVelocity=n,Xd.set(Ds,s)),Ds[0]=null,Ds[1]=null,s},fR=M(({samples:i,radius:e,size:t,shadowPass:n,depthLayer:s})=>{const r=w(0).toVar("meanVertical"),o=w(0).toVar("squareMeanVertical"),a=i.lessThanEqual(w(1)).select(w(0),w(2).div(i.sub(1))),u=i.lessThanEqual(w(1)).select(w(0),w(-1));Ct({start:Be(0),end:Be(i),type:"int",condition:"<"},({i:c})=>{const d=u.add(w(c).mul(a));let h=n.sample(pt(fr.xy,W(0,d).mul(e)).div(t));n.value.isArrayTexture&&(h=h.depth(s)),h=h.x,r.addAssign(h),o.addAssign(h.mul(h))}),r.divAssign(i),o.divAssign(i);const l=Wn(o.sub(r.mul(r)).max(0));return W(r,l)}),pR=M(({samples:i,radius:e,size:t,shadowPass:n,depthLayer:s})=>{const r=w(0).toVar("meanHorizontal"),o=w(0).toVar("squareMeanHorizontal"),a=i.lessThanEqual(w(1)).select(w(0),w(2).div(i.sub(1))),u=i.lessThanEqual(w(1)).select(w(0),w(-1));Ct({start:Be(0),end:Be(i),type:"int",condition:"<"},({i:c})=>{const d=u.add(w(c).mul(a));let h=n.sample(pt(fr.xy,W(d,0).mul(e)).div(t));n.value.isArrayTexture&&(h=h.depth(s)),r.addAssign(h.x),o.addAssign(pt(h.y.mul(h.y),h.x.mul(h.x)))}),r.divAssign(i),o.divAssign(i);const l=Wn(o.sub(r.mul(r)).max(0));return W(r,l)}),gR=[oR,aR,uR,lR];let Ka;const Ui=new Ag;class Lg extends QN{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:s,shadow:r,depthLayer:o}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),u=t({depthTexture:n,shadowCoord:s,shadow:r,depthLayer:o});return a.select(u,w(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:s}=e,r=n.biasNode||Pe("bias","float",n).setGroup(J);let o=t,a;if(n.camera.isOrthographicCamera||s.logarithmicDepthBuffer!==!0)o=o.xyz.div(o.w),a=o.z;else{const u=o.w;o=o.xy.div(u);const l=Pe("near","float",n.camera).setGroup(J),c=Pe("far","float",n.camera).setGroup(J);a=rg(u.negate(),l,c)}return o=A(o.x,o.y.oneMinus(),s.reversedDepthBuffer?a.sub(r):a.add(r)),o}getShadowFilterFn(e){return gR[e]}setupRenderTarget(e,t){const n=new nn(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?er:ii;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=n,{shadowMap:s,depthTexture:n}}setupShadow(e){const{renderer:t,camera:n}=e,{light:s,shadow:r}=this,{depthTexture:o,shadowMap:a}=this.setupRenderTarget(r,e),u=t.shadowMap.type,l=t.hasCompatibility(Ns.TEXTURE_COMPARE);if((u===Vh||u===xy)&&l?(o.minFilter=vt,o.magFilter=vt):(o.minFilter=xt,o.magFilter=xt),r.camera.coordinateSystem=n.coordinateSystem,r.camera.updateProjectionMatrix(),u===Or&&r.isPointLightShadow!==!0){o.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Jt,type:it,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Jt,type:it,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Jt,type:it,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Jt,type:it,depthBuffer:!1}));let R=we(o);o.isArrayTexture&&(R=R.depth(this.depthLayer));let v=we(this.vsmShadowMapVertical.texture);o.isArrayTexture&&(v=v.depth(this.depthLayer));const P=Pe("blurSamples","float",r).setGroup(J),D=Pe("radius","float",r).setGroup(J),L=Pe("mapSize","vec2",r).setGroup(J);let j=this.vsmMaterialVertical||(this.vsmMaterialVertical=new We);j.fragmentNode=fR({samples:P,radius:D,size:L,shadowPass:R,depthLayer:this.depthLayer}).context(e.getSharedContext()),j.name="VSMVertical",j=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new We),j.fragmentNode=pR({samples:P,radius:D,size:L,shadowPass:v,depthLayer:this.depthLayer}).context(e.getSharedContext()),j.name="VSMHorizontal"}const c=Pe("intensity","float",r).setGroup(J),d=Pe("normalBias","float",r).setGroup(J),h=rc(s),f=pr.mul(d);let p;!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld?p=h.mul(Dg.add(f)):p=Y("mat4").onObjectUpdate(({object:v},P)=>P.value.multiplyMatrices(h.value,v.matrixWorld)).mul(Xe).add(h.mul(ie(f,0)));const g=this.setupShadowCoord(e,p),m=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(m===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const y=u===Or&&r.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:o,_=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:y,shadowCoord:g,shadow:r,depthLayer:this.depthLayer});let T;t.shadowMap.transmitted===!0&&(a.texture.isCubeTexture?T=dt(a.texture,g.xyz):(T=we(a.texture,g),o.isArrayTexture&&(T=T.depth(this.depthLayer))));let S;T?S=Te(1,_.rgb.mix(T,1),c.mul(T.a)).toVar():S=Te(1,_,c).toVar(),this.shadowMap=a,this.shadow.map=a;const N=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return T&&S.toInspector(`${N} / Color`,()=>this.shadowMap.texture.isCubeTexture?dt(this.shadowMap.texture):we(this.shadowMap.texture)),S.toInspector(`${N} / Depth`,()=>this.shadowMap.texture.isCubeTexture?dt(this.shadowMap.texture).r.oneMinus():Et(this.shadowMap.depthTexture,dr().mul(Zs(we(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(e.renderer.shadowMap.enabled!==!1)return M(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),n===null&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){const{shadow:t,shadowMap:n,light:s}=this,{renderer:r,scene:o}=e;t.updateMatrices(s),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);const a=o.name;o.name=`Shadow Map [ ${s.name||"ID: "+s.id} ]`,r.render(o,t.camera),o.name=a}updateShadow(e){const{shadowMap:t,light:n,shadow:s}=this,{renderer:r,scene:o,camera:a}=e,u=r.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const c=s.camera.layers.mask;(s.camera.layers.mask&4294967294)===0&&(s.camera.layers.mask=a.layers.mask);const d=r.getRenderObjectFunction(),h=r.getMRT(),f=h?h.has("velocity"):!1;Ka=rR(r,o,Ka),o.overrideMaterial=cR(n),r.setRenderObjectFunction(hR(r,s,u,f)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(d),u===Or&&s.isPointLightShadow!==!0&&this.vsmPass(r),s.camera.layers.mask=c,iR(r,o,Ka)}vsmPass(e){const{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),Ui.material=this.vsmMaterialVertical,Ui.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Ui.material=this.vsmMaterialHorizontal,Ui.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,dR(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const mR=(i,e)=>new Lg(i,e),yR=new Dt,Kd=new St,Mr=new V,Ya=new V,bR=[new V(1,0,0),new V(-1,0,0),new V(0,-1,0),new V(0,1,0),new V(0,0,1),new V(0,0,-1)],_R=[new V(0,-1,0),new V(0,-1,0),new V(0,0,-1),new V(0,0,1),new V(0,-1,0),new V(0,-1,0)],xR=[new V(1,0,0),new V(-1,0,0),new V(0,1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1)],TR=[new V(0,-1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1),new V(0,-1,0),new V(0,-1,0)],vR=M(({depthTexture:i,bd3D:e,dp:t})=>dt(i,e).compare(t)),SR=M(({depthTexture:i,bd3D:e,dp:t,shadow:n})=>{const s=Pe("radius","float",n).setGroup(J),r=Pe("mapSize","vec2",n).setGroup(J),o=s.div(r.x),a=bt(e),u=sn(Ts(e,a.x.greaterThan(a.z).select(A(0,1,0),A(1,0,0)))),l=Ts(e,u),c=Cg(fr.xy).mul(6.28318530718),d=Qt(0,5,c),h=Qt(1,5,c),f=Qt(2,5,c),p=Qt(3,5,c),g=Qt(4,5,c);return dt(i,e.add(u.mul(d.x).add(l.mul(d.y)).mul(o))).compare(t).add(dt(i,e.add(u.mul(h.x).add(l.mul(h.y)).mul(o))).compare(t)).add(dt(i,e.add(u.mul(f.x).add(l.mul(f.y)).mul(o))).compare(t)).add(dt(i,e.add(u.mul(p.x).add(l.mul(p.y)).mul(o))).compare(t)).add(dt(i,e.add(u.mul(g.x).add(l.mul(g.y)).mul(o))).compare(t)).mul(1/5)}),NR=M(({filterFn:i,depthTexture:e,shadowCoord:t,shadow:n},s)=>{const r=t.xyz.toConst(),o=r.abs().toConst(),a=o.x.max(o.y).max(o.z),u=Y("float").setGroup(J).onRenderUpdate(()=>n.camera.near),l=Y("float").setGroup(J).onRenderUpdate(()=>n.camera.far),c=Pe("bias","float",n).setGroup(J),d=w(1).toVar();return Se(a.sub(l).lessThanEqual(0).and(a.sub(u).greaterThanEqual(0)),()=>{let h;s.renderer.reversedDepthBuffer?(h=f0(a.negate(),u,l),h.subAssign(c)):(h=ng(a.negate(),u,l),h.addAssign(c));const f=r.normalize();d.assign(i({depthTexture:e,bd3D:f,dp:h,shadow:n}))}),d});class RR extends Lg{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===yy?vR:SR}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:s,shadow:r}){return NR({filterFn:t,depthTexture:n,shadowCoord:s,shadow:r})}setupRenderTarget(e,t){const n=new by(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?er:ii;const s=t.createCubeRenderTarget(e.mapSize.width);return s.texture.name="PointShadowMap",s.depthTexture=n,{shadowMap:s,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:s}=this,{renderer:r,scene:o}=e,a=t.camera,u=t.matrix,l=r.coordinateSystem===Xr,c=l?bR:xR,d=l?_R:TR;n.setSize(t.mapSize.width,t.mapSize.width);const h=r.autoClear,f=r.getClearColor(yR),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let g=0;g<6;g++){r.setRenderTarget(n,g),r.clear();const m=s.distance||a.far;m!==a.far&&(a.far=m,a.updateProjectionMatrix()),Mr.setFromMatrixPosition(s.matrixWorld),a.position.copy(Mr),Ya.copy(a.position),Ya.add(c[g]),a.up.copy(d[g]),a.lookAt(Ya),a.updateMatrixWorld(),u.makeTranslation(-Mr.x,-Mr.y,-Mr.z),Kd.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(Kd,a.coordinateSystem,a.reversedDepth);const y=o.name;o.name=`Point Light Shadow [ ${s.name||"ID: "+s.id} ] - Face ${g+1}`,r.render(o,a),o.name=y}r.autoClear=h,r.setClearColor(f,p)}}const wR=(i,e)=>new RR(i,e);class Es extends gr{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Dt,this.colorNode=e&&e.colorNode||Y(this.color).setGroup(J),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=te.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,this.baseColorNode!==null&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return Bg(this.light).sub(e.context.positionView||$e)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return mR(this.light)}setupShadow(e){const{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let n=this.shadowColorNode;if(n===null){const s=this.light.shadow.shadowNode;let r;s!==void 0?r=q(s):r=this.setupShadowNode(),this.shadowNode=r,this.shadowColorNode=n=this.colorNode.mul(r),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const Ug=M(({lightDistance:i,cutoffDistance:e,decayExponent:t})=>{const n=i.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(n.mul(i.div(e).pow4().oneMinus().clamp().pow2()),n)}),ER=({color:i,lightVector:e,cutoffDistance:t,decayExponent:n})=>{const s=e.normalize(),r=e.length(),o=Ug({lightDistance:r,cutoffDistance:t,decayExponent:n}),a=i.mul(o);return{lightDirection:s,lightColor:a}};class AR extends Es{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Y(0).setGroup(J),this.decayExponentNode=Y(2).setGroup(J)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return wR(this.light)}setupDirect(e){return ER({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}M(([i=dr()],{renderer:e,material:t})=>{const n=Sp(i.mul(2).sub(1));let s;if(t.alphaToCoverage&&e.currentSamples>0){const r=w(n.fwidth()).toVar();s=En(r.oneMinus(),r.add(1),n).oneMinus()}else s=Tt(n.greaterThan(1),0,1);return s});const CR=M(([i,e])=>{const t=i.x,n=i.y,s=i.z;let r=e.element(0).mul(.886227);return r=r.add(e.element(1).mul(2*.511664).mul(n)),r=r.add(e.element(2).mul(2*.511664).mul(s)),r=r.add(e.element(3).mul(2*.511664).mul(t)),r=r.add(e.element(4).mul(2*.429043).mul(t).mul(n)),r=r.add(e.element(5).mul(2*.429043).mul(n).mul(s)),r=r.add(e.element(6).mul(s.mul(s).mul(.743125).sub(.247708))),r=r.add(e.element(7).mul(2*.429043).mul(t).mul(s)),r=r.add(e.element(8).mul(.429043).mul(ue(t,t).sub(ue(n,n)))),r}),Lt=new nc;class MR extends Xn{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const s=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let o=!1;if(r===null)s._clearColor.getRGB(Lt),Lt.a=s._clearColor.a;else if(r.isColor===!0)r.getRGB(Lt),Lt.a=1,o=!0;else if(r.isNode===!0){const u=this.get(e),l=r;Lt.copy(s._clearColor);let c=u.backgroundMesh;if(c===void 0){let T=function(){r.removeEventListener("dispose",T),c.material.dispose(),c.geometry.dispose()};const h=ie(l).mul(jd).context({getUV:()=>BN.mul(VT),getTextureLevel:()=>MN}),f=Wr.element(3).element(3).equal(1),p=rn(1,Wr.element(1).element(1)).mul(3),g=f.select(Xe.mul(p),Xe),m=li.mul(ie(g,0));let y=Wr.mul(ie(m.xyz,1));y=y.setZ(y.w);const _=new We;_.name="Background.material",_.side=ot,_.depthTest=!1,_.depthWrite=!1,_.allowOverride=!1,_.fog=!1,_.lights=!1,_.vertexNode=y,_.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=c=new kt(new _l(1,32,32),_),c.frustumCulled=!1,c.name="Background.mesh",r.addEventListener("dispose",T)}const d=l.getCacheKey();u.backgroundCacheKey!==d&&(u.backgroundMeshNode.node=ie(l).mul(jd),u.backgroundMeshNode.needsUpdate=!0,c.material.needsUpdate=!0,u.backgroundCacheKey=d),t.unshift(c,c.geometry,c.material,0,0,null,null)}else k("Renderer: Unsupported background configuration.",r);const a=s.xr.getEnvironmentBlendMode();if(a==="additive"?Lt.set(0,0,0,1):a==="alpha-blend"&&Lt.set(0,0,0,0),s.autoClear===!0||o===!0){const u=n.clearColorValue;u.r=Lt.r,u.g=Lt.g,u.b=Lt.b,u.a=Lt.a,(s.backend.isWebGLBackend===!0||s.alpha===!0)&&(u.r*=u.a,u.g*=u.a,u.b*=u.a),n.depthClearValue=s.getClearDepth(),n.stencilClearValue=s.getClearStencil(),n.clearColor=s.autoClearColor===!0,n.clearDepth=s.autoClearDepth===!0,n.clearStencil=s.autoClearStencil===!0}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let BR=0;class cl{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=BR++}}class PR{constructor(e,t,n,s,r,o,a,u,l,c=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=c,this.nodeAttributes=s,this.bindings=r,this.updateNodes=o,this.updateBeforeNodes=a,this.updateAfterNodes=u,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){const s=new cl(t.name,[]);e.push(s);for(const r of t.bindings)s.bindings.push(r.clone())}else e.push(t);return e}}class Yd{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class FR{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class Og{constructor(e,t,n=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=s}}class DR extends Og{constructor(e,t,n=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=s}}class LR{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let UR=0;class Qa{constructor(e=null){this.id=UR++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class OR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class Kn{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class IR extends Kn{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class kR extends Kn{constructor(e,t=new ce){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class GR extends Kn{constructor(e,t=new V){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class VR extends Kn{constructor(e,t=new ze){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class $R extends Kn{constructor(e,t=new Dt){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class zR extends Kn{constructor(e,t=new Ef){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class WR extends Kn{constructor(e,t=new ri){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class jR extends Kn{constructor(e,t=new St){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class qR extends IR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class HR extends kR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class XR extends GR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class KR extends VR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class YR extends $R{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class QR extends zR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ZR extends WR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class JR extends jR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let ew=0;const Qd=new WeakMap,tw=new WeakMap,nw=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Oi=i=>/e/g.test(i)?String(i).replace(/\+/g,""):(i=Number(i),i+(i%1?"":".0"));class Ig{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=ja(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Qa,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:ew++})}isFlatShading(){return this.material.flatShading===!0||this.geometry.hasAttribute("normal")===!1}isOpaque(){const e=this.material;return e.transparent===!1&&e.blending===gn&&e.alphaToCoverage===!1}createRenderTarget(e,t,n){return new Ss(e,t,n)}createCubeRenderTarget(e,t){return new ug(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=t[0].groupNode;let s=n.shared;if(s)for(let o=1;o<t.length;o++)n!==t[o].groupNode&&(s=!1);let r;if(s){let o="";for(const c of t)if(c.isNodeUniformsGroup){c.uniforms.sort((d,h)=>d.nodeUniform.node.id-h.nodeUniform.node.id);for(const d of c.uniforms)o+=d.nodeUniform.node.id}else o+=c.nodeUniform.id;const a=this.renderer._currentRenderContext||this.renderer;let u=Qd.get(a);u===void 0&&(u=new Map,Qd.set(a,u));const l=ur(o);r=u.get(l),r===void 0&&(r=new cl(e,t),u.set(l,r))}else r=new cl(e,t);return r}getBindGroupArray(e,t){const n=this.bindings[t];let s=n[e];return s===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(e===null){const t={},n=this.bindings;for(const s of Na)for(const r in n[s]){const o=n[s][r],a=t[r]||(t[r]=[]);for(const u of o)a.includes(u)===!1&&a.push(u)}e=[];for(const s in t){const r=t[s],o=this._getBindGroup(s,r);e.push(o)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((t,n)=>t.bindings[0].groupNode.order-n.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const n=e[t];this.bindingsIndexes[n.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.includes(e)===!1&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();(t!==te.NONE||n!==te.NONE)&&this.sequentialNodes.includes(e)===!1&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes)e.getUpdateType()!==te.NONE&&this.updateNodes.push(e);for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t!==te.NONE&&this.updateBeforeNodes.push(e),n!==te.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===vt||e.magFilter===bu||e.magFilter===Yr||e.magFilter===fs||e.minFilter===vt||e.minFilter===bu||e.minFilter===Yr||e.minFilter===fs}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const n=this.getDataFromNode(e);return n.cache===void 0&&(n.cache=new Qa(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){z("Abstract function.")}getInstanceIndex(){z("Abstract function.")}getDrawIndex(){z("Abstract function.")}getFrontFacing(){z("Abstract function.")}getFragCoord(){z("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,t.usageCount}generateTexture(){z("Abstract function.")}generateTextureLod(){z("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let s=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const o=n?n[r]:null;o!==null?s+=o.build(this,e):s+=this.generateConst(e),r<t-1&&(s+=", ")}return s+=" )",s}generateStruct(e,t,n=null){const s=[];for(const r of t){const{name:o,type:a}=r;n&&n[o]&&n[o].isNode?s.push(n[o].build(this,a)):s.push(this.generateConst(a))}return e+"( "+s.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new Dt:e==="vec2"||e==="uvec2"||e==="ivec2"?t=new ce:e==="vec3"||e==="uvec3"||e==="ivec3"?t=new V:(e==="vec4"||e==="uvec4"||e==="ivec4")&&(t=new ze)),e==="float")return Oi(t);if(e==="int")return`${Math.round(t)}`;if(e==="uint")return t>=0?`${Math.round(t)}u`:"0u";if(e==="bool")return t?"true":"false";if(e==="color")return`${this.getType("vec3")}( ${Oi(t.r)}, ${Oi(t.g)}, ${Oi(t.b)} )`;const n=this.getTypeLength(e),s=this.getComponentType(e),r=o=>this.generateConst(s,o);if(n===2)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(n===3)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(n===4&&e!=="mat2")return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e==="color"?"vec3":e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){const n=this.attributes;for(const r of n)if(r.name===e)return r;const s=new Yd(e,t);return this.registerDeclaration(s),n.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e==="void"||e==="property"||e==="sampler"||e==="samplerComparison"||e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="depthTexture"||e==="texture3D"}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===st)return"int";if(t===Ve)return"uint"}return"float"}getElementType(e){return e==="mat2"?"vec2":e==="mat3"?"vec3":e==="mat4"?"vec4":this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e==="float"||e==="bool"||e==="int"||e==="uint")return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]==="b"?"bool":t[1]==="i"?"int":t[1]==="u"?"uint":"float"}getVectorType(e){return e==="color"?"vec3":e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="texture3D"?"vec4":e}getTypeFromLength(e,t="float"){if(e===1)return t;let n=Yf(e);const s=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(n=n.replace("vec","mat")),s+n}getTypeFromArray(e){return nw.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,s=e.itemSize,r=e.normalized;let o;return!(e instanceof Rf)&&r!==!0&&(o=this.getTypeFromArray(n)),this.getTypeFromLength(s,o)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return n!==null?Number(n[1]):t==="float"||t==="bool"||t==="int"||t==="uint"?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return t==="int"||t==="uint"?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]===e)this.activeStacks.pop();else throw new Error("NodeBuilder: Invalid active stack removal.")}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=ja(this.stack);const e=tp();return this.stacks.push(e),To(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){const n=this.getDataFromNode(t);n.stack=e}return this.stack=e.parent,To(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){n=n===null?e.isGlobal(this)?this.globalCache:this.cache:n;let s=n.getData(e);s===void 0&&(s={},n.setData(e,s)),s[t]===void 0&&(s[t]={});let r=s[t];const o=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(o);return a&&(r.subBuildsCache===void 0&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),r.subBuilds=o),r}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e,"vertex");let s=n.bufferAttribute;if(s===void 0){const r=this.uniforms.index++;s=new Yd("nodeAttribute"+r,t,e),this.bufferAttributes.push(s),n.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,s=this.shaderStage){const r=this.getDataFromNode(e,s,this.globalCache);let o=r.structType;if(o===void 0){const a=this.structs.index++;n===null&&(n="StructType"+a),o=new OR(n,t),this.structs[s].push(o),this.types[s][n]=e,r.structType=o}return o}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,s=null){const r=this.getDataFromNode(e,n,this.globalCache);let o=r.uniform;if(o===void 0){const a=this.uniforms.index++;o=new FR(s||"nodeUniform"+a,t,e),this.uniforms[n].push(o),this.registerDeclaration(o),r.uniform=o}return o}getVarFromNode(e,t=null,n=e.getNodeType(this),s=this.shaderStage,r=!1){const o=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",o.subBuilds);let u=o[a];if(u===void 0){const l=r?"_const":"_var",c=this.vars[s]||(this.vars[s]=[]),d=this.vars[l]||(this.vars[l]=0);t===null&&(t=(r?"nodeConst":"nodeVar")+d,this.vars[l]++),a!=="variable"&&(t=this.getSubBuildProperty(t,o.subBuilds));const h=e.getArrayCount(this);u=new Og(t,n,r,h),r||c.push(u),this.registerDeclaration(u),o[a]=u}return u}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0)&&(e.cNode?this.isDeterministic(e.cNode):!0);if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0);if(e.isArrayNode){if(e.values!==null){for(const t of e.values)if(!this.isDeterministic(t))return!1}return!0}else if(e.isConstNode)return!0;return!1}getVaryingFromNode(e,t=null,n=e.getNodeType(this),s=null,r=null){const o=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",o.subBuilds);let u=o[a];if(u===void 0){const l=this.varyings,c=l.length;t===null&&(t="nodeVarying"+c),a!=="varying"&&(t=this.getSubBuildProperty(t,o.subBuilds)),u=new DR(t,n,s,r),l.push(u),this.registerDeclaration(u),o[a]=u}return u}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),s=this.getPropertyName(e);let r=1,o=s;for(;n[o]!==void 0;)o=s+"_"+r++;r>1&&(e.name=o,z(`TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${o}'.`)),n[o]=e}getCodeFromNode(e,t,n=this.shaderStage){const s=this.getDataFromNode(e);let r=s.code;if(r===void 0){const o=this.codes[n]||(this.codes[n]=[]),a=o.length;r=new LR("nodeCode"+a,t),o.push(r),s.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:s}=this.getDataFromNode(e);let r=!0,o=t;for(;o;){if(s.get(o)===!0){r=!1;break}o=this.getDataFromNode(o).parentNodeBlock}if(r)for(const a of n)this.addLineFlowCode(a)}addLineFlowCodeBlock(e,t,n){const s=this.getDataFromNode(e),r=s.flowCodes||(s.flowCodes=[]),o=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);r.push(t),o.set(n,!0)}addLineFlowCode(e,t=null){return e===""?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e=e+`;
|
|
541
|
-
`),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=" ",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new zN,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout,n={[Symbol.iterator](){let o=0;const a=Object.values(this);return{next:()=>({value:a[o],done:o++>=a.length})}}};for(const o of t.inputs)n[o.name]=new SN(o.type,o.name);e.layout=null;const s=e.call(n),r=this.flowStagesNode(s,t.type);return e.layout=t,r}flowBuildStage(e,t,n=null){const s=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,n);return this.setBuildStage(s),r}flowStagesNode(e,t=null){const n=this.flow,s=this.vars,r=this.declarations,o=this.cache,a=this.buildStage,u=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new Qa,this.stack=ja();for(const c of Sa)this.setBuildStage(c),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=s,this.declarations=r,this.cache=o,this.stack=u,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){z("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=n,s}flowNodeFromShaderStage(e,t,n=null,s=null){const r=this.tab,o=this.cache,a=this.shaderStage,u=this.context;this.setShaderStage(e);const l={...this.context};delete l.nodeBlock,this.cache=this.globalCache,this.tab=" ",this.context=l;let c=null;if(this.buildStage==="generate"){const d=this.flowChildNode(t,n);s!==null&&(d.code+=`${this.tab+s} = ${d.result};
|
|
542
|
-
`),this.flowCode[e]=this.flowCode[e]+d.code,c=d}else c=t.build(this);return this.setShaderStage(a),this.cache=o,this.tab=r,this.context=u,c}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){z("Abstract function.")}getVaryings(){z("Abstract function.")}getVar(e,t,n=null){return`${n!==null?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e,t=!1){const n=[],s=this.vars[e];if(s!==void 0)for(const r of s)n.push(`${this.getVar(r.type,r.name,r.count)};`);return n.join(t?`
|
|
543
|
-
`:`
|
|
544
|
-
`)}getUniforms(){z("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(t!==void 0)for(const s of t)n+=s.code+`
|
|
545
|
-
`;return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){z("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(e&&e.isNode?e.isShaderCallNodeInternal?t=e.shaderNode.subBuilds:e.isStackNode?t=[e.subBuild]:t=this.getDataFromNode(e,"any").subBuilds:e instanceof Set?t=[...e]:t=e,!t)return null;const n=this.subBuildLayers;for(let s=t.length-1;s>=0;s--){const r=t[s];if(n.includes(r))return r}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n;t!==null?n=this.getClosestSubBuild(t):n=this.subBuildFn;let s;return n?s=e?n+"_"+e:n:s=e,s}prebuild(){const{object:e,renderer:t,material:n}=this;if(t.contextNode.isContextNode===!0?this.context={...this.context,...t.contextNode.getFlowContextData()}:k('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),n&&n.contextNode&&(n.contextNode.isContextNode===!0?this.context={...this.context,...n.contextNode.getFlowContextData()}:k('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),n!==null){let s=t.library.fromMaterial(n);s===null&&(k(`NodeBuilder: Material "${n.type}" is not compatible.`),s=new We),s.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of Sa){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Na){this.setShaderStage(t);const n=this.flowNodes[t];for(const s of n)e==="generate"?this.flowNode(s):s.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(const e of Sa){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Na){this.setShaderStage(t);const n=this.flowNodes[t];for(const s of n)e==="generate"?this.flowNode(s):s.build(this);await $h()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=tw.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let s=n.cache;if(s===void 0){if(t==="float"||t==="int"||t==="uint")s=new qR(e);else if(t==="vec2"||t==="ivec2"||t==="uvec2")s=new HR(e);else if(t==="vec3"||t==="ivec3"||t==="uvec3")s=new XR(e);else if(t==="vec4"||t==="ivec4"||t==="uvec4")s=new KR(e);else if(t==="color")s=new YR(e);else if(t==="mat2")s=new QR(e);else if(t==="mat3")s=new ZR(e);else if(t==="mat4")s=new JR(e);else throw new Error(`Uniform "${t}" not implemented.`);n.cache=s}return s}format(e,t,n){if(t=this.getVectorType(t),n=this.getVectorType(n),t===n||n===null||this.isReference(n))return e;const s=this.getTypeLength(t),r=this.getTypeLength(n);return s===16&&r===9?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:s===9&&r===4?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||r>4||r===0?e:s===r?`${this.getType(n)}( ${e} )`:s>r?(e=n==="bool"?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),n)):r===4&&s>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:s===2?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(s===1&&r>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${Io} - Node System
|
|
546
|
-
`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||Qf(this.object).useVelocity===!0}}class Zd{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return n===void 0&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===te.FRAME){const s=this._getMaps(this.updateBeforeMap,n);if(s.frameId!==this.frameId){const r=s.frameId;s.frameId=this.frameId,e.updateBefore(this)===!1&&(s.frameId=r)}}else if(t===te.RENDER){const s=this._getMaps(this.updateBeforeMap,n);if(s.renderId!==this.renderId){const r=s.renderId;s.renderId=this.renderId,e.updateBefore(this)===!1&&(s.renderId=r)}}else t===te.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===te.FRAME){const s=this._getMaps(this.updateAfterMap,n);s.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(s.frameId=this.frameId)}else if(t===te.RENDER){const s=this._getMaps(this.updateAfterMap,n);s.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(s.renderId=this.renderId)}else t===te.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===te.FRAME){const s=this._getMaps(this.updateMap,n);s.frameId!==this.frameId&&e.update(this)!==!1&&(s.frameId=this.frameId)}else if(t===te.RENDER){const s=this._getMaps(this.updateMap,n);s.renderId!==this.renderId&&e.update(this)!==!1&&(s.renderId=this.renderId)}else t===te.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class ic{constructor(e,t,n=null,s="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=s,this.isConst=r}}ic.isNodeFunctionInput=!0;class sw extends Es{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class rw extends Es{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:Pg(this.light),lightColor:e}}}class iw extends Es{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Mg(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Y(new Dt).setGroup(J)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:s}=this,o=pr.dot(s).mul(.5).add(.5),a=Te(n,t,o);e.context.irradiance.addAssign(a)}}class oc extends Es{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Y(0).setGroup(J),this.penumbraCosNode=Y(0).setGroup(J),this.cutoffDistanceNode=Y(0).setGroup(J),this.decayExponentNode=Y(0).setGroup(J),this.colorNode=Y(this.color).setGroup(J)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:n,penumbraCosNode:s}=this;return En(n,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return n===void 0&&(n=HN(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:s,light:r}=this,o=this.getLightVector(e),a=o.normalize(),u=a.dot(Pg(r)),l=this.getSpotAttenuation(e,u),c=o.length(),d=Ug({lightDistance:c,cutoffDistance:n,decayExponent:s});let h=t.mul(l).mul(d),f,p;return r.colorNode?(p=this.getLightCoord(e),f=r.colorNode(p)):r.map&&(p=this.getLightCoord(e),f=we(r.map,p.xy).onRenderUpdate(()=>r.map)),f&&(h=p.mul(2).sub(1).abs().lessThan(1).all().select(h.mul(f),h)),{lightColor:h,lightDirection:a}}}class ow extends oc{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const n=this.light.iesMap;let s=null;if(n&&n.isTexture===!0){const r=t.acos().mul(1/Math.PI);s=we(n,W(r,0),0).r}else s=super.getSpotAttenuation(t);return s}}class aw extends Es{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let n=0;n<9;n++)t.push(new V);this.lightProbe=At(t)}update(e){const{light:t}=this;super.update(e);for(let n=0;n<9;n++)this.lightProbe.array[n].copy(t.sh.coefficients[n]).multiplyScalar(t.intensity)}setup(e){const t=CR(pr,this.lightProbe);e.context.irradiance.addAssign(t)}}const uw=M(([i,e])=>{const t=i.abs().sub(e);return wn(Je(t,0)).add(sr(Je(t.x,t.y),0))});class lw extends oc{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),t.aspect===null){let n=1;t.map!==null&&(n=t.map.width/t.map.height),t.shadow.aspect=n}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=w(0),n=this.penumbraCosNode,s=rc(this.light).mul(e.context.positionWorld||rr);return Se(s.w.greaterThan(0),()=>{const r=s.xyz.div(s.w),o=uw(r.xy.sub(W(.5)),W(.5)),a=rn(-1,ct(1,gp(n)).sub(1));t.assign(Xl(o.mul(-2).mul(a)))}),t}}const Za=new St,Ii=new St;let Br=null;class cw extends Es{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Y(new V).setGroup(J),this.halfWidth=Y(new V).setGroup(J),this.updateType=te.RENDER}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;Ii.identity(),Za.copy(t.matrixWorld),Za.premultiply(n),Ii.extractRotation(Za),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(Ii),this.halfHeight.value.applyMatrix4(Ii)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=we(Br.LTC_FLOAT_1),n=we(Br.LTC_FLOAT_2)):(t=we(Br.LTC_HALF_1),n=we(Br.LTC_HALF_2));const{colorNode:s,light:r}=this,o=Bg(r);return{lightColor:s,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){Br=e}}class kg{parseFunction(){z("Abstract function.")}}class ac{constructor(e,t,n="",s=""){this.type=e,this.inputs=t,this.name=n,this.precision=s}getCode(){z("Abstract function.")}}ac.isNodeFunction=!0;const dw=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,hw=/[a-z_0-9]+/ig,Jd="#pragma main",fw=i=>{i=i.trim();const e=i.indexOf(Jd),t=e!==-1?i.slice(e+Jd.length):i,n=t.match(dw);if(n!==null&&n.length===5){const s=n[4],r=[];let o=null;for(;(o=hw.exec(s))!==null;)r.push(o);const a=[];let u=0;for(;u<r.length;){const p=r[u][0]==="const";p===!0&&u++;let g=r[u][0];g==="in"||g==="out"||g==="inout"?u++:g="";const m=r[u++][0];let y=Number.parseInt(r[u][0]);Number.isNaN(y)===!1?u++:y=null;const _=r[u++][0];a.push(new ic(m,_,y,g,p))}const l=t.substring(n[0].length),c=n[3]!==void 0?n[3]:"",d=n[2],h=n[1]!==void 0?n[1]:"",f=e!==-1?i.slice(0,e):"";return{type:d,inputs:a,name:c,precision:h,inputsCode:s,blockCode:l,headerCode:f}}else throw new Error("FunctionNode: Function is not a GLSL code.")};class pw extends ac{constructor(e){const{type:t,inputs:n,name:s,precision:r,inputsCode:o,blockCode:a,headerCode:u}=fw(e);super(t,n,s,r),this.inputsCode=o,this.blockCode=a,this.headerCode=u}getCode(e=this.name){let t;const n=this.blockCode;if(n!==""){const{type:s,inputsCode:r,headerCode:o,precision:a}=this;let u=`${s} ${e} ( ${r.trim()} )`;a!==""&&(u=`${a} ${u}`),t=o+u+n}else t="";return t}}class gw extends kg{parseFunction(e){return new pw(e)}}const Rt=[],Pn=[];class mw extends Xn{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new Zd,this.nodeBuilderCache=new Map,this.callHashCache=new Hn,this.groupsData=new Hn,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;Rt[0]=t,Rt[1]=e;let n=this.groupsData.get(Rt);return n===void 0&&this.groupsData.set(Rt,n={}),Rt[0]=null,Rt[1]=null,n.version!==t.version?(n.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const n=this.backend.createNodeBuilder(e.object,this.renderer);return n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n}getForRender(e,t=!1){const n=this.get(e);let s=n.nodeBuilderState;if(s===void 0){const{nodeBuilderCache:r}=this,o=this.getForRenderCacheKey(e);if(s=r.get(o),s===void 0){const a=async()=>{let u=this._createNodeBuilder(e,e.material);try{t?await u.buildAsync():u.build()}catch(l){u=this._createNodeBuilder(e,new We),t?await u.buildAsync():u.build(),k("TSL: "+l)}return u};if(t)return a().then(u=>(s=this._createNodeBuilderState(u),r.set(o,s),s.usedTimes++,n.nodeBuilderState=s,s));{let u=this._createNodeBuilder(e,e.material);try{u.build()}catch(l){u=this._createNodeBuilder(e,new We),u.build();let c=l.stackTrace;!c&&l.stack&&(c=new at(l.stack)),k("TSL: "+l,c)}s=this._createNodeBuilderState(u),r.set(o,s)}}s.usedTimes++,n.nodeBuilderState=s}return s}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(t.nodeBuilderState!==void 0)return t.nodeBuilderState;const n=this.getForRenderCacheKey(e),s=this.nodeBuilderCache.get(n);return s!==void 0?(s.usedTimes++,t.nodeBuilderState=s,s):(t.pendingBuild!==!0&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||this._buildQueue.length===0)return;this._buildInProgress=!0,this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t!==void 0&&(t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(n===void 0){const s=this.backend.createNodeBuilder(e,this.renderer);s.build(),n=this._createNodeBuilderState(s),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new PR(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){Rt[0]=e,Rt[1]=t;const n=this.renderer.info.calls,s=this.callHashCache.get(Rt)||{};if(s.callId!==n){const r=this.getEnvironmentNode(e),o=this.getFogNode(e);t&&Pn.push(t.getCacheKey(!0)),r&&Pn.push(r.getCacheKey()),o&&Pn.push(o.getCacheKey()),Pn.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Pn.push(this.renderer.shadowMap.enabled?1:0),Pn.push(this.renderer.shadowMap.type),s.callId=n,s.cacheKey=oi(Pn),this.callHashCache.set(Rt,s),Pn.length=0}return Rt[0]=null,Rt[1]=null,s.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const s=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==n||s){const r=this.getCacheNode("background",n,()=>{if(n.isCubeTexture===!0||n.mapping===Rl||n.mapping===wl||n.mapping===yu){if(e.backgroundBlurriness>0||n.mapping===yu)return _g(n);{let o;return n.isCubeTexture===!0?o=dt(n):o=we(n),cg(o)}}else{if(n.isTexture===!0)return we(n,ms.flipY()).setUpdateMatrix(!0);n.isColor!==!0&&k("WebGPUNodes: Unsupported background configuration.",n)}},s);t.backgroundNode=r,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,s=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let o=r.get(t);return(o===void 0||s)&&(o=n(),r.set(t,o)),o}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const s=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const r=Pe("color","color",n).setGroup(J),o=Pe("density","float",n).setGroup(J);return Hd(r,jN(o))}else if(n.isFog){const r=Pe("color","color",n).setGroup(J),o=Pe("near","float",n).setGroup(J),a=Pe("far","float",n).setGroup(J);return Hd(r,WN(o,a))}else k("Renderer: Unsupported fog configuration.",n)});t.fogNode=s,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const s=this.getCacheNode("environment",n,()=>{if(n.isCubeTexture===!0)return dt(n);if(n.isTexture===!0)return we(n);k("Nodes: Unsupported environment configuration.",n)});t.environmentNode=s,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,s=null,r=null){const o=this.nodeFrame;return o.renderer=e,o.scene=t,o.object=n,o.camera=s,o.material=r,o}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?we(e,ms).depth(hr("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):we(e,ms).renderOutput(t.toneMapping,t.currentColorSpace)}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const s of n.updateNodes)t.updateNode(s)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const s of n.updateNodes)t.updateNode(s)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Zd,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Ja=new bl;class Ao{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new ri,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,n){const s=e.length;for(let r=0;r<s;r++){Ja.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const o=t[n+r],a=Ja.normal;o.x=-a.x,o.y=-a.y,o.z=-a.z,o.w=Ja.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let n=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const s=t.clippingPlanes,r=s.length;let o,a;if(this.clipIntersection?(o=this.intersectionPlanes,a=e.intersectionPlanes.length):(o=this.unionPlanes,a=e.unionPlanes.length),o.length!==a+r){o.length=a+r;for(let u=0;u<r;u++)o[a+u]=new ze;n=!0}this.projectPlanes(s,o,a),n&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return t===void 0&&(t=new Ao(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class yw{constructor(e,t,n){this.bundleGroup=e,this.camera=t,this.renderContext=n}}const Fn=[];class bw{constructor(){this.bundles=new Hn}get(e,t,n){const s=this.bundles;Fn[0]=e,Fn[1]=t,Fn[2]=n;let r=s.get(Fn);return r===void 0&&(r=new yw(e,t,n),s.set(Fn,r)),Fn[0]=null,Fn[1]=null,Fn[2]=null,r}dispose(){this.bundles=new Hn}}class Gg{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const n=this.getMaterialNodeClass(e.type);if(n!==null){t=new n;for(const s in e)t[s]=e[s]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,n){if(n.has(t)){z(`Redefinition of node ${t}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t=="function"||typeof t=="object")throw new Error(`Base class ${t} is not a class.`);n.set(t,e)}addClass(e,t,n){if(n.has(t)){z(`Redefinition of node ${t.name}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t!="function")throw new Error(`Base class ${t.name} is not a class.`);n.set(t,e)}}const _w=new Fg,eh=new WeakMap;class xw{createNode(e=[]){return new Fg().setLights(e)}getNode(e){if(e.isQuadMesh)return _w;let t=eh.get(e);return t===void 0&&(t=this.createNode(),eh.set(e,t)),t}}class Ur extends Ss{constructor(e=1,t=1,n={}){super(e,t,n),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const th=new V,nh=new V,sh=new WeakMap;class Tw extends Oo{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Hr,this._cameraL.viewport=new ze,this._cameraR=new Hr,this._cameraR.viewport=new ze,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Em,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding=typeof XRWebGLBinding<"u",this._createXRLayer=Ew.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new ce,this._onSessionEvent=Nw.bind(this),this._onSessionEnd=Rw.bind(this),this._onInputSourcesChange=ww.bind(this),this._onAnimationFrame=Aw.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(!(this._glProjLayer===null&&this._glBaseLayer===null))return this._foveation}setFoveation(e){this._foveation=e,this._glProjLayer!==null&&(this._glProjLayer.fixedFoveation=e),this._glBaseLayer!==null&&this._glBaseLayer.fixedFoveation!==void 0&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,this.isPresenting===!0&&z("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&z("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(this._session!==null)return this._session.environmentBlendMode}getBinding(){return this._glBinding===null&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,s,r,o,a,u={}){const l=new Am(e,t),c=new Ur(r,o,{format:It,type:ht,depthTexture:new nn(r,o,u.stencil?Sn:Ve,void 0,void 0,void 0,void 0,void 0,void 0,u.stencil?vn:Tn),stencilBuffer:u.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const d=new On({color:16777215,side:hs});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const h=new kt(l,d);h.position.copy(n),h.quaternion.copy(s);const f={type:"quad",width:e,height:t,translation:n,quaternion:s,pixelwidth:r,pixelheight:o,plane:h,material:d,rendercall:a,renderTarget:c};if(this._layers.push(f),this._session!==null){f.plane.material=new On({color:16777215,side:hs}),f.plane.material.blending=qs,f.plane.material.blendEquation=pn,f.plane.material.blendSrc=Un,f.plane.material.blendDst=Un,f.xrlayer=this._createXRLayer(f);const p=this._session.renderState.layers;p.unshift(f.xrlayer),this._session.updateRenderState({layers:p})}else c.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,n,s,r,o,a,u,l={}){const c=new Ih(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),d=new Ur(o,a,{format:It,type:ht,depthTexture:new nn(o,a,l.stencil?Sn:Ve,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?vn:Tn),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});d._autoAllocateDepthBuffer=!0;const h=new On({color:16777215,side:ot});h.map=d.texture,h.map.offset.y=1,h.map.repeat.y=-1;const f=new kt(c,h);f.position.copy(s),f.quaternion.copy(r);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:s,quaternion:r,pixelwidth:o,pixelheight:a,plane:f,material:h,rendercall:u,renderTarget:d};if(this._layers.push(p),this._session!==null){p.plane.material=new On({color:16777215,side:ot}),p.plane.material.blending=qs,p.plane.material.blendEquation=pn,p.plane.material.blendSrc=Un,p.plane.material.blendDst=Un,p.xrlayer=this._createXRLayer(p);const g=this._session.renderState.layers;g.unshift(p.xrlayer),this._session.updateRenderState({layers:g})}else d.isXRRenderTarget=!1;return f}renderLayers(){const e=new V,t=new Js,n=this._renderer,s=this.isPresenting;this.isPresenting=!1;const r=new ce;n.getSize(r);const o=n.getRenderTarget();for(const a of this._layers){a.renderTarget.isXRRenderTarget=this._session!==null,a.renderTarget._hasExternalTextures=a.renderTarget.isXRRenderTarget;const u=n.contextNode;let l;if(a.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){a.xrlayer.transform=new XRRigidTransform(a.plane.getWorldPosition(e),a.plane.getWorldQuaternion(t));const c=this._glBinding.getSubImage(a.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(a.renderTarget,c.colorTexture,void 0),n._setXRLayerSize(a.renderTarget.width,a.renderTarget.height),l=sh.get(u),l===void 0&&(l=u.context({getOutput:d=>Pp(d,n.toneMapping,n.outputColorSpace)}),sh.set(u,l))}else l=u;n.contextNode=l,n.setRenderTarget(a.renderTarget),a.rendercall(),n.contextNode=u}n.setRenderTarget(o),n._setXRLayerSize(r.x,r.y),this.isPresenting=s}getSession(){return this._session}async setSession(e){const t=this._renderer,n=t.backend;this._gl=t.getContext();const s=this._gl,r=s.getContextAttributes();if(this._session=e,e!==null){if(n.isWebGPUBackend===!0)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await n.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._supportsLayers===!0){let o=null,a=null,u=null;t.depth&&(u=t.stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24,o=t.stencil?vn:Tn,a=t.stencil?Sn:Ve);const l={colorFormat:s.RGBA8,depthFormat:u,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(l.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const c=this._glBinding.createProjectionLayer(l),d=[c];this._glProjLayer=c,t.setPixelRatio(1),t._setXRLayerSize(c.textureWidth,c.textureHeight);const h=this._useMultiview?2:1,f=new nn(c.textureWidth,c.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,o,h);if(this._xrRenderTarget=new Ur(c.textureWidth,c.textureHeight,{format:It,type:ht,colorSpace:t.outputColorSpace,depthTexture:f,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:c.ignoreDepthValues===!1,resolveStencilBuffer:c.ignoreDepthValues===!1,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const p of this._layers)p.plane.material=new On({color:16777215,side:p.type==="cylinder"?ot:hs}),p.plane.material.blending=qs,p.plane.material.blendEquation=pn,p.plane.material.blendSrc=Un,p.plane.material.blendDst=Un,p.xrlayer=this._createXRLayer(p),d.unshift(p.xrlayer);e.updateRenderState({layers:d})}else{const o={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},a=new XRWebGLLayer(e,s,o);this._glBaseLayer=a,e.updateRenderState({baseLayer:a}),t.setPixelRatio(1),t._setXRLayerSize(a.framebufferWidth,a.framebufferHeight),this._xrRenderTarget=new Ur(a.framebufferWidth,a.framebufferHeight,{format:It,type:ht,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:a.ignoreDepthValues===!1,resolveStencilBuffer:a.ignoreDepthValues===!1}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(t===null)return;const n=e.near,s=e.far,r=this._cameraXR,o=this._cameraL,a=this._cameraR;r.near=a.near=o.near=n,r.far=a.far=o.far=s,r.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==r.near||this._currentDepthFar!==r.far)&&(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=e.layers.mask|6,o.layers.mask=r.layers.mask&-5,a.layers.mask=r.layers.mask&-3;const u=e.parent,l=r.cameras;rh(r,u);for(let c=0;c<l.length;c++)rh(l[c],u);l.length===2?vw(r,o,a):r.projectionMatrix.copy(o.projectionMatrix),Sw(e,r,u)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new Cm,this._controllers[e]=t),t}}function vw(i,e,t){th.setFromMatrixPosition(e.matrixWorld),nh.setFromMatrixPosition(t.matrixWorld);const n=th.distanceTo(nh),s=e.projectionMatrix.elements,r=t.projectionMatrix.elements,o=s[14]/(s[10]-1),a=s[14]/(s[10]+1),u=(s[9]+1)/s[5],l=(s[9]-1)/s[5],c=(s[8]-1)/s[0],d=(r[8]+1)/r[0],h=o*c,f=o*d,p=n/(-c+d),g=p*-c;if(e.matrixWorld.decompose(i.position,i.quaternion,i.scale),i.translateX(g),i.translateZ(p),i.matrixWorld.compose(i.position,i.quaternion,i.scale),i.matrixWorldInverse.copy(i.matrixWorld).invert(),s[10]===-1)i.projectionMatrix.copy(e.projectionMatrix),i.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const m=o+p,y=a+p,_=h-g,T=f+(n-g),S=u*a/y*m,N=l*a/y*m;i.projectionMatrix.makePerspective(_,T,S,N,m,y),i.projectionMatrixInverse.copy(i.projectionMatrix).invert()}}function rh(i,e){e===null?i.matrixWorld.copy(i.matrix):i.matrixWorld.multiplyMatrices(e.matrixWorld,i.matrix),i.matrixWorldInverse.copy(i.matrixWorld).invert()}function Sw(i,e,t){t===null?i.matrix.copy(e.matrixWorld):(i.matrix.copy(t.matrixWorld),i.matrix.invert(),i.matrix.multiply(e.matrixWorld)),i.matrix.decompose(i.position,i.quaternion,i.scale),i.updateMatrixWorld(!0),i.projectionMatrix.copy(e.projectionMatrix),i.projectionMatrixInverse.copy(e.projectionMatrixInverse),i.isPerspectiveCamera&&(i.fov=jm*2*Math.atan(1/i.projectionMatrix.elements[5]),i.zoom=1)}function Nw(i){const e=this._controllerInputSources.indexOf(i.inputSource);if(e===-1)return;const t=this._controllers[e];if(t!==void 0){const n=this.getReferenceSpace();t.update(i.inputSource,i.frame,n),t.dispatchEvent({type:i.type,data:i.inputSource})}}function Rw(){const i=this._session,e=this._renderer;i.removeEventListener("select",this._onSessionEvent),i.removeEventListener("selectstart",this._onSessionEvent),i.removeEventListener("selectend",this._onSessionEvent),i.removeEventListener("squeeze",this._onSessionEvent),i.removeEventListener("squeezestart",this._onSessionEvent),i.removeEventListener("squeezeend",this._onSessionEvent),i.removeEventListener("end",this._onSessionEnd),i.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let t=0;t<this._controllers.length;t++){const n=this._controllerInputSources[t];n!==null&&(this._controllerInputSources[t]=null,this._controllers[t].disconnect(n))}if(this._currentDepthNear=null,this._currentDepthFar=null,e._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,this._sessionUsesLayers===!0)for(const t of this._layers)t.renderTarget=new Ur(t.pixelwidth,t.pixelheight,{format:It,type:ht,depthTexture:new nn(t.pixelwidth,t.pixelheight,t.stencilBuffer?Sn:Ve,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?vn:Tn),stencilBuffer:t.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),t.renderTarget.isXRRenderTarget=!1,t.plane.material=t.material,t.material.map=t.renderTarget.texture,t.material.map.offset.y=1,t.material.map.repeat.y=-1,delete t.xrlayer;this.isPresenting=!1,this._useMultiview=!1,e._animation.stop(),e._animation.setAnimationLoop(this._currentAnimationLoop),e._animation.setContext(this._currentAnimationContext),e._animation.start(),e.setPixelRatio(this._currentPixelRatio),e.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function ww(i){const e=this._controllers,t=this._controllerInputSources;for(let n=0;n<i.removed.length;n++){const s=i.removed[n],r=t.indexOf(s);r>=0&&(t[r]=null,e[r].disconnect(s))}for(let n=0;n<i.added.length;n++){const s=i.added[n];let r=t.indexOf(s);if(r===-1){for(let a=0;a<e.length;a++)if(a>=t.length){t.push(s),r=a;break}else if(t[a]===null){t[a]=s,r=a;break}if(r===-1)break}const o=e[r];o&&o.connect(s)}}function Ew(i){return i.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(i.translation,i.quaternion),width:i.width/2,height:i.height/2,space:this._referenceSpace,viewPixelWidth:i.pixelwidth,viewPixelHeight:i.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(i.translation,i.quaternion),radius:i.radius,centralAngle:i.centralAngle,aspectRatio:i.aspectRatio,space:this._referenceSpace,viewPixelWidth:i.pixelwidth,viewPixelHeight:i.pixelheight,clearOnAccess:!1})}function Aw(i,e){if(e===void 0)return;const t=this._cameraXR,n=this._renderer,s=n.backend,r=this._glBaseLayer,o=this.getReferenceSpace(),a=e.getViewerPose(o);if(this._xrFrame=e,a!==null){const u=a.views;this._glBaseLayer!==null&&s.setXRTarget(r.framebuffer);let l=!1;u.length!==t.cameras.length&&(t.cameras.length=0,l=!0);for(let c=0;c<u.length;c++){const d=u[c];let h;if(this._supportsLayers===!0){const p=this._glBinding.getViewSubImage(this._glProjLayer,d);h=p.viewport,c===0&&s.setXRRenderTargetTextures(this._xrRenderTarget,p.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:p.depthStencilTexture)}else h=r.getViewport(d);let f=this._cameras[c];f===void 0&&(f=new Hr,f.layers.enable(c),f.viewport=new ze,this._cameras[c]=f),f.matrix.fromArray(d.transform.matrix),f.matrix.decompose(f.position,f.quaternion,f.scale),f.projectionMatrix.fromArray(d.projectionMatrix),f.projectionMatrixInverse.copy(f.projectionMatrix).invert(),f.viewport.set(h.x,h.y,h.width,h.height),c===0&&(t.matrix.copy(f.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),l===!0&&t.cameras.push(f)}n.setOutputRenderTarget(this._xrRenderTarget)}for(let u=0;u<this._controllers.length;u++){const l=this._controllerInputSources[u],c=this._controllers[u];l!==null&&c!==void 0&&c.update(l,e,o)}this._currentAnimationLoop&&this._currentAnimationLoop(i,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}class Cw extends Oo{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new ze(0,0,this._width,this._height),this._scissor=new ze(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Kh,this.depthTexture=new nn}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),n===!0&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,s){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,n,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,s,r=0,o=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,s),a.minDepth=r,a.maxDepth=o}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const ih=new Tl,Ls=new ce,eu=new ze,tu=new mm,nu=new gm,ki=new St,dn=new ze,Mw={[hs]:ot,[ot]:hs,[xn]:xn};class Bw{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,reversedDepthBuffer:s=!1,alpha:r=!0,depth:o=!0,stencil:a=!1,antialias:u=!1,samples:l=0,getFallback:c=null,outputBufferType:d=it,multiview:h=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=n,this.reversedDepthBuffer=s,this.outputColorSpace=xl,this.toneMapping=cs,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=o,this.stencil=a,this.info=new lN,this.contextNode=Rs(),this.library=new Gg,this.lighting=new xw,this._samples=l||u===!0?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new Cw(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Fp,this._inspector.setRenderer(this),this._getFallback=c,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const f=this.alpha===!0?0:1;this._clearColor=new nc(0,0,0,f),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=d,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:Vh},this.xr=new Tw(this,h),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(p,g,m)=>{await this.compileAsync(p,g);const y=this._renderLists.get(p,g),_=this._renderContexts.get(this._renderTarget,this._mrt),T=p.overrideMaterial||m.material,S=this._objects.get(m,T,p,g,y.lightsNode,_,_.clippingContext),{fragmentShader:N,vertexShader:R}=S.getNodeBuilderState();return{fragmentShader:N,vertexShader:R}}}}async init(){return this._initPromise!==null?this._initPromise:(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(s){if(this._getFallback!==null)try{this.backend=n=this._getFallback(s),await n.init(this)}catch(r){t(r);return}else{t(s);return}}this._nodes=new mw(this,n),this._animation=new eN(this,this._nodes,this.info),this._attributes=new aN(n,this.info),this._background=new MR(this,this._nodes),this._geometries=new uN(this._attributes,this.info),this._textures=new vN(this,n,this.info),this._pipelines=new fN(n,this._nodes,this.info),this._bindings=new pN(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new rN(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new yN(this.lighting),this._bundles=new bw,this._renderContexts=new xN(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)}),this._initPromise)}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();const s=this._nodes.nodeFrame,r=s.renderId,o=this._currentRenderContext,a=this._currentRenderObjectFunction,u=this._handleObjectFunction,l=this._compilationPromises;n===null&&(n=e);const c=e.isScene===!0?e:n.isScene===!0?n:ih,h=this.needsFrameBufferTarget&&this._renderTarget===null?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,f=this._renderContexts.get(h,this._mrt),p=this._activeMipmapLevel,g=[];this._currentRenderContext=f,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=g,s.renderId++,s.update(),f.depth=this.depth,f.stencil=this.stencil,f.clippingContext||(f.clippingContext=new Ao),f.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,h);const m=this._renderLists.get(c,t);if(m.begin(),this._projectObject(e,t,0,m,f.clippingContext),n!==e&&n.traverseVisible(function(N){N.isLight&&N.layers.test(t.layers)&&m.pushLight(N)}),m.finish(),h!==null){this._textures.updateRenderTarget(h,p);const N=this._textures.get(h);f.textures=N.textures,f.depthTexture=N.depthTexture}else f.textures=null,f.depthTexture=null;n!==e?this._background.update(n,m,f):this._background.update(c,m,f);const y=m.opaque,_=m.transparent,T=m.transparentDoublePass,S=m.lightsNode;this.opaque===!0&&y.length>0&&this._renderObjects(y,t,c,S),this.transparent===!0&&_.length>0&&this._renderTransparents(_,T,t,c,S),s.renderId=r,this._currentRenderContext=o,this._currentRenderObjectFunction=a,this._handleObjectFunction=u,this._compilationPromises=l;for(const N of g){const R=this._objects.get(N.object,N.material,N.scene,N.camera,N.lightsNode,N.renderContext,N.clippingContext,N.passId);R.drawRange=N.object.geometry.drawRange,R.group=N.group,this._geometries.updateForRender(R),await this._nodes.getForRenderAsync(R),this._nodes.updateBefore(R),this._nodes.updateForRender(R),this._bindings.updateForRender(R);const v=[];this._pipelines.getForRender(R,v),v.length>0&&await Promise.all(v),this._nodes.updateAfter(R),await $h()}}async renderAsync(e,t){Oe('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){k("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){this._inspector!==null&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;e===!0?(t.modelViewMatrix=id,t.modelNormalViewMatrix=od):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===id&&e.modelNormalViewMatrix===od}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Oe('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
|
|
547
|
-
|
|
548
|
-
Message: ${e.message}`;e.reason&&(t+=`
|
|
549
|
-
Reason: ${e.reason}`),k(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:s,camera:r,renderList:o}=e,a=this._currentRenderContext,u=this._bundles.get(s,r,a),l=this.backend.get(u),c=s.version!==l.version;if(c||l.bundleGPU===void 0){this.backend.beginBundle(a),(l.renderObjects===void 0||c)&&(l.renderObjects=[]),this._currentRenderBundle=u;const{transparentDoublePass:h,transparent:f,opaque:p}=o;this.opaque===!0&&p.length>0&&this._renderObjects(p,r,t,n),this.transparent===!0&&f.length>0&&this._renderTransparents(f,h,r,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,u),l.version=s.version}else{const{renderObjects:h}=l;for(let f=0,p=h.length;f<p;f++){const g=h[f];this._nodes.needsRefresh(g)&&(this._nodes.updateBefore(g),this._nodes.updateForRender(g),this._bindings.updateForRender(g),this._nodes.updateAfter(g))}}this.backend.addBundle(a,u)}render(e,t){if(this._initialized===!1)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,n=e!==cs,s=t!==Ge.workingColorSpace;if(n===!1&&s===!1)return null;const{width:r,height:o}=this.getDrawingBufferSize(Ls),{depth:a,stencil:u}=this,l=this._outputRenderTarget||this._canvasTarget;let c=this._frameBufferTargets.get(l);if(c===void 0){c=new Ss(r,o,{depthBuffer:a,stencilBuffer:u,type:this._outputBufferType,format:It,colorSpace:Ge.workingColorSpace,generateMipmaps:!1,minFilter:vt,magFilter:vt,samples:this.samples}),c.isPostProcessingRenderTarget=!0;const m=()=>{l.removeEventListener("dispose",m),c.dispose(),this._frameBufferTargets.delete(l)};l.addEventListener("dispose",m),this._frameBufferTargets.set(l,c)}const d=this.getOutputRenderTarget();c.depthBuffer=a,c.stencilBuffer=u,d!==null?c.setSize(d.width,d.height,d.depth):c.setSize(r,o,1);const h=this._outputRenderTarget?this._outputRenderTarget.viewport:l._viewport,f=this._outputRenderTarget?this._outputRenderTarget.scissor:l._scissor,p=this._outputRenderTarget?1:l._pixelRatio,g=this._outputRenderTarget?this._outputRenderTarget.scissorTest:l._scissorTest;return c.viewport.copy(h),c.scissor.copy(f),c.viewport.multiplyScalar(p),c.scissor.multiplyScalar(p),c.scissorTest=g,c.multiview=d!==null?d.multiview:!1,c.resolveDepthBuffer=d!==null?d.resolveDepthBuffer:!0,c._autoAllocateDepthBuffer=d!==null?d._autoAllocateDepthBuffer:!1,c}_renderScene(e,t,n=!0){if(this._isDeviceLost===!0)return;const s=n?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,o=r.renderId,a=this._currentRenderContext,u=this._currentRenderObjectFunction,l=this._handleObjectFunction;this._callDepth++;const c=e.isScene===!0?e:ih,d=this._renderTarget||this._outputRenderTarget,h=this._activeCubeFace,f=this._activeMipmapLevel;let p;if(s!==null?(p=s,this.setRenderTarget(p)):p=d,p!==null&&p.depthBuffer===!0){const se=this._textures.get(p);se.depthInitialized!==!0&&((this.autoClear===!1||this.autoClear===!0&&this.autoClearDepth===!1)&&this.clearDepth(),se.depthInitialized=!0)}const g=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,p);const m=this.xr;if(m.isPresenting===!1){let se=!1;if(this.reversedDepthBuffer===!0&&t.reversedDepth!==!0){if(t._reversedDepth=!0,t.isArrayCamera)for(const oe of t.cameras)oe._reversedDepth=!0;se=!0}const Z=this.coordinateSystem;if(t.coordinateSystem!==Z){if(t.coordinateSystem=Z,t.isArrayCamera)for(const oe of t.cameras)oe.coordinateSystem=Z;se=!0}if(se===!0&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const oe of t.cameras)oe.updateProjectionMatrix()}e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),m.enabled===!0&&m.isPresenting===!0&&(m.cameraAutoUpdate===!0&&m.updateCamera(t),t=m.getCamera());const y=this._canvasTarget;let _=y._viewport,T=y._scissor,S=y._pixelRatio;p!==null&&(_=p.viewport,T=p.scissor,S=1),this.getDrawingBufferSize(Ls),eu.set(0,0,Ls.width,Ls.height);const N=_.minDepth===void 0?0:_.minDepth,R=_.maxDepth===void 0?1:_.maxDepth;g.viewportValue.copy(_).multiplyScalar(S).floor(),g.viewportValue.width>>=f,g.viewportValue.height>>=f,g.viewportValue.minDepth=N,g.viewportValue.maxDepth=R,g.viewport=g.viewportValue.equals(eu)===!1,g.scissorValue.copy(T).multiplyScalar(S).floor(),g.scissor=y._scissorTest&&g.scissorValue.equals(eu)===!1,g.scissorValue.width>>=f,g.scissorValue.height>>=f,g.clippingContext||(g.clippingContext=new Ao),g.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,p);const v=t.isArrayCamera?nu:tu;t.isArrayCamera||(ki.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(ki,t.coordinateSystem,t.reversedDepth));const P=this._renderLists.get(e,t);if(P.begin(),this._projectObject(e,t,0,P,g.clippingContext),P.finish(),this.sortObjects===!0&&P.sort(this._opaqueSort,this._transparentSort),p!==null){this._textures.updateRenderTarget(p,f);const se=this._textures.get(p);g.textures=se.textures,g.depthTexture=se.depthTexture,g.width=se.width,g.height=se.height,g.renderTarget=p,g.depth=p.depthBuffer,g.stencil=p.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=Ls.width,g.height=Ls.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=f,g.height>>=f,g.activeCubeFace=h,g.activeMipmapLevel=f,g.occlusionQueryCount=P.occlusionQueryCount,g.scissorValue.max(dn.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(c,P,g),g.camera=t,this.backend.beginRender(g);const{bundles:D,lightsNode:L,transparentDoublePass:j,transparent:ee,opaque:re}=P;return D.length>0&&this._renderBundles(D,c,L),this.opaque===!0&&re.length>0&&this._renderObjects(re,t,c,L),this.transparent===!0&&ee.length>0&&this._renderTransparents(ee,j,t,c,L),this.backend.finishRender(g),r.renderId=o,this._currentRenderContext=a,this._currentRenderObjectFunction=u,this._handleObjectFunction=l,this._callDepth--,s!==null&&(this.setRenderTarget(d,h,f),this._renderOutput(p)),c.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let n=this._quadCache.get(e.texture),s;if(n===void 0){s=new Ag(new We),s.name="Output Color Transform",s.material.name="outputColorTransform",s.material.fragmentNode=this._nodes.getOutputNode(e.texture),n={quad:s,cacheKey:t},this._quadCache.set(e.texture,n);const a=()=>{s.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",a)};e.texture.addEventListener("dispose",a)}else s=n.quad,n.cacheKey!==t&&(s.material.fragmentNode=this._nodes.getOutputNode(e.texture),s.material.needsUpdate=!0,n.cacheKey=t);const r=this.autoClear,o=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(s,s.camera,!1),this.autoClear=r,this.xr.enabled=o}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,n=0,s=-1){if(t!==null&&t.isReadbackBuffer&&this.info.memoryMap.has(t)===!1){this.info.createReadbackBuffer(t);const r=()=>{t.removeEventListener("dispose",r),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",r)}if(n%4!==0||s>0&&s%4!==0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,n,s)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,s){this._canvasTarget.setScissor(e,t,n,s)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,s,r=0,o=1){this._canvasTarget.setViewport(e,t,n,s,r,o)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this.reversedDepthBuffer===!0?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(this._initialized===!1)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const s=this._renderTarget||this._getFrameBufferTarget();let r=null;if(s!==null){this._textures.updateRenderTarget(s);const o=this._textures.get(s);r=this._renderContexts.get(s,null,-1),r.textures=o.textures,r.depthTexture=o.depthTexture,r.width=o.width,r.height=o.height,r.renderTarget=s,r.depth=s.depthBuffer,r.stencil=s.stencilBuffer;const a=this.backend.getClearColor();r.clearColorValue.r=a.r,r.clearColorValue.g=a.g,r.clearColorValue.b=a.b,r.clearColorValue.a=a.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel(),s.depthBuffer===!0&&(o.depthInitialized=!0)}this.backend.clear(e,t,n,r),s!==null&&this._renderTarget===null&&this._renderOutput(s)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Oe('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,n)}async clearColorAsync(){Oe('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Oe('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Oe('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==cs,t=this.currentColorSpace!==Ge.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return this._renderTarget!==null?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:cs}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Ge.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){if(this._initialized===!0){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{e!==null&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return z("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const n=this._nodes.nodeFrame,s=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,o=this._pipelines,a=this._bindings,u=this._nodes,l=Array.isArray(e)?e:[e];if(l[0]===void 0||l[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const c of l){if(o.has(c)===!1){const f=()=>{c.removeEventListener("dispose",f),o.delete(c),a.deleteForCompute(c),u.delete(c)};c.addEventListener("dispose",f);const p=c.onInitFunction;p!==null&&p.call(c,{renderer:this})}u.updateForCompute(c),a.updateForCompute(c);const d=a.getForCompute(c),h=o.getForCompute(c,d);r.compute(e,c,d,h,t)}r.finishCompute(e),n.renderId=s,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){this._initialized===!1&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Oe('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(this._initialized===!1)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Oe('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(this._initialized===!1)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(this._initialized===!1)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=dn.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=dn.copy(t).floor();else{k("Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=dn.set(0,0,e.image.width,e.image.height);let n=this._currentRenderContext,s;n!==null?s=n.renderTarget:(s=this._renderTarget||this._getFrameBufferTarget(),s!==null&&(this._textures.updateRenderTarget(s),n=this._textures.get(s))),this._textures.updateTexture(e,{renderTarget:s}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,s=null,r=0,o=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,s,r,o),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,s,r,o=0,a=0){return this.backend.copyTextureToBuffer(e.textures[o],t,n,s,r,a)}_projectObject(e,t,n,s,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)s.pushLight(e);else if(e.isSprite){const u=t.isArrayCamera?nu:tu;if(!e.frustumCulled||u.intersectsSprite(e,t)){this.sortObjects===!0&&dn.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ki);const{geometry:l,material:c}=e;c.visible&&s.push(e,l,c,n,dn.z,null,r)}}else if(e.isLineLoop)k("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const u=t.isArrayCamera?nu:tu;if(!e.frustumCulled||u.intersectsObject(e,t)){const{geometry:l,material:c}=e;if(this.sortObjects===!0&&(l.boundingSphere===null&&l.computeBoundingSphere(),dn.copy(l.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(ki)),Array.isArray(c)){const d=l.groups;for(let h=0,f=d.length;h<f;h++){const p=d[h],g=c[p.materialIndex];g&&g.visible&&s.push(e,l,g,n,dn.z,p,r)}}else c.visible&&s.push(e,l,c,n,dn.z,null,r)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){const u=s;s=this._renderLists.get(e,t),s.begin(),u.pushBundle({bundleGroup:e,camera:t,renderList:s}),s.finish()}const a=e.children;for(let u=0,l=a.length;u<l;u++)this._projectObject(a[u],t,n,s,r)}_renderBundles(e,t,n){for(const s of e)this._renderBundle(s,t,n)}_renderTransparents(e,t,n,s,r){if(t.length>0){for(const{material:o}of t)o.side=ot;this._renderObjects(t,n,s,r,"backSide");for(const{material:o}of t)o.side=hs;this._renderObjects(e,n,s,r);for(const{material:o}of t)o.side=xn}else this._renderObjects(e,n,s,r)}_renderObjects(e,t,n,s,r=null){for(let o=0,a=e.length;o<a;o++){const{object:u,geometry:l,material:c,group:d,clippingContext:h}=e[o];this._currentRenderObjectFunction(u,n,t,l,c,d,s,h,r)}}_getShadowNodes(e){const t=e.version;let n=this._cacheShadowNodes.get(e);if(n===void 0||n.version!==t){const s=e.map!==null,r=e.colorNode&&e.colorNode.isNode,o=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let u=null,l=null,c=null;if(s||r||o||a){let d,h;if(o?(d=e.castShadowNode.rgb,h=e.castShadowNode.a,this.shadowMap.transmitted!==!0&&Oe("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(d=A(0),h=w(1)),s&&(h=h.mul(Pe("map","texture",e).a)),r&&(h=h.mul(e.colorNode.a)),l=ie(d,h),a){const f=e.maskShadowNode||e.maskNode;l=M(([p])=>(f.not().discard(),p))(l)}}e.depthNode&&e.depthNode.isNode&&(c=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?u=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(u=e.positionNode),n={version:t,colorNode:l,depthNode:c,positionNode:u},this._cacheShadowNodes.set(e,n)}return n}renderObject(e,t,n,s,r,o,a,u=null,l=null){let c=!1,d,h,f,p;if(e.onBeforeRender(this,t,n,s,r,o),r.allowOverride===!0&&t.overrideMaterial!==null){const g=t.overrideMaterial;if(c=!0,d=g.isNodeMaterial?g.colorNode:null,h=g.isNodeMaterial?g.depthNode:null,f=g.isNodeMaterial?g.positionNode:null,p=t.overrideMaterial.side,r.positionNode&&r.positionNode.isNode&&(g.positionNode=r.positionNode),g.alphaTest=r.alphaTest,g.alphaMap=r.alphaMap,g.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,g.isShadowPassMaterial){const{colorNode:m,depthNode:y,positionNode:_}=this._getShadowNodes(r);this.shadowMap.type===Or?g.side=r.shadowSide!==null?r.shadowSide:r.side:g.side=r.shadowSide!==null?r.shadowSide:Mw[r.side],m!==null&&(g.colorNode=m),y!==null&&(g.depthNode=y),_!==null&&(g.positionNode=_)}r=g}r.transparent===!0&&r.side===xn&&r.forceSinglePass===!1?(r.side=ot,this._handleObjectFunction(e,r,t,n,a,o,u,"backSide"),r.side=hs,this._handleObjectFunction(e,r,t,n,a,o,u,l),r.side=xn):this._handleObjectFunction(e,r,t,n,a,o,u,l),c&&(t.overrideMaterial.colorNode=d,t.overrideMaterial.depthNode=h,t.overrideMaterial.positionNode=f,t.overrideMaterial.side=p),e.onAfterRender(this,t,n,s,r,o)}hasCompatibility(e){if(this._initialized===!1)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,s,r,o,a,u){const l=this._objects.get(e,t,n,s,r,this._currentRenderContext,a,u);l.drawRange=e.geometry.drawRange,l.group=o,this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup);const c=this._nodes.needsRefresh(l);c&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),this._pipelines.isReady(l)&&(this.backend.draw(l,this.info),c&&this._nodes.updateAfter(l))}_createObjectPipeline(e,t,n,s,r,o,a,u){if(this._compilationPromises!==null){this._compilationPromises.push({object:e,material:t,scene:n,camera:s,lightsNode:r,group:o,clippingContext:a,passId:u,renderContext:this._currentRenderContext});return}const l=this._objects.get(e,t,n,s,r,this._currentRenderContext,a,u);l.drawRange=e.geometry.drawRange,l.group=o,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class Vg{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}function Pw(i){return i+(kn-i%kn)%kn}class $g extends Vg{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return Pw(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}}class zg extends $g{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let Fw=0;class Wg extends zg{constructor(e,t){super("UniformBuffer_"+Fw++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class Dw extends zg{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(this._updateRangeCache.has(t)!==!0){const n=this.updateRanges,s=e.offset,r=e.itemSize,o={start:s,count:r};n.push(o),this._updateRangeCache.set(t,o)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let n=0,s=this.uniforms.length;n<s;n++){const r=this.uniforms[n],o=r.boundary,a=r.itemSize*e,u=t%kn,l=u%o,c=u+l;t+=l,c!==0&&kn-c<a&&(t+=kn-c),r.offset=t/e,r.index=n,t+=a}return Math.ceil(t/kn)*kn}update(){let e=!1;for(const t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}updateByType(e){if(e.isNumberUniform)return this.updateNumber(e);if(e.isVector2Uniform)return this.updateVector2(e);if(e.isVector3Uniform)return this.updateVector3(e);if(e.isVector4Uniform)return this.updateVector4(e);if(e.isColorUniform)return this.updateColor(e);if(e.isMatrix3Uniform)return this.updateMatrix3(e);if(e.isMatrix4Uniform)return this.updateMatrix4(e);k("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,s=e.getValue(),r=e.offset,o=e.getType();if(n[r]!==s){const a=this._getBufferForType(o);a[r]=n[r]=s,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const n=this.values,s=e.getValue(),r=e.offset,o=e.getType();if(n[r+0]!==s.x||n[r+1]!==s.y){const a=this._getBufferForType(o);a[r+0]=n[r+0]=s.x,a[r+1]=n[r+1]=s.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const n=this.values,s=e.getValue(),r=e.offset,o=e.getType();if(n[r+0]!==s.x||n[r+1]!==s.y||n[r+2]!==s.z){const a=this._getBufferForType(o);a[r+0]=n[r+0]=s.x,a[r+1]=n[r+1]=s.y,a[r+2]=n[r+2]=s.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const n=this.values,s=e.getValue(),r=e.offset,o=e.getType();if(n[r+0]!==s.x||n[r+1]!==s.y||n[r+2]!==s.z||n[r+3]!==s.w){const a=this._getBufferForType(o);a[r+0]=n[r+0]=s.x,a[r+1]=n[r+1]=s.y,a[r+2]=n[r+2]=s.z,a[r+3]=n[r+3]=s.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const n=this.values,s=e.getValue(),r=e.offset;if(n[r+0]!==s.r||n[r+1]!==s.g||n[r+2]!==s.b){const o=this.buffer;o[r+0]=n[r+0]=s.r,o[r+1]=n[r+1]=s.g,o[r+2]=n[r+2]=s.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const n=this.values,s=e.getValue().elements,r=e.offset;if(n[r+0]!==s[0]||n[r+1]!==s[1]||n[r+2]!==s[2]||n[r+4]!==s[3]||n[r+5]!==s[4]||n[r+6]!==s[5]||n[r+8]!==s[6]||n[r+9]!==s[7]||n[r+10]!==s[8]){const o=this.buffer;o[r+0]=n[r+0]=s[0],o[r+1]=n[r+1]=s[1],o[r+2]=n[r+2]=s[2],o[r+4]=n[r+4]=s[3],o[r+5]=n[r+5]=s[4],o[r+6]=n[r+6]=s[5],o[r+8]=n[r+8]=s[6],o[r+9]=n[r+9]=s[7],o[r+10]=n[r+10]=s[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const n=this.values,s=e.getValue().elements,r=e.offset;return Uw(n,s,r)===!1&&(this.buffer.set(s,r),Lw(n,s,r),t=!0,this.addUniformUpdateRange(e)),t}_getBufferForType(e){return e==="int"||e==="ivec2"||e==="ivec3"||e==="ivec4"?new Int32Array(this.buffer.buffer):e==="uint"||e==="uvec2"||e==="uvec3"||e==="uvec4"?new Uint32Array(this.buffer.buffer):this.buffer}}function Lw(i,e,t){for(let n=0,s=e.length;n<s;n++)i[t+n]=e[n]}function Uw(i,e,t){for(let n=0,s=e.length;n<s;n++)if(i[t+n]!==e[n])return!1;return!0}let Ow=0;class jg extends Dw{constructor(e,t){super(e),this.id=Ow++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class qg extends Vg{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let Iw=0;class kw extends qg{constructor(e,t){super(e,t),this.id=Iw++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class ta extends kw{constructor(e,t,n,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class Hg extends ta{constructor(e,t,n,s=null){super(e,t,n,s),this.isSampledCubeTexture=!0}}class dl extends ta{constructor(e,t,n,s=null){super(e,t,n,s),this.isSampledTexture3D=!0}}const oh={bitcast_int_uint:new Ke("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new Ke("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},Gw={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},ah={low:"lowp",medium:"mediump",high:"highp"},uh={swizzleAssign:!0,storageBuffer:!1},lh={perspective:"smooth",linear:"noperspective"},ch={centroid:"centroid"},dh=`
|
|
550
|
-
precision highp float;
|
|
551
|
-
precision highp int;
|
|
552
|
-
precision highp sampler2D;
|
|
553
|
-
precision highp sampler3D;
|
|
554
|
-
precision highp samplerCube;
|
|
555
|
-
precision highp sampler2DArray;
|
|
556
|
-
|
|
557
|
-
precision highp usampler2D;
|
|
558
|
-
precision highp usampler3D;
|
|
559
|
-
precision highp usamplerCube;
|
|
560
|
-
precision highp usampler2DArray;
|
|
561
|
-
|
|
562
|
-
precision highp isampler2D;
|
|
563
|
-
precision highp isampler3D;
|
|
564
|
-
precision highp isamplerCube;
|
|
565
|
-
precision highp isampler2DArray;
|
|
566
|
-
|
|
567
|
-
precision highp sampler2DShadow;
|
|
568
|
-
precision highp sampler2DArrayShadow;
|
|
569
|
-
precision highp samplerCubeShadow;
|
|
570
|
-
`;class Vw extends Ig{constructor(e,t){super(e,t,new gw),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==tr}_include(e){const t=oh[e];return t.build(this),this.addInclude(t),t}getMethod(e){return oh[e]!==void 0&&this._include(e),Gw[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),s=[];for(const o of t.inputs)s.push(this.getType(o.type)+" "+o.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {
|
|
571
|
-
|
|
572
|
-
${n.vars}
|
|
573
|
-
|
|
574
|
-
${n.code}
|
|
575
|
-
return ${n.result};
|
|
576
|
-
|
|
577
|
-
}`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const n=t.array,s=t.count*t.itemSize,{itemSize:r}=t,o=t.array.constructor.name.toLowerCase().includes("int");let a=o?Do:Fo;r===2?a=o?Lo:Jt:r===3?a=o?qh:Uo:r===4&&(a=o?Cl:It);const u={Float32Array:rt,Uint8Array:ht,Uint16Array:ds,Uint32Array:Ve,Int8Array:Ws,Int16Array:js,Int32Array:st,Uint8ClampedArray:ht},l=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/r))));let c=Math.ceil(s/r/l);l*c*r<s&&c++;const d=l*c*r,h=new n.constructor(d);h.set(n,0),t.array=h;const f=new Sf(t.array,l,c,a,u[t.array.constructor.name]||rt);f.needsUpdate=!0,f.isPBOTexture=!0;const p=new ui(f,null,null);p.setPrecision("high"),t.pboNode=p,t.pbo=p.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&e.node.isTextureNode!==!0&&e.node.isBufferNode!==!0?e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:n}=e,s=t.value;if(this.renderer.backend.has(s)){const c=this.renderer.backend.get(s);c.pbo=s.pbo}const r=this.getUniformFromNode(s.pboNode,"texture",this.shaderStage,this.context.nodeName),o=this.getPropertyName(r);this.increaseUsage(n);const a=n.build(this,"uint"),u=this.getDataFromNode(e);let l=u.propertyName;if(l===void 0){const c=this.getVarFromNode(e);l=this.getPropertyName(c);const d=this.getDataFromNode(t);let h=d.propertySizeName;h===void 0&&(h=l+"Size",this.getVarFromNode(t,h,"uint"),this.addLineFlowCode(`${h} = uint( textureSize( ${o}, 0 ).x )`,e),d.propertySizeName=h);const{itemSize:f}=s,p="."+lr.join("").slice(0,f),g=`ivec2(${a} % ${h}, ${a} / ${h})`,m=this.generateTextureLoad(null,o,g,"0",null,null);let y="vec4";s.pbo.type===Ve?y="uvec4":s.pbo.type===st&&(y="ivec4"),this.addLineFlowCode(`${l} = ${y}(${m})${p}`,e),u.propertyName=l}return l}generateTextureLoad(e,t,n,s,r,o){s===null&&(s="0");let a;return r?o?a=`texelFetchOffset( ${t}, ivec3( ${n}, ${r} ), int( ${s} ), ${o} )`:a=`texelFetch( ${t}, ivec3( ${n}, ${r} ), int( ${s} ) )`:o?a=`texelFetchOffset( ${t}, ${n}, int( ${s} ), ${o} )`:a=`texelFetch( ${t}, ${n}, int( ${s} ) )`,e!==null&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,n,s,r){return s&&(n=`vec3( ${n}, ${s} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${n}, ${r} ).x`:`texture( ${t}, ${n} ).x`:r?`textureOffset( ${t}, ${n}, ${r} )`:`texture( ${t}, ${n} )`}generateTextureLevel(e,t,n,s,r,o){return r&&(n=`vec3( ${n}, ${r} )`),o?`textureLodOffset( ${t}, ${n}, ${s}, ${o} )`:`textureLod( ${t}, ${n}, ${s} )`}generateTextureBias(e,t,n,s,r,o){return r&&(n=`vec3( ${n}, ${r} )`),o?`textureOffset( ${t}, ${n}, ${o}, ${s} )`:`texture( ${t}, ${n}, ${s} )`}generateTextureGrad(e,t,n,s,r,o){return r&&(n=`vec3( ${n}, ${r} )`),o?`textureGradOffset( ${t}, ${n}, ${s[0]}, ${s[1]}, ${o} )`:`textureGrad( ${t}, ${n}, ${s[0]}, ${s[1]} )`}generateTextureCompare(e,t,n,s,r,o,a=this.shaderStage){if(a==="fragment")return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${s} ) )`:r?o?`textureOffset( ${t}, vec4( ${n}, ${r}, ${s} ), ${o} )`:`texture( ${t}, vec4( ${n}, ${r}, ${s} ) )`:o?`textureOffset( ${t}, vec3( ${n}, ${s} ), ${o} )`:`texture( ${t}, vec3( ${n}, ${s} ) )`;k(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}getUniforms(e){const t=this.uniforms[e],n=[],s={};for(const o of t){let a=null,u=!1;if(o.type==="texture"||o.type==="texture3D"){const l=o.node.value;let c="";(l.isDataTexture===!0||l.isData3DTexture===!0)&&(l.type===Ve?c="u":l.type===st&&(c="i")),o.type==="texture3D"&&l.isArrayTexture===!1?a=`${c}sampler3D ${o.name};`:l.compareFunction?l.isArrayTexture===!0?a=`sampler2DArrayShadow ${o.name};`:a=`sampler2DShadow ${o.name};`:l.isArrayTexture===!0||l.isDataArrayTexture===!0||l.isCompressedArrayTexture===!0?a=`${c}sampler2DArray ${o.name};`:a=`${c}sampler2D ${o.name};`}else if(o.type==="cubeTexture")a=`samplerCube ${o.name};`;else if(o.type==="cubeDepthTexture")o.node.value.compareFunction?a=`samplerCubeShadow ${o.name};`:a=`samplerCube ${o.name};`;else if(o.type==="buffer"){const l=o.node,c=this.getType(l.bufferType),d=l.bufferCount,h=d>0?d:"";a=`${l.name} {
|
|
578
|
-
${c} ${o.name}[${h}];
|
|
579
|
-
};
|
|
580
|
-
`}else{const l=o.groupNode.name;if(s[l]===void 0){const c=this.uniformGroups[l];if(c!==void 0){const d=[];for(const h of c.uniforms){const f=h.getType(),p=this.getVectorType(f),g=h.nodeUniform.node.precision;let m=`${p} ${h.name};`;g!==null&&(m=ah[g]+" "+m),d.push(" "+m)}s[l]=d}}u=!0}if(!u){const l=o.node.precision;l!==null&&(a=ah[l]+" "+a),a="uniform "+a,n.push(a)}}let r="";for(const o in s){const a=s[o];r+=this._getGLSLUniformStruct(o,a.join(`
|
|
581
|
-
`))+`
|
|
582
|
-
`}return r+=n.join(`
|
|
583
|
-
`),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==st){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const s=n.array;s instanceof Uint32Array||s instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t="";if(e==="vertex"||e==="compute"){const n=this.getAttributesArray();let s=0;for(const r of n)t+=`layout( location = ${s++} ) in ${r.type} ${r.name};
|
|
584
|
-
`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(` ${n.type} ${n.name};`);return t.join(`
|
|
585
|
-
`)}getStructs(e){const t=[],n=this.structs[e],s=[];for(const r of n)if(r.output)for(const o of r.members)s.push(`layout( location = ${o.index} ) out ${o.type} ${o.name};`);else{let o="struct "+r.name+` {
|
|
586
|
-
`;o+=this.getStructMembers(r),o+=`
|
|
587
|
-
};
|
|
588
|
-
`,t.push(o)}return s.length===0&&s.push("layout( location = 0 ) out vec4 fragColor;"),`
|
|
589
|
-
`+s.join(`
|
|
590
|
-
`)+`
|
|
591
|
-
|
|
592
|
-
`+t.join(`
|
|
593
|
-
`)}getVaryings(e){let t="";const n=this.varyings;if(e==="vertex"||e==="compute")for(const s of n){e==="compute"&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){const o=lh[s.interpolationType]||s.interpolationType,a=ch[s.interpolationSampling]||"";t+=`${o} ${a} out ${r} ${s.name};
|
|
594
|
-
`}else{const o=r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":"";t+=`${o}out ${r} ${s.name};
|
|
595
|
-
`}else t+=`${r} ${s.name};
|
|
596
|
-
`}else if(e==="fragment"){for(const s of n)if(s.needsInterpolation){const r=this.getType(s.type);if(s.interpolationType){const o=lh[s.interpolationType]||s.interpolationType,a=ch[s.interpolationSampling]||"";t+=`${o} ${a} in ${r} ${s.name};
|
|
597
|
-
`}else{const o=r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":"";t+=`${o}in ${r} ${s.name};
|
|
598
|
-
`}}}for(const s of this.builtins[e])t+=`${s};
|
|
599
|
-
`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((n,s)=>n*s,1)}u`}getSubgroupSize(){k("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){k("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){k("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const s=this.extensions[n]||(this.extensions[n]=new Map);s.has(e)===!1&&s.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if(e==="vertex"){const s=this.renderer.backend.extensions;this.object.isBatchedMesh&&s.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(n!==void 0)for(const{name:s,behavior:r}of n.values())t.push(`#extension ${s} : ${r}`);return t.join(`
|
|
600
|
-
`)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=uh[e];if(t===void 0){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance";break}if(n!==void 0){const s=this.renderer.backend.extensions;s.has(n)&&(s.get(n),t=!0)}uh[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let n=0;n<e.length;n++){const s=e[n],r=this.getPropertyName(s.attributeNode);r&&(t+=`${s.varyingName} = ${r};
|
|
601
|
-
`)}return t}_getGLSLUniformStruct(e,t){return`
|
|
602
|
-
layout( std140 ) uniform ${e} {
|
|
603
|
-
${t}
|
|
604
|
-
};`}_getGLSLVertexCode(e){return`#version 300 es
|
|
605
|
-
|
|
606
|
-
${this.getSignature()}
|
|
607
|
-
|
|
608
|
-
// extensions
|
|
609
|
-
${e.extensions}
|
|
610
|
-
|
|
611
|
-
// precision
|
|
612
|
-
${dh}
|
|
613
|
-
|
|
614
|
-
// uniforms
|
|
615
|
-
${e.uniforms}
|
|
616
|
-
|
|
617
|
-
// varyings
|
|
618
|
-
${e.varyings}
|
|
619
|
-
|
|
620
|
-
// attributes
|
|
621
|
-
${e.attributes}
|
|
622
|
-
|
|
623
|
-
// vars
|
|
624
|
-
${e.vars}
|
|
625
|
-
|
|
626
|
-
// codes
|
|
627
|
-
${e.codes}
|
|
628
|
-
|
|
629
|
-
void main() {
|
|
630
|
-
|
|
631
|
-
// transforms
|
|
632
|
-
${e.transforms}
|
|
633
|
-
|
|
634
|
-
// flow
|
|
635
|
-
${e.flow}
|
|
636
|
-
|
|
637
|
-
gl_PointSize = 1.0;
|
|
638
|
-
|
|
639
|
-
}
|
|
640
|
-
`}_getGLSLFragmentCode(e){return`#version 300 es
|
|
641
|
-
|
|
642
|
-
${this.getSignature()}
|
|
643
|
-
|
|
644
|
-
// extensions
|
|
645
|
-
${e.extensions}
|
|
646
|
-
|
|
647
|
-
// precision
|
|
648
|
-
${dh}
|
|
649
|
-
|
|
650
|
-
// structs
|
|
651
|
-
${e.structs}
|
|
652
|
-
|
|
653
|
-
// uniforms
|
|
654
|
-
${e.uniforms}
|
|
655
|
-
|
|
656
|
-
// varyings
|
|
657
|
-
${e.varyings}
|
|
658
|
-
|
|
659
|
-
// vars
|
|
660
|
-
${e.vars}
|
|
661
|
-
|
|
662
|
-
// codes
|
|
663
|
-
${e.codes}
|
|
664
|
-
|
|
665
|
-
void main() {
|
|
666
|
-
|
|
667
|
-
// flow
|
|
668
|
-
${e.flow}
|
|
669
|
-
|
|
670
|
-
}
|
|
671
|
-
`}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n=`// code
|
|
672
|
-
|
|
673
|
-
`;n+=this.flowCode[t];const s=this.flowNodes[t],r=s[s.length-1];for(const a of s){const u=this.getFlowData(a),l=a.name;l&&(n.length>0&&(n+=`
|
|
674
|
-
`),n+=` // flow -> ${l}
|
|
675
|
-
`),n+=`${u.code}
|
|
676
|
-
`,a===r&&t!=="compute"&&(n+=`// result
|
|
677
|
-
`,t==="vertex"?(n+="gl_Position = ",n+=`${u.result};`):t==="fragment"&&(a.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${u.result};`)))}const o=e[t];if(o.extensions=this.getExtensions(t),o.uniforms=this.getUniforms(t),o.attributes=this.getAttributes(t),o.varyings=this.getVaryings(t),o.vars=this.getVars(t,!0),o.structs=this.getStructs(t),o.codes=this.getCodes(t),o.transforms=this.getTransforms(t),o.flow=n,t==="vertex"){const a=this.renderer.backend.extensions;this.object.isBatchedMesh&&a.has("WEBGL_multi_draw")===!1&&(o.uniforms+=`
|
|
678
|
-
uniform uint nodeUniformDrawId;
|
|
679
|
-
`)}}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,s=null){const r=super.getUniformFromNode(e,t,n,s),o=this.getDataFromNode(e,n,this.globalCache);let a=o.uniformGPU;if(a===void 0){const u=e.groupNode,l=u.name,c=this.getBindGroupArray(l,n);if(t==="texture")a=new ta(r.name,r.node,u),c.push(a);else if(t==="cubeTexture"||t==="cubeDepthTexture")a=new Hg(r.name,r.node,u),c.push(a);else if(t==="texture3D")a=new dl(r.name,r.node,u),c.push(a);else if(t==="buffer"){r.name=`buffer${e.id}`;const d=this.getSharedDataFromNode(e);let h=d.buffer;h===void 0&&(e.name=`NodeBuffer_${e.id}`,h=new Wg(e,u),h.name=e.name,d.buffer=h),c.push(h),a=h}else{let d=this.uniformGroups[l];d===void 0?(d=new jg(l,u),this.uniformGroups[l]=d,c.push(d)):c.indexOf(d)===-1&&c.push(d),a=this.getNodeUniform(r,t);const h=a.name;d.uniforms.some(p=>p.name===h)||d.addUniform(a)}o.uniformGPU=a}return r}}let su=null,Us=null;class Xg{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Zt.RENDER]:null,[Zt.COMPUTE]:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),n=this.renderer.info.frame;let s;e.isComputeNode===!0?s="c:"+this.renderer.info.compute.frameCalls:s="r:"+this.renderer.info.render.frameCalls,t.timestampUID=s+":"+e.id+":f"+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Zt.COMPUTE:Zt.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp){Oe("WebGPURenderer: Timestamp tracking is disabled.");return}const t=this.timestampQueryPool[e];if(!t)return;const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return su=su||new ce,this.renderer.getDrawingBufferSize(su)}setScissorTest(){}getClearColor(){const e=this.renderer;return Us=Us||new nc,e.getClearColor(Us),Us.getRGB(Us),Us}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:Mm(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Io} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let $w=0;class zw{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}}class Ww{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:s}=n,r=e.array,o=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,u=n.get(a);let l=u.bufferGPU;l===void 0&&(l=this._createBuffer(s,t,r,o),u.bufferGPU=l,u.bufferType=t,u.version=a.version);let c;if(r instanceof Float32Array)c=s.FLOAT;else if(typeof Float16Array<"u"&&r instanceof Float16Array)c=s.HALF_FLOAT;else if(r instanceof Uint16Array)e.isFloat16BufferAttribute?c=s.HALF_FLOAT:c=s.UNSIGNED_SHORT;else if(r instanceof Int16Array)c=s.SHORT;else if(r instanceof Uint32Array)c=s.UNSIGNED_INT;else if(r instanceof Int32Array)c=s.INT;else if(r instanceof Int8Array)c=s.BYTE;else if(r instanceof Uint8Array)c=s.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)c=s.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);let d={bufferGPU:l,bufferType:t,type:c,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:c===s.INT||c===s.UNSIGNED_INT||e.gpuType===st,id:$w++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const h=this._createBuffer(s,t,r,o);d=new zw(d,h)}n.set(e,d)}updateAttribute(e){const t=this.backend,{gl:n}=t,s=e.array,r=e.isInterleavedBufferAttribute?e.data:e,o=t.get(r),a=o.bufferType,u=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,o.bufferGPU),u.length===0)n.bufferSubData(a,0,s);else{for(let l=0,c=u.length;l<c;l++){const d=u[l];n.bufferSubData(a,d.start*s.BYTES_PER_ELEMENT,s,d.start,d.count)}r.clearUpdateRanges()}n.bindBuffer(a,null),o.version=r.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const s=t.get(e);n.deleteBuffer(s.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,s=-1){const r=this.backend,{gl:o}=r,a=e.isInterleavedBufferAttribute?e.data:e,u=r.get(a),{bufferGPU:l}=u,c=s===-1?u.byteLength-n:s;let d;if(t===null)d=new Uint8Array(new ArrayBuffer(c));else if(t.isReadbackBuffer){if(t._mapped===!0)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");const h=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",h),t.removeEventListener("dispose",h)};t.addEventListener("release",h),t.addEventListener("dispose",h),d=new Uint8Array(new ArrayBuffer(c)),t.buffer=d.buffer}else d=new Uint8Array(t);return o.bindBuffer(o.COPY_READ_BUFFER,l),o.getBufferSubData(o.COPY_READ_BUFFER,n,d),o.bindBuffer(o.COPY_READ_BUFFER,null),o.bindBuffer(o.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:d.buffer}_createBuffer(e,t,n,s){const r=e.createBuffer();return e.bindBuffer(t,r),e.bufferData(t,n,s),e.bindBuffer(t,null),r}}let Pr,hn;class jw{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;Pr={[pn]:e.FUNC_ADD,[nf]:e.FUNC_SUBTRACT,[tf]:e.FUNC_REVERSE_SUBTRACT},hn={[Un]:e.ZERO,[ff]:e.ONE,[hf]:e.SRC_COLOR,[df]:e.SRC_ALPHA,[cf]:e.SRC_ALPHA_SATURATE,[lf]:e.DST_COLOR,[uf]:e.DST_ALPHA,[af]:e.ONE_MINUS_SRC_COLOR,[of]:e.ONE_MINUS_SRC_ALPHA,[rf]:e.ONE_MINUS_DST_COLOR,[sf]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=new ze().fromArray(t),this.currentViewport=new ze().fromArray(n),this._tempVec4=new ze}enable(e){const{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;e!==Pm?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===Fm?t.cullFace(t.BACK):e===Dm?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){const s=this.gl,r=this.backend.drawBuffersIndexedExt;if(!r){Oe("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.");return}for(let o=0;o<e.length;o++){const a=e[o];let u=null;if(t!==null){const l=t.getBlendMode(a.name);l.blending===pf?u=n:l.blending!==Nn&&(u=l)}else u=n;u!==null?this._setMRTBlendingIndex(o,u):r.blendFuncSeparateiOES(o,s.ONE,s.ZERO,s.ONE,s.ZERO)}}_setMRTBlendingIndex(e,t){const{gl:n}=this,s=this.backend.drawBuffersIndexedExt,r=t.blending,o=t.blendSrc,a=t.blendDst,u=t.blendEquation,l=t.premultipliedAlpha;if(r===qs){const c=t.blendSrcAlpha!==null?t.blendSrcAlpha:o,d=t.blendDstAlpha!==null?t.blendDstAlpha:a,h=t.blendEquationAlpha!==null?t.blendEquationAlpha:u;s.blendEquationSeparateiOES(e,Pr[u],Pr[h]),s.blendFuncSeparateiOES(e,hn[o],hn[a],hn[c],hn[d])}else if(s.blendEquationSeparateiOES(e,n.FUNC_ADD,n.FUNC_ADD),l)switch(r){case gn:s.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case Vs:s.blendFuncSeparateiOES(e,n.ONE,n.ONE,n.ONE,n.ONE);break;case Gs:s.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case ks:s.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:s.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}else switch(r){case gn:s.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case Vs:s.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case Gs:s.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case ks:s.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:s.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}}setBlending(e,t,n,s,r,o,a,u){const{gl:l}=this;if(e===Nn){this.currentBlendingEnabled===!0&&(this.disable(l.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),e!==qs){if(e!==this.currentBlending||u!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==pn||this.currentBlendEquationAlpha!==pn)&&(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=pn,this.currentBlendEquationAlpha=pn),u)switch(e){case gn:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case Vs:l.blendFunc(l.ONE,l.ONE);break;case Gs:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case ks:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:k("WebGLState: Invalid blending: ",e);break}else switch(e){case gn:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case Vs:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case Gs:k("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case ks:k("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:k("WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=u}return}r=r||t,o=o||n,a=a||s,(t!==this.currentBlendEquation||r!==this.currentBlendEquationAlpha)&&(l.blendEquationSeparate(Pr[t],Pr[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),(n!==this.currentBlendSrc||s!==this.currentBlendDst||o!==this.currentBlendSrcAlpha||a!==this.currentBlendDstAlpha)&&(l.blendFuncSeparate(hn[n],hn[s],hn[o],hn[a]),this.currentBlendSrc=n,this.currentBlendDst=s,this.currentBlendSrcAlpha=o,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=Nf[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case vf:t.depthFunc(t.NEVER);break;case Tf:t.depthFunc(t.ALWAYS);break;case xf:t.depthFunc(t.LESS);break;case _f:t.depthFunc(t.LEQUAL);break;case bf:t.depthFunc(t.EQUAL);break;case yf:t.depthFunc(t.GEQUAL);break;case mf:t.depthFunc(t.GREATER);break;case gf:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,s){const r=this._tempVec4.set(e,t,n,s);if(this.currentScissor.equals(r)===!1){const{gl:o}=this;o.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,n,s){const r=this._tempVec4.set(e,t,n,s);if(this.currentViewport.equals(r)===!1){const{gl:o}=this;o.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,n){(this.currentStencilFunc!==e||this.currentStencilRef!==t||this.currentStencilFuncMask!==n)&&(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){(this.currentStencilFail!==e||this.currentStencilZFail!==t||this.currentStencilZPass!==n)&&(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){const{gl:s}=this;e.side===xn?this.disable(s.CULL_FACE):this.enable(s.CULL_FACE);let r=e.side===ot;t&&(r=!r),this.setFlipSided(r),e.blending===gn&&e.transparent===!1?this.setBlending(Nn):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const o=e.stencilWrite;if(this.setStencilTest(o),o&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),e.alphaToCoverage===!0&&this.backend.renderer.currentSamples>0?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n)for(let u=0;u<8;u++)u<n?this.enable(12288+u):this.disable(12288+u)}setPolygonOffset(e,t,n){const{gl:s}=this;e?(this.enable(s.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==n)&&(s.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(s.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e?(this.gl.useProgram(e),this.currentProgram=e,!0):!1}setVertexState(e,t=null){const n=this.gl;return this.currentVAO!==e||this.currentIndex!==t?(n.bindVertexArray(e),t!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0):!1}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:n,currentBoundFramebuffers:s}=this;return s[e]!==t?(n.bindFramebuffer(e,t),s[e]=t,e===n.DRAW_FRAMEBUFFER&&(s[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(s[n.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){const{gl:n}=this;let s=[],r=!1;if(e.textures!==null){s=this.currentDrawbuffers.get(t),s===void 0&&(s=[],this.currentDrawbuffers.set(t,s));const o=e.textures;if(s.length!==o.length||s[0]!==n.COLOR_ATTACHMENT0){for(let a=0,u=o.length;a<u;a++)s[a]=n.COLOR_ATTACHMENT0+a;s.length=o.length,r=!0}}else s[0]!==n.BACK&&(s[0]=n.BACK,r=!0);r&&n.drawBuffers(s)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:s}=this;e===void 0&&(e=t.TEXTURE0+s-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:s,currentTextureSlot:r,currentBoundTextures:o,maxTextures:a}=this;n===void 0&&(r===null?n=s.TEXTURE0+a-1:n=r);let u=o[n];u===void 0&&(u={type:void 0,texture:void 0},o[n]=u),(u.type!==e||u.texture!==t)&&(r!==n&&(s.activeTexture(n),this.currentTextureSlot=n),s.bindTexture(e,t),u.type=e,u.texture=t)}bindBufferBase(e,t,n){const{gl:s}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==n?(s.bindBufferBase(e,t,n),this.currentBoundBufferBases[r]=n,!0):!1}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,s=n[t];s!==void 0&&s.type!==void 0&&(e.bindTexture(s.type,null),s.type=void 0,s.texture=void 0)}getParameter(e){const{gl:t,parameters:n}=this;return n[e]!==void 0?n[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:n,parameters:s}=this;s[e]!==t&&(n.pixelStorei(e,t),s[e]=t)}}class qw{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=tr){const{gl:n,extensions:s}=this;let r;const o=Ge.getTransfer(t);if(e===ht)return n.UNSIGNED_BYTE;if(e===Hh)return n.UNSIGNED_SHORT_4_4_4_4;if(e===Xh)return n.UNSIGNED_SHORT_5_5_5_1;if(e===Sl)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===Nl)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===Ws)return n.BYTE;if(e===js)return n.SHORT;if(e===ds)return n.UNSIGNED_SHORT;if(e===st)return n.INT;if(e===Ve)return n.UNSIGNED_INT;if(e===rt)return n.FLOAT;if(e===it)return n.HALF_FLOAT;if(e===jh)return n.ALPHA;if(e===Uo)return n.RGB;if(e===It)return n.RGBA;if(e===Tn)return n.DEPTH_COMPONENT;if(e===vn)return n.DEPTH_STENCIL;if(e===Fo)return n.RED;if(e===Do)return n.RED_INTEGER;if(e===Jt)return n.RG;if(e===Lo)return n.RG_INTEGER;if(e===Cl)return n.RGBA_INTEGER;if(e===Qi||e===Zi||e===Ji||e===eo)if(o===ae)if(r=s.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(e===Qi)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Zi)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Ji)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===eo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=s.get("WEBGL_compressed_texture_s3tc"),r!==null){if(e===Qi)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Zi)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Ji)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===eo)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===fc||e===pc||e===gc||e===mc)if(r=s.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(e===fc)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===pc)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===gc)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===mc)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===_u||e===xu||e===Tu||e===vu||e===Su||e===fo||e===Nu)if(r=s.get("WEBGL_compressed_texture_etc"),r!==null){if(e===_u||e===xu)return o===ae?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Tu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===vu)return r.COMPRESSED_R11_EAC;if(e===Su)return r.COMPRESSED_SIGNED_R11_EAC;if(e===fo)return r.COMPRESSED_RG11_EAC;if(e===Nu)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(e===Ru||e===wu||e===Eu||e===Au||e===Cu||e===Mu||e===Bu||e===Pu||e===Fu||e===Du||e===Lu||e===Uu||e===Ou||e===Iu)if(r=s.get("WEBGL_compressed_texture_astc"),r!==null){if(e===Ru)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===wu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Eu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Au)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Cu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Mu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Bu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Pu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Fu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Du)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Lu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Uu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Ou)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Iu)return o===ae?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===ku)if(r=s.get("EXT_texture_compression_bptc"),r!==null){if(e===ku)return o===ae?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(e===Gu||e===Vu||e===po||e===$u)if(r=s.get("EXT_texture_compression_rgtc"),r!==null){if(e===Gu)return r.COMPRESSED_RED_RGTC1_EXT;if(e===Vu)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===po)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===$u)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===Sn?n.UNSIGNED_INT_24_8:n[e]!==void 0?n[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,s)=>{function r(){const o=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(o===e.WAIT_FAILED){e.deleteSync(t),s();return}if(o===e.TIMEOUT_EXPIRED){requestAnimationFrame(r);return}e.deleteSync(t),n()}r()})}}let hh=!1,Gi,ru,fh;class Hw{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,hh===!1&&(this._init(),hh=!0)}_init(){const e=this.gl;Gi={[Go]:e.REPEAT,[Kr]:e.CLAMP_TO_EDGE,[ko]:e.MIRRORED_REPEAT},ru={[xt]:e.NEAREST,[Yh]:e.NEAREST_MIPMAP_NEAREST,[Yr]:e.NEAREST_MIPMAP_LINEAR,[vt]:e.LINEAR,[bu]:e.LINEAR_MIPMAP_NEAREST,[fs]:e.LINEAR_MIPMAP_LINEAR},fh={[ef]:e.NEVER,[Jh]:e.ALWAYS,[Al]:e.LESS,[ii]:e.LEQUAL,[Zh]:e.EQUAL,[er]:e.GEQUAL,[ho]:e.GREATER,[Qh]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return e.isCubeTexture===!0?n=t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?n=t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?n=t.TEXTURE_3D:n=t.TEXTURE_2D,n}getInternalFormat(e,t,n,s,r,o=!1){const{gl:a,extensions:u}=this;if(e!==null){if(a[e]!==void 0)return a[e];z("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=null;s&&(l=u.get("EXT_texture_norm16"),l||z("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let c=t;if(t===a.RED&&(n===a.FLOAT&&(c=a.R32F),n===a.HALF_FLOAT&&(c=a.R16F),n===a.UNSIGNED_BYTE&&(c=a.R8),n===a.BYTE&&(c=a.R8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.R16_EXT),n===a.SHORT&&l&&(c=l.R16_SNORM_EXT)),t===a.RED_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.R8UI),n===a.UNSIGNED_SHORT&&(c=a.R16UI),n===a.UNSIGNED_INT&&(c=a.R32UI),n===a.BYTE&&(c=a.R8I),n===a.SHORT&&(c=a.R16I),n===a.INT&&(c=a.R32I)),t===a.RG&&(n===a.FLOAT&&(c=a.RG32F),n===a.HALF_FLOAT&&(c=a.RG16F),n===a.UNSIGNED_BYTE&&(c=a.RG8),n===a.BYTE&&(c=a.RG8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.RG16_EXT),n===a.SHORT&&l&&(c=l.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.RG8UI),n===a.UNSIGNED_SHORT&&(c=a.RG16UI),n===a.UNSIGNED_INT&&(c=a.RG32UI),n===a.BYTE&&(c=a.RG8I),n===a.SHORT&&(c=a.RG16I),n===a.INT&&(c=a.RG32I)),t===a.RGB){const d=o?hc:Ge.getTransfer(r);n===a.FLOAT&&(c=a.RGB32F),n===a.HALF_FLOAT&&(c=a.RGB16F),n===a.UNSIGNED_BYTE&&(c=d===ae?a.SRGB8:a.RGB8),n===a.BYTE&&(c=a.RGB8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.RGB16_EXT),n===a.SHORT&&l&&(c=l.RGB16_SNORM_EXT),n===a.UNSIGNED_SHORT_5_6_5&&(c=a.RGB565),n===a.UNSIGNED_SHORT_5_5_5_1&&(c=a.RGB5_A1),n===a.UNSIGNED_SHORT_4_4_4_4&&(c=a.RGB4),n===a.UNSIGNED_INT_5_9_9_9_REV&&(c=a.RGB9_E5),n===a.UNSIGNED_INT_10F_11F_11F_REV&&(c=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.RGB8UI),n===a.UNSIGNED_SHORT&&(c=a.RGB16UI),n===a.UNSIGNED_INT&&(c=a.RGB32UI),n===a.BYTE&&(c=a.RGB8I),n===a.SHORT&&(c=a.RGB16I),n===a.INT&&(c=a.RGB32I)),t===a.RGBA){const d=o?hc:Ge.getTransfer(r);n===a.FLOAT&&(c=a.RGBA32F),n===a.HALF_FLOAT&&(c=a.RGBA16F),n===a.UNSIGNED_BYTE&&(c=d===ae?a.SRGB8_ALPHA8:a.RGBA8),n===a.BYTE&&(c=a.RGBA8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.RGBA16_EXT),n===a.SHORT&&l&&(c=l.RGBA16_SNORM_EXT),n===a.UNSIGNED_SHORT_4_4_4_4&&(c=a.RGBA4),n===a.UNSIGNED_SHORT_5_5_5_1&&(c=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.RGBA8UI),n===a.UNSIGNED_SHORT&&(c=a.RGBA16UI),n===a.UNSIGNED_INT&&(c=a.RGBA32UI),n===a.BYTE&&(c=a.RGBA8I),n===a.SHORT&&(c=a.RGBA16I),n===a.INT&&(c=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(n===a.UNSIGNED_SHORT&&(c=a.DEPTH_COMPONENT16),n===a.UNSIGNED_INT&&(c=a.DEPTH_COMPONENT24),n===a.FLOAT&&(c=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&n===a.UNSIGNED_INT_24_8&&(c=a.DEPTH24_STENCIL8),(c===a.R16F||c===a.R32F||c===a.RG16F||c===a.RG32F||c===a.RGBA16F||c===a.RGBA32F)&&u.get("EXT_color_buffer_float"),c}setTextureParameters(e,t){const{gl:n,extensions:s,backend:r}=this,{state:o}=this.backend,a=Ge.getPrimaries(Ge.workingColorSpace),u=t.colorSpace===tr?null:Ge.getPrimaries(t.colorSpace),l=t.colorSpace===tr||a===u?n.NONE:n.BROWSER_DEFAULT_WEBGL;o.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),o.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),o.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),o.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),n.texParameteri(e,n.TEXTURE_WRAP_S,Gi[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,Gi[t.wrapT]),(e===n.TEXTURE_3D||e===n.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,Gi[t.wrapR])),n.texParameteri(e,n.TEXTURE_MAG_FILTER,ru[t.magFilter]);const c=t.mipmaps!==void 0&&t.mipmaps.length>0,d=t.minFilter===vt&&c?fs:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,ru[d]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,fh[t.compareFunction])),s.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===xt||t.minFilter!==Yr&&t.minFilter!==fs||t.type===rt&&s.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const h=s.get("EXT_texture_filter_anisotropic");n.texParameterf(e,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:s}=this,r=this.getGLTextureType(e);let o=s[r];o===void 0&&(o=t.createTexture(),n.state.bindTexture(r,o),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),s[r]=o),n.set(e,{textureGPU:o,glTextureType:r})}createTexture(e,t){const{gl:n,backend:s}=this,{levels:r,width:o,height:a,depth:u}=t,l=s.utils.convert(e.format,e.colorSpace),c=s.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,l,c,e.normalized,e.colorSpace,e.isVideoTexture),h=n.createTexture(),f=this.getGLTextureType(e);s.state.bindTexture(f,h),this.setTextureParameters(f,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,r,d,o,a,u):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,r,d,o,a,u):e.isVideoTexture||n.texStorage2D(f,r,d,o,a),s.set(e,{textureGPU:h,glTextureType:f,glFormat:l,glType:c,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:n,backend:s}=this,{state:r}=s,{textureGPU:o,glTextureType:a,glFormat:u,glType:l}=s.get(t),{width:c,height:d}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(a,o),r.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(a,0,0,0,c,d,u,l,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:s,height:r}=t,{textureGPU:o,glTextureType:a,glFormat:u,glType:l,glInternalFormat:c}=this.backend.get(e);if(!(e.isRenderTargetTexture||o===void 0))if(this.backend.state.bindTexture(a,o),this.setTextureParameters(a,e),e.isCompressedTexture){const d=e.mipmaps,h=t.image;for(let f=0;f<d.length;f++){const p=d[f];e.isCompressedArrayTexture?e.format!==n.RGBA?u!==null?n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,f,0,0,0,p.width,p.height,h.depth,u,p.data):z("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texSubImage3D(n.TEXTURE_2D_ARRAY,f,0,0,0,p.width,p.height,h.depth,u,l,p.data):u!==null?n.compressedTexSubImage2D(n.TEXTURE_2D,f,0,0,p.width,p.height,u,p.data):z("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const d=t.images,h=e.mipmaps;for(let f=0;f<6;f++){const p=Vi(d[f]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,0,0,s,r,u,l,p);for(let g=0;g<h.length;g++){const m=h[g],y=Vi(m.images[f]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+f,g+1,0,0,y.width,y.height,u,l,y)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const d=t.image;if(e.layerUpdates.size>0){const h=Bm(d.width,d.height,e.format,e.type);for(const f of e.layerUpdates){const p=d.data.subarray(f*h/d.data.BYTES_PER_ELEMENT,(f+1)*h/d.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,f,d.width,d.height,1,u,l,p)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,d.width,d.height,d.depth,u,l,d.data)}else if(e.isData3DTexture){const d=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,d.width,d.height,d.depth,u,l,d.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,c,u,l,t.image);else if(e.isHTMLTexture)typeof n.texElementImage2D=="function"&&n.texElementImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t.image);else{const d=e.mipmaps;if(d.length>0)for(let h=0,f=d.length;h<f;h++){const p=d[h],g=Vi(p);n.texSubImage2D(a,h,0,0,p.width,p.height,u,l,g)}else{const h=Vi(t.image);n.texSubImage2D(a,0,0,0,s,r,u,l,h)}}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:s,glTextureType:r}=n.get(e);n.state.bindTexture(r,s),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const s=n.get(e);if(s.renderBufferStorageSetup=void 0,s.framebuffers){for(const r in s.framebuffers)t.deleteFramebuffer(s.framebuffers[r]);delete s.framebuffers}if(s.depthRenderbuffer&&(t.deleteRenderbuffer(s.depthRenderbuffer),delete s.depthRenderbuffer),s.stencilRenderbuffer&&(t.deleteRenderbuffer(s.stencilRenderbuffer),delete s.stencilRenderbuffer),s.msaaFrameBuffer&&(t.deleteFramebuffer(s.msaaFrameBuffer),delete s.msaaFrameBuffer),s.msaaRenderbuffers){for(let r=0;r<s.msaaRenderbuffers.length;r++)t.deleteRenderbuffer(s.msaaRenderbuffers[r]);delete s.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:n,backend:s}=this,{textureGPU:r,renderTarget:o}=s.get(e);this.deallocateRenderBuffers(o),t===!1&&n.deleteTexture(r),s.delete(e)}copyTextureToTexture(e,t,n=null,s=null,r=0,o=0){const{gl:a,backend:u}=this,{state:l}=this.backend,{textureGPU:c,glTextureType:d,glType:h,glFormat:f}=u.get(t);l.bindTexture(d,c);let p,g,m,y,_,T,S,N,R;const v=e.isCompressedTexture?e.mipmaps[o]:e.image;if(n!==null)p=n.max.x-n.min.x,g=n.max.y-n.min.y,m=n.isBox3?n.max.z-n.min.z:1,y=n.min.x,_=n.min.y,T=n.isBox3?n.min.z:0;else{const Z=Math.pow(2,-r);p=Math.floor(v.width*Z),g=Math.floor(v.height*Z),e.isDataArrayTexture||e.isArrayTexture?m=v.depth:e.isData3DTexture?m=Math.floor(v.depth*Z):m=1,y=0,_=0,T=0}s!==null?(S=s.x,N=s.y,R=s.z):(S=0,N=0,R=0),l.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const P=l.getParameter(a.UNPACK_ROW_LENGTH),D=l.getParameter(a.UNPACK_IMAGE_HEIGHT),L=l.getParameter(a.UNPACK_SKIP_PIXELS),j=l.getParameter(a.UNPACK_SKIP_ROWS),ee=l.getParameter(a.UNPACK_SKIP_IMAGES);l.pixelStorei(a.UNPACK_ROW_LENGTH,v.width),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,v.height),l.pixelStorei(a.UNPACK_SKIP_PIXELS,y),l.pixelStorei(a.UNPACK_SKIP_ROWS,_),l.pixelStorei(a.UNPACK_SKIP_IMAGES,T);const re=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,se=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const Z=u.get(e),oe=u.get(t),F=u.get(Z.renderTarget),G=u.get(oe.renderTarget),Q=F.framebuffers[Z.cacheKey],ve=G.framebuffers[oe.cacheKey];l.bindFramebuffer(a.READ_FRAMEBUFFER,Q),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,ve);for(let I=0;I<m;I++)re&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,Z.textureGPU,r,T+I),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,c,o,R+I)),a.blitFramebuffer(y,_,p,g,S,N,p,g,a.DEPTH_BUFFER_BIT,a.NEAREST);l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(r!==0||e.isRenderTargetTexture||u.has(e)){const Z=u.get(e);this._srcFramebuffer===null&&(this._srcFramebuffer=a.createFramebuffer()),this._dstFramebuffer===null&&(this._dstFramebuffer=a.createFramebuffer()),l.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let oe=0;oe<m;oe++)re?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,Z.textureGPU,r,T+oe):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,Z.textureGPU,r),se?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,c,o,R+oe):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,c,o),r!==0?a.blitFramebuffer(y,_,p,g,S,N,p,g,a.COLOR_BUFFER_BIT,a.NEAREST):se?a.copyTexSubImage3D(d,o,S,N,R+oe,y,_,p,g):a.copyTexSubImage2D(d,o,S,N,y,_,p,g);l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else se?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(d,o,S,N,R,p,g,m,f,h,v.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(d,o,S,N,R,p,g,m,f,v.data):a.texSubImage3D(d,o,S,N,R,p,g,m,f,h,v):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,o,S,N,p,g,f,h,v.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,o,S,N,v.width,v.height,f,v.data):a.texSubImage2D(a.TEXTURE_2D,o,S,N,p,g,f,h,v);l.pixelStorei(a.UNPACK_ROW_LENGTH,P),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,D),l.pixelStorei(a.UNPACK_SKIP_PIXELS,L),l.pixelStorei(a.UNPACK_SKIP_ROWS,j),l.pixelStorei(a.UNPACK_SKIP_IMAGES,ee),o===0&&t.generateMipmaps&&a.generateMipmap(d),l.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:s}=this,{state:r}=this.backend,{textureGPU:o}=this.backend.get(e),{x:a,y:u,z:l,w:c}=n,d=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const f=a!==0||u!==0;let p,g;if(e.isDepthTexture===!0?(p=s.DEPTH_BUFFER_BIT,g=s.DEPTH_ATTACHMENT,t.stencil&&(p|=s.STENCIL_BUFFER_BIT)):(p=s.COLOR_BUFFER_BIT,g=s.COLOR_ATTACHMENT0),f){const m=this.backend.get(t.renderTarget),y=m.framebuffers[t.getCacheKey()],_=m.msaaFrameBuffer;r.bindFramebuffer(s.DRAW_FRAMEBUFFER,y),r.bindFramebuffer(s.READ_FRAMEBUFFER,_);const T=h-u-c;s.blitFramebuffer(a,T,a+l,T+c,a,T,a+l,T+c,p,s.NEAREST),r.bindFramebuffer(s.READ_FRAMEBUFFER,y),r.bindTexture(s.TEXTURE_2D,o),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,T,l,c),r.unbindTexture()}else{const m=s.createFramebuffer();r.bindFramebuffer(s.DRAW_FRAMEBUFFER,m),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,g,s.TEXTURE_2D,o,0),s.blitFramebuffer(0,0,l,c,0,0,l,c,p,s.NEAREST),s.deleteFramebuffer(m)}}else r.bindTexture(s.TEXTURE_2D,o),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,h-c-u,l,c),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,s=!1){const{gl:r}=this,o=t.renderTarget,{depthTexture:a,depthBuffer:u,stencilBuffer:l,width:c,height:d}=o;if(r.bindRenderbuffer(r.RENDERBUFFER,e),u&&!l){let h=r.DEPTH_COMPONENT24;s===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,o.samples,h,c,d):n>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(h=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,n,h,c,d)):r.renderbufferStorage(r.RENDERBUFFER,h,c,d),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else u&&l&&(n>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,n,r.DEPTH24_STENCIL8,c,d):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,c,d),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,s,r,o){const{backend:a,gl:u}=this,{textureGPU:l,glFormat:c,glType:d}=this.backend.get(e),h=u.createFramebuffer();a.state.bindFramebuffer(u.READ_FRAMEBUFFER,h);const f=e.isCubeTexture?u.TEXTURE_CUBE_MAP_POSITIVE_X+o:u.TEXTURE_2D;u.framebufferTexture2D(u.READ_FRAMEBUFFER,u.COLOR_ATTACHMENT0,f,l,0);const p=this._getTypedArrayType(d),g=this._getBytesPerTexel(d,c),y=s*r*g,_=u.createBuffer();u.bindBuffer(u.PIXEL_PACK_BUFFER,_),u.bufferData(u.PIXEL_PACK_BUFFER,y,u.STREAM_READ),u.readPixels(t,n,s,r,c,d,0),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const T=new p(y/p.BYTES_PER_ELEMENT);return u.bindBuffer(u.PIXEL_PACK_BUFFER,_),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,T),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(u.READ_FRAMEBUFFER,null),u.deleteFramebuffer(h),T}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let s=0;if(e===n.UNSIGNED_BYTE&&(s=1),(e===n.UNSIGNED_SHORT_4_4_4_4||e===n.UNSIGNED_SHORT_5_5_5_1||e===n.UNSIGNED_SHORT_5_6_5||e===n.UNSIGNED_SHORT||e===n.HALF_FLOAT)&&(s=2),(e===n.UNSIGNED_INT||e===n.FLOAT)&&(s=4),t===n.RGBA)return s*4;if(t===n.RGB)return s*3;if(t===n.ALPHA)return s}dispose(){const{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}}function Vi(i){return i.isDataTexture?i.image.data:typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&i instanceof OffscreenCanvas?i:i.data}class Xw{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class Kw{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(t.has("EXT_texture_filter_anisotropic")===!0){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(this.maxUniformBlockSize!==null)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const ph={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class Yw{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:n,mode:s,object:r,type:o,info:a,index:u}=this;u!==0?n.drawElements(s,t,o,e):n.drawArrays(s,e,t),a.update(r,t,1)}renderInstances(e,t,n){const{gl:s,mode:r,type:o,index:a,object:u,info:l}=this;n!==0&&(a!==0?s.drawElementsInstanced(r,t,o,e,n):s.drawArraysInstanced(r,e,t,n),l.update(u,t,n))}renderMultiDraw(e,t,n){const{extensions:s,mode:r,object:o,info:a}=this;if(n===0)return;const u=s.get("WEBGL_multi_draw");if(u===null)for(let l=0;l<n;l++)this.render(e[l],t[l]);else{this.index!==0?u.multiDrawElementsWEBGL(r,t,0,this.type,e,0,n):u.multiDrawArraysWEBGL(r,e,0,t,0,n);let l=0;for(let c=0;c<n;c++)l+=t[c];a.update(o,l,1)}}}class Kg{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return t===void 0&&(z(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class Qw extends Kg{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext){z("EXT_disjoint_timer_query not supported; timestamps will be disabled."),this.trackTimestamp=!1;return}this.queries=[];for(let s=0;s<this.maxQueries;s++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return Oe(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t==null||this.activeQuery!==null)return;const n=this.queries[t];if(n)try{this.queryStates.get(t)==="inactive"&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(s){k("Error in beginQuery:",s),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(n){k("Error in endQuery:",n),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[r,o]of this.queryOffsets)if(this.queryStates.get(o)==="ended"){const u=this.queries[o];e.set(r,this.resolveQuery(u))}if(e.size===0)return this.lastValue;const t={},n=[];for(const[r,o]of e){const a=r.match(/^(.*):f(\d+)$/),u=parseInt(a[2]);n.includes(u)===!1&&n.push(u),t[u]===void 0&&(t[u]=0);const l=await o;this.timestamps.set(r,l),t[u]+=l}const s=t[n[n.length-1]];return this.lastValue=s,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return k("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let n,s=!1;const r=()=>{n&&(clearTimeout(n),n=null)},o=u=>{s||(s=!0,r(),t(u))},a=()=>{if(this.isDisposed){o(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){o(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){n=setTimeout(a,1);return}const c=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(c)/1e6)}catch(u){k("Error checking query:",u),t(this.lastValue)}};a()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,!!this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class gh extends Xg{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=t.context!==void 0?t.context:e.domElement.getContext("webgl2",n);function r(o){o.preventDefault();const a={api:"WebGL",message:o.statusMessage||"Unknown reason",reason:null,originalEvent:o};e.onDeviceLost(a)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=s,this.extensions=new Xw(this),this.capabilities=new Kw(this),this.attributeUtils=new Ww(this),this.textureUtils=new Hw(this),this.bufferRenderer=new Yw(this),this.state=new jw(this),this.utils=new qw(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(z("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return uo}async getArrayBufferAsync(e,t=null,n=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,s)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),n!==null){const r=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:r}),this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer===!0&&e.multiview===!1&&z("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new Qw(this.gl,e,2048));const n=this.timestampQueryPool[e];n.allocateQueriesForContext(t)!==null&&n.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:r,height:o}=this.getDrawingBufferSize();t.viewport(0,0,r,o)}if(e.scissor)this.updateScissor(e);else{const{width:r,height:o}=this.getDrawingBufferSize();t.scissor(0,0,r,o)}this.initTimestampQuery(Zt.RENDER,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(s),n.occlusionQueryObjects=new Array(s),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,s=this.get(e),r=s.previousContext;n.resetVertexState();const o=e.occlusionQueryCount;o>0&&(o>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(a!==null)for(let u=0;u<a.length;u++){const l=a[u];l.generateMipmaps&&this.generateMipmaps(l)}if(this._currentContext=r,this._resolveRenderTarget(e),r!==null){if(this._setFramebuffer(r),r.viewport)this.updateViewport(r);else{const{width:u,height:l}=this.getDrawingBufferSize();n.viewport(0,0,u,l)}if(r.scissor)this.updateScissor(r);else{const{width:u,height:l}=this.getDrawingBufferSize();n.scissor(0,0,u,l)}}this.prepareTimestampBuffer(Zt.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:s}=t;if(n&&s){const r=new WeakSet,{gl:o}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const a=()=>{let u=0;for(let l=0;l<n.length;l++){const c=n[l];c!==null&&o.getQueryParameter(c,o.QUERY_RESULT_AVAILABLE)&&(o.getQueryParameter(c,o.QUERY_RESULT)===0&&r.add(s[l]),n[l]=null,o.deleteQuery(c),u++)}u<n.length?requestAnimationFrame(a):t.occluded=r};a()}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:n,y:s,width:r,height:o}=e.viewportValue;t.viewport(n,e.height-o-s,r,o)}updateScissor(e){const{state:t}=this,{x:n,y:s,width:r,height:o}=e.scissorValue;t.scissor(n,e.height-o-s,r,o)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,n,s=null,r=!0,o=!0){const{gl:a,renderer:u}=this;s===null&&(s={textures:null,clearColorValue:this.getClearColor()});let l=0;if(e&&(l|=a.COLOR_BUFFER_BIT),t&&(l|=a.DEPTH_BUFFER_BIT),n&&(l|=a.STENCIL_BUFFER_BIT),l!==0){let c;s.clearColorValue?c=s.clearColorValue:c=this.getClearColor();const d=u.getClearDepth(),h=u.getClearStencil();if(t&&this.state.setDepthMask(!0),s.textures===null)a.clearColor(c.r,c.g,c.b,c.a),a.clear(l);else{if(r&&this._setFramebuffer(s),e)for(let f=0;f<s.textures.length;f++)f===0?a.clearBufferfv(a.COLOR,f,[c.r,c.g,c.b,c.a]):a.clearBufferfv(a.COLOR,f,[0,0,0,1]);t&&n?a.clearBufferfi(a.DEPTH_STENCIL,0,d,h):t?a.clearBufferfv(a.DEPTH,0,[d]):n&&a.clearBufferiv(a.STENCIL,0,[h]),r&&o&&this._resolveRenderTarget(s)}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(Zt.COMPUTE,this.getTimestampUID(e))}compute(e,t,n,s,r=null){const{state:o,gl:a}=this;this.discard===!1&&(o.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:u,transformBuffers:l,attributes:c}=this.get(s),d=this._getVaoKey(c),h=this.vaoCache[d];h===void 0?this.vaoCache[d]=this._createVao(c):o.setVertexState(h),o.useProgram(u),this._bindUniforms(n);const f=this._getTransformFeedback(l);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,f),a.beginTransformFeedback(a.POINTS),r=r!==null?r:t.count,Array.isArray(r)?(Oe("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&typeof r=="object"&&r.isIndirectStorageBufferAttribute&&(Oe("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),c[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let p=0;p<l.length;p++){const g=l[p];g.pbo&&this.has(g.pbo)&&this.textureUtils.copyBufferToTexture(g.transformBuffer,g.pbo),g.switchBuffers()}}finishCompute(e){const{state:t,gl:n}=this;this.discard=!1,t.disable(n.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Zt.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,n,s,r,o){if(e.isBatchedMesh)if(this.hasFeature("WEBGL_multi_draw")===!1){const{gl:a}=this,u=a.getUniformLocation(o,"nodeUniformDrawId"),l=e._multiDrawStarts,c=e._multiDrawCounts,d=e._multiDrawCount;for(let h=0;h<d;h++)a.uniform1ui(u,h),t.render(l[h],c[h])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else r>1?t.renderInstances(n,s,r):t.render(n,s)}draw(e){const{object:t,pipeline:n,material:s,context:r,hardwareClippingPlanes:o}=e,{programGPU:a}=this.get(n),{gl:u,state:l}=this,c=this.get(r),d=e.getDrawParameters();if(d===null)return;this._bindUniforms(e.getBindings());const h=t.isMesh&&t.matrixWorld.determinant()<0;l.setMaterial(s,h,o),r.mrt!==null&&r.textures!==null&&l.setMRTBlending(r.textures,r.mrt,s),l.useProgram(a);const f=e.getAttributes(),p=this.get(f);let g=p.vaoGPU;if(g===void 0){const v=this._getVaoKey(f);g=this.vaoCache[v],g===void 0&&(g=this._createVao(f),this.vaoCache[v]=g,p.vaoGPU=g)}const m=e.getIndex(),y=m!==null?this.get(m).bufferGPU:null;l.setVertexState(g,y);const _=c.lastOcclusionObject;if(_!==t&&_!==void 0){if(_!==null&&_.occlusionTest===!0&&(u.endQuery(u.ANY_SAMPLES_PASSED),c.occlusionQueryIndex++),t.occlusionTest===!0){const v=u.createQuery();u.beginQuery(u.ANY_SAMPLES_PASSED,v),c.occlusionQueries[c.occlusionQueryIndex]=v,c.occlusionQueryObjects[c.occlusionQueryIndex]=t}c.lastOcclusionObject=t}const T=this.bufferRenderer;t.isPoints?T.mode=u.POINTS:t.isLineSegments?T.mode=u.LINES:t.isLine?T.mode=u.LINE_STRIP:t.isLineLoop?T.mode=u.LINE_LOOP:s.wireframe===!0?(l.setLineWidth(s.wireframeLinewidth*this.renderer.getPixelRatio()),T.mode=u.LINES):T.mode=u.TRIANGLES;const{vertexCount:S,instanceCount:N}=d;let{firstVertex:R}=d;if(T.object=t,m!==null){R*=m.array.BYTES_PER_ELEMENT;const v=this.get(m);T.index=m.count,T.type=v.type}else T.index=0;if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const v=this.get(e.camera),P=e.camera.cameras,D=e.getBindingGroup("cameraIndex").bindings[0];if(v.indexesGPU===void 0||v.indexesGPU.length!==P.length){const Z=new Uint32Array([0,0,0,0]),oe=[];for(let F=0,G=P.length;F<G;F++){const Q=u.createBuffer();Z[0]=F,u.bindBuffer(u.UNIFORM_BUFFER,Q),u.bufferData(u.UNIFORM_BUFFER,Z,u.STATIC_DRAW),oe.push(Q)}v.indexesGPU=oe}let L=0;e:for(const Z of e.getBindings())for(const oe of Z.bindings){if(oe===D)break e;(oe.isUniformsGroup||oe.isUniformBuffer)&&L++}const j=this.renderer.getPixelRatio(),ee=this._currentContext.renderTarget,re=this._isRenderCameraDepthArray(this._currentContext),se=this._currentContext.activeCubeFace;if(re){const Z=this.get(ee.depthTexture);if(Z.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){Z.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:oe}=ee;for(let F=0,G=P.length;F<G;F++)this.renderer._activeCubeFace=F,this._currentContext.activeCubeFace=F,this._setFramebuffer(this._currentContext),this.clear(!1,!0,oe,this._currentContext,!1,!1);this.renderer._activeCubeFace=se,this._currentContext.activeCubeFace=se}}for(let Z=0,oe=P.length;Z<oe;Z++){const F=P[Z];if(t.layers.test(F.layers)){re&&(this.renderer._activeCubeFace=Z,this._currentContext.activeCubeFace=Z,this._setFramebuffer(this._currentContext));const G=F.viewport;if(G!==void 0){const Q=G.x*j,ve=G.y*j,I=G.width*j,H=G.height*j;l.viewport(Math.floor(Q),Math.floor(e.context.height-H-ve),Math.floor(I),Math.floor(H))}l.bindBufferBase(u.UNIFORM_BUFFER,L,v.indexesGPU[Z]),this._draw(t,T,R,S,N,a)}this._currentContext.activeCubeFace=se,this.renderer._activeCubeFace=se}}else this._draw(t,T,R,S,N,a)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,s,r,o){return this.textureUtils.copyTextureToBuffer(e,t,n,s,r,o)}updateSampler(){return""}createNodeBuilder(e,t){return new Vw(e,t)}createProgram(e){const t=this.gl,{stage:n,code:s}=e,r=n==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,s),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,s=e.pipeline,{fragmentProgram:r,vertexProgram:o}=s,a=n.createProgram(),u=this.get(r).shaderGPU,l=this.get(o).shaderGPU;if(n.attachShader(a,u),n.attachShader(a,l),n.linkProgram(a),this.set(s,{programGPU:a,fragmentShader:u,vertexShader:l}),t!==null&&this.parallel){const c=new Promise(d=>{const h=this.parallel,f=()=>{n.getProgramParameter(a,h.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),d()):requestAnimationFrame(f)};f()});t.push(c);return}this._completeCompile(e,s)}_handleSource(e,t){const n=e.split(`
|
|
680
|
-
`),s=[],r=Math.max(t-6,0),o=Math.min(t+6,n.length);for(let a=r;a<o;a++){const u=a+1;s.push(`${u===t?">":" "} ${u}: ${n[a]}`)}return s.join(`
|
|
681
|
-
`)}_getShaderErrors(e,t,n){const s=e.getShaderParameter(t,e.COMPILE_STATUS),o=(e.getShaderInfoLog(t)||"").trim();if(s&&o==="")return"";const a=/ERROR: 0:(\d+)/.exec(o);if(a){const u=parseInt(a[1]);return n.toUpperCase()+`
|
|
682
|
-
|
|
683
|
-
`+o+`
|
|
684
|
-
|
|
685
|
-
`+this._handleSource(e.getShaderSource(t),u)}else return o}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const s=this.gl,o=(s.getProgramInfoLog(e)||"").trim();if(s.getProgramParameter(e,s.LINK_STATUS)===!1)if(typeof this.renderer.debug.onShaderError=="function")this.renderer.debug.onShaderError(s,e,n,t);else{const a=this._getShaderErrors(s,n,"vertex"),u=this._getShaderErrors(s,t,"fragment");k("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(e,s.VALIDATE_STATUS)+`
|
|
686
|
-
|
|
687
|
-
Program Info Log: `+o+`
|
|
688
|
-
`+a+`
|
|
689
|
-
`+u)}else o!==""&&z("WebGLProgram: Program Info Log:",o)}}_completeCompile(e,t){const{state:n,gl:s}=this,r=this.get(t),{programGPU:o,fragmentShader:a,vertexShader:u}=r;s.getProgramParameter(o,s.LINK_STATUS)===!1&&this._logProgramError(o,a,u),n.useProgram(o);const l=e.getBindings();this._setupBindings(l,o),this.set(t,{programGPU:o,pipeline:o})}createComputePipeline(e,t){const{state:n,gl:s}=this,r={stage:"fragment",code:`#version 300 es
|
|
690
|
-
precision highp float;
|
|
691
|
-
void main() {}`};this.createProgram(r);const{computeProgram:o}=e,a=s.createProgram(),u=this.get(r).shaderGPU,l=this.get(o).shaderGPU,c=o.transforms,d=[],h=[];for(let m=0;m<c.length;m++){const y=c[m];d.push(y.varyingName),h.push(y.attributeNode)}s.attachShader(a,u),s.attachShader(a,l),s.transformFeedbackVaryings(a,d,s.SEPARATE_ATTRIBS),s.linkProgram(a),s.getProgramParameter(a,s.LINK_STATUS)===!1&&this._logProgramError(a,u,l),n.useProgram(a),this._setupBindings(t,a);const f=o.attributes,p=[],g=[];for(let m=0;m<f.length;m++){const y=f[m].node.attribute;p.push(y),this.has(y)||this.attributeUtils.createAttribute(y,s.ARRAY_BUFFER)}for(let m=0;m<h.length;m++){const y=h[m].attribute;this.has(y)||this.attributeUtils.createAttribute(y,s.ARRAY_BUFFER);const _=this.get(y);g.push(_)}this.set(e,{programGPU:a,transformBuffers:g,attributes:p})}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let n=0,s=0;for(const r of t){this.set(r,{textures:s,uniformBuffers:n});for(const o of r.bindings)o.isUniformBuffer&&n++,o.isSampledTexture&&s++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this;for(const n of e.bindings){const s=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){const r=n.buffer;let{bufferGPU:o}=this.get(r);o===void 0?(o=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,o),t.bufferData(t.UNIFORM_BUFFER,r.byteLength,t.DYNAMIC_DRAW),this.set(r,{bufferGPU:o})):t.bindBuffer(t.UNIFORM_BUFFER,o);const a=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,o),a.length===0)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const u=co(r),l=u?1:r.BYTES_PER_ELEMENT;for(let c=0,d=a.length;c<d;c++){const h=a[c],f=h.start*l,p=h.count*l,g=f*(u?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,g,r,f,p)}}s.bufferGPU=o,this.set(n,s)}else if(n.isSampledTexture){const{textureGPU:r,glTextureType:o}=this.get(n.texture);s.textureGPU=r,s.glTextureType=o,this.set(n,s)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const s=this.get(e).bufferGPU,r=e.buffer,o=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,s),o.length===0)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const a=co(r),u=a?1:r.BYTES_PER_ELEMENT;for(let l=0,c=o.length;l<c;l++){const d=o[l],h=d.start*u,f=d.count*u,p=h*(a?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,p,r,h,f)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(ph).filter(s=>ph[s]===e),n=this.extensions;for(let s=0;s<t.length;s++)if(n.has(t[s]))return!0;return!1}copyTextureToTexture(e,t,n=null,s=null,r=0,o=0){this.textureUtils.copyTextureToTexture(e,t,n,s,r,o)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}hasCompatibility(e){return e===Ns.TEXTURE_COMPARE?!0:super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:n}=this;this._setFramebuffer(e),n.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:n}=this;let s=null;if(e.textures!==null){const r=e.renderTarget,o=this.get(r),{samples:a,depthBuffer:u,stencilBuffer:l}=r,c=r.isCubeRenderTarget===!0,d=r.isRenderTarget3D===!0,h=r.depth>1,f=r.isXRRenderTarget===!0,p=f===!0&&r._hasExternalTextures===!0;let g=o.msaaFrameBuffer,m=o.depthRenderbuffer;const y=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),T=this._useMultisampledExtension(r),S=wg(e);let N;if(c?(o.cubeFramebuffers||(o.cubeFramebuffers={}),N=o.cubeFramebuffers[S]):f&&p===!1?N=this._xrFramebuffer:(o.framebuffers||(o.framebuffers={}),N=o.framebuffers[S]),N===void 0){N=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,N);const R=e.textures,v=[];if(c){o.cubeFramebuffers[S]=N;const{textureGPU:D}=this.get(R[0]),L=this.renderer._activeCubeFace,j=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+L,D,j)}else{o.framebuffers[S]=N;for(let D=0;D<R.length;D++){const L=R[D],j=this.get(L);j.renderTarget=e.renderTarget,j.cacheKey=S;const ee=t.COLOR_ATTACHMENT0+D;if(r.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,ee,j.textureGPU,0,a,0,2);else if(d||h){const re=this.renderer._activeCubeFace,se=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,ee,j.textureGPU,se,re)}else if(T)y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,ee,t.TEXTURE_2D,j.textureGPU,0,a);else{const re=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,ee,t.TEXTURE_2D,j.textureGPU,re)}}}const P=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(r._autoAllocateDepthBuffer===!0){const D=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(D,e,0,T),o.xrDepthRenderbuffer=D,v.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,D),t.framebufferRenderbuffer(t.FRAMEBUFFER,P,t.RENDERBUFFER,D)}else if(e.depthTexture!==null){v.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const D=this.get(e.depthTexture);if(D.renderTarget=e.renderTarget,D.cacheKey=S,r.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,P,D.textureGPU,0,a,0,2);else if(p&&T)y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,P,t.TEXTURE_2D,D.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const L=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,P,D.textureGPU,0,L)}else if(e.depthTexture.isCubeTexture){const L=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,P,t.TEXTURE_CUBE_MAP_POSITIVE_X+L,D.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,P,t.TEXTURE_2D,D.textureGPU,0)}o.depthInvalidationArray=v}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,N);const v=this.renderer._activeCubeFace,P=this.get(e.depthTexture),D=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,D,P.textureGPU,0,v)}if((f||T||r.multiview)&&r._isOpaqueFramebuffer!==!0){n.bindFramebuffer(t.FRAMEBUFFER,N);const v=this.get(e.textures[0]);r.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,v.textureGPU,0,a,0,2):T?y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,v.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,v.textureGPU,0);const P=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(r._autoAllocateDepthBuffer===!0){const D=o.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,D),t.framebufferRenderbuffer(t.FRAMEBUFFER,P,t.RENDERBUFFER,D)}else{const D=this.get(e.depthTexture);r.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,P,D.textureGPU,0,a,0,2):T?y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,P,t.TEXTURE_2D,D.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,P,t.TEXTURE_2D,D.textureGPU,0)}}}if(a>0&&T===!1&&!r.multiview){if(g===void 0){const R=[];g=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,g);const v=[],P=e.textures;for(let D=0;D<P.length;D++){v[D]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,v[D]),R.push(t.COLOR_ATTACHMENT0+D);const L=e.textures[D],j=this.get(L);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,j.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+D,t.RENDERBUFFER,v[D])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),o.msaaFrameBuffer=g,o.msaaRenderbuffers=v,u&&m===void 0){m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,a),o.depthRenderbuffer=m;const D=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;R.push(D)}o.invalidationArray=R}s=o.msaaFrameBuffer}else s=N;n.drawBuffers(e,N)}n.bindFramebuffer(t.FRAMEBUFFER,s)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){const s=this.get(e[n]);t+=":"+s.id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let s=0;s<e.length;s++){const r=e[s],o=this.get(r);t.bindBuffer(t.ARRAY_BUFFER,o.bufferGPU),t.enableVertexAttribArray(s);let a,u;r.isInterleavedBufferAttribute===!0?(a=r.data.stride*o.bytesPerElement,u=r.offset*o.bytesPerElement):(a=0,u=0),o.isInteger?t.vertexAttribIPointer(s,r.itemSize,o.type,a,u):t.vertexAttribPointer(s,r.itemSize,o.type,r.normalized,a,u),r.isInstancedBufferAttribute&&!r.isInterleavedBufferAttribute?t.vertexAttribDivisor(s,r.meshPerAttribute):r.isInterleavedBufferAttribute&&r.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(s,r.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let r=0;r<e.length;r++)t+=":"+e[r].id;let n=this.transformFeedbackCache[t];if(n!==void 0)return n;const{gl:s}=this;n=s.createTransformFeedback(),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,n);for(let r=0;r<e.length;r++){const o=e[r];s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,r,o.transformBuffer)}return s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;let s=0,r=0;for(const o of e)for(const a of o.bindings)if(a.isUniformsGroup||a.isUniformBuffer){const u=s++,l=n.getUniformBlockIndex(t,a.name);n.uniformBlockBinding(t,l,u)}else if(a.isSampledTexture){const u=r++,l=n.getUniformLocation(t,a.name);n.uniform1i(l,u)}}_bindUniforms(e){const{gl:t,state:n}=this;let s=0,r=0;for(const o of e)for(const a of o.bindings){const u=this.get(a);if(a.isUniformsGroup||a.isUniformBuffer){const l=s++;n.bindBufferBase(t.UNIFORM_BUFFER,l,u.bufferGPU)}else if(a.isSampledTexture){const l=r++;n.bindTexture(u.glTextureType,u.textureGPU,t.TEXTURE0+l)}}}_resolveRenderTarget(e){const{gl:t,state:n}=this,s=e.renderTarget;if(e.textures!==null&&s){const r=this.get(s);if(s.samples>0&&this._useMultisampledExtension(s)===!1){const o=r.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const u=r.msaaFrameBuffer,l=r.msaaRenderbuffers,c=e.textures,d=c.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,u),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,o),d)for(let h=0;h<c.length;h++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.TEXTURE_2D,null,0);for(let h=0;h<c.length;h++){if(d){const{textureGPU:f}=this.get(c[h]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[h]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,f,0)}if(e.scissor){const{x:f,y:p,width:g,height:m}=e.scissorValue,y=e.height-m-p;t.blitFramebuffer(f,y,f+g,y+m,f,y,f+g,y+m,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(d)for(let h=0;h<c.length;h++){const{textureGPU:f}=this.get(c[h]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.RENDERBUFFER,l[h]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+h,t.TEXTURE_2D,f,0)}this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(s.resolveDepthBuffer===!1&&r.framebuffers){const o=r.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,o),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer!==!1}dispose(){this.textureUtils!==null&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const $i={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list"},en=typeof self<"u"&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},Ye={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},ut={Store:"store"},be={Load:"load",Clear:"clear"},mh={CCW:"ccw",CW:"cw"},yh={None:"none",Back:"back"},Co={Uint16:"uint16",Uint32:"uint32"},b={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R16Unorm:"r16unorm",R16Snorm:"r16snorm",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RG16Unorm:"rg16unorm",RG16Snorm:"rg16snorm",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rg11b10ufloat",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA16Unorm:"rgba16unorm",RGBA16Snorm:"rgba16snorm",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-unorm-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},iu={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},Ht={Linear:"linear",Nearest:"nearest"},he={Zero:"zero",One:"one",Src:"src",OneMinusSrc:"one-minus-src",SrcAlpha:"src-alpha",OneMinusSrcAlpha:"one-minus-src-alpha",Dst:"dst",OneMinusDst:"one-minus-dst",DstAlpha:"dst-alpha",OneMinusDstAlpha:"one-minus-dst-alpha",SrcAlphaSaturated:"src-alpha-saturated",Constant:"constant",OneMinusConstant:"one-minus-constant"},es={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},bh={None:0,All:15},Dn={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},ou={Storage:"storage",ReadOnlyStorage:"read-only-storage"},au={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},_h={NonFiltering:"non-filtering",Comparison:"comparison"},ts={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},xh={TwoD:"2d",ThreeD:"3d"},tt={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},Zw={All:"all"},zi={Vertex:"vertex",Instance:"instance"},Mo={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},Th={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class Jw extends qg{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class eE extends $g{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let tE=0;class nE extends eE{constructor(e,t){super("StorageBuffer_"+tE++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Mt.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class sE extends Xn{constructor(e){super(),this.device=e;const t=`
|
|
692
|
-
struct VarysStruct {
|
|
693
|
-
@builtin( position ) Position: vec4f,
|
|
694
|
-
@location( 0 ) vTex : vec2f,
|
|
695
|
-
@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
|
|
696
|
-
};
|
|
697
|
-
|
|
698
|
-
@group( 0 ) @binding ( 2 )
|
|
699
|
-
var<uniform> flipY: u32;
|
|
700
|
-
|
|
701
|
-
@vertex
|
|
702
|
-
fn mainVS(
|
|
703
|
-
@builtin( vertex_index ) vertexIndex : u32,
|
|
704
|
-
@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
|
|
705
|
-
|
|
706
|
-
var Varys : VarysStruct;
|
|
707
|
-
|
|
708
|
-
var pos = array(
|
|
709
|
-
vec2f( -1, -1 ),
|
|
710
|
-
vec2f( -1, 3 ),
|
|
711
|
-
vec2f( 3, -1 ),
|
|
712
|
-
);
|
|
713
|
-
|
|
714
|
-
let p = pos[ vertexIndex ];
|
|
715
|
-
let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
|
|
716
|
-
Varys.vTex = p * mult + vec2f( 0.5 );
|
|
717
|
-
Varys.Position = vec4f( p, 0, 1 );
|
|
718
|
-
Varys.vBaseArrayLayer = instanceIndex;
|
|
719
|
-
|
|
720
|
-
return Varys;
|
|
721
|
-
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
@group( 0 ) @binding( 0 )
|
|
725
|
-
var imgSampler : sampler;
|
|
726
|
-
|
|
727
|
-
@group( 0 ) @binding( 1 )
|
|
728
|
-
var img2d : texture_2d<f32>;
|
|
729
|
-
|
|
730
|
-
@fragment
|
|
731
|
-
fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
|
|
732
|
-
|
|
733
|
-
return textureSample( img2d, imgSampler, Varys.vTex );
|
|
734
|
-
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
@group( 0 ) @binding( 1 )
|
|
738
|
-
var img2dArray : texture_2d_array<f32>;
|
|
739
|
-
|
|
740
|
-
@fragment
|
|
741
|
-
fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
|
|
742
|
-
|
|
743
|
-
return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
|
|
744
|
-
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
const faceMat = array(
|
|
748
|
-
mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
|
|
749
|
-
mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
|
|
750
|
-
mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
|
|
751
|
-
mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
|
|
752
|
-
mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
|
|
753
|
-
mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
|
|
754
|
-
);
|
|
755
|
-
|
|
756
|
-
@group( 0 ) @binding( 1 )
|
|
757
|
-
var imgCube : texture_cube<f32>;
|
|
758
|
-
|
|
759
|
-
@fragment
|
|
760
|
-
fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
|
|
761
|
-
|
|
762
|
-
return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
|
|
763
|
-
|
|
764
|
-
}
|
|
765
|
-
`;this.mipmapSampler=e.createSampler({minFilter:Ht.Linear}),this.flipYSampler=e.createSampler({minFilter:Ht.Nearest}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:t})}getTransferPipeline(e,t){t=t||"2d-array";const n=`${e}-${t}`;let s=this.transferPipelines[n];return s===void 0&&(s=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[n]=s),s}flipY(e,t,n=0){const s=t.format,{width:r,height:o}=t.size,a=this.device.createTexture({size:{width:r,height:o},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=this.getTransferPipeline(s,e.textureBindingViewDimension),l=this.getTransferPipeline(s,a.textureBindingViewDimension),c=this.device.createCommandEncoder({}),d=(h,f,p,g,m,y)=>{const _=h.getBindGroupLayout(0),T=this.device.createBindGroup({layout:_,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:f.createView({dimension:f.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:y?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),S=c.beginRenderPass({colorAttachments:[{view:g.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:m,arrayLayerCount:1}),loadOp:be.Clear,storeOp:ut.Store}]});S.setPipeline(h),S.setBindGroup(0,T),S.draw(3,1,0,p),S.end()};d(u,e,n,a,0,!1),d(l,a,0,e,n,!0),this.device.queue.submit([c.finish()]),a.destroy()}generateMipmaps(e,t=null){const n=this.get(e),s=n.layers||this._mipmapCreateBundles(e),r=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(r,s),t===null&&this.device.queue.submit([r.finish()]),n.layers=s}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(e.format,t),s=n.getBindGroupLayout(0),r=[];for(let o=1;o<e.mipLevelCount;o++)for(let a=0;a<e.depthOrArrayLayers;a++){const u=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:e.createView({dimension:t,baseMipLevel:o-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),l={colorAttachments:[{view:e.createView({dimension:"2d",baseMipLevel:o,mipLevelCount:1,baseArrayLayer:a,arrayLayerCount:1}),loadOp:be.Clear,storeOp:ut.Store}]},c=this.device.createRenderBundleEncoder({colorFormats:[e.format]});c.setPipeline(n),c.setBindGroup(0,u),c.draw(3,1,0,a),r.push({renderBundles:[c.finish()],passDescriptor:l})}return r}_mipmapRunBundles(e,t){const n=t.length;for(let s=0;s<n;s++){const r=t[s],o=e.beginRenderPass(r.passDescriptor);o.executeBundles(r.renderBundles),o.end()}}}const rE={[ef]:"never",[Al]:"less",[Zh]:"equal",[ii]:"less-equal",[ho]:"greater",[er]:"greater-equal",[Jh]:"always",[Qh]:"not-equal"},iE=[0,1,3,2,4,5];class oE{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,n=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let s=this._samplerCache.get(n);if(s===void 0){const o={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};e.isDepthTexture&&e.compareFunction===null&&(o.magFilter=Ht.Nearest,o.minFilter=Ht.Nearest,o.mipmapFilter=Ht.Nearest),o.magFilter===Ht.Linear&&o.minFilter===Ht.Linear&&o.mipmapFilter===Ht.Linear&&(o.maxAnisotropy=e.anisotropy),e.isDepthTexture&&e.compareFunction!==null&&t.hasCompatibility(Ns.TEXTURE_COMPARE)&&(o.compare=rE[e.compareFunction]),s={sampler:t.device.createSampler(o),usedTimes:0},this._samplerCache.set(n,s)}const r=t.get(e);if(r.sampler!==s.sampler){if(r.sampler!==void 0){const o=this._samplerCache.get(r.samplerKey);o.usedTimes--,o.usedTimes===0&&this._samplerCache.delete(r.samplerKey)}r.samplerKey=n,r.sampler=s.sampler,s.usedTimes++}return n}createDefaultTexture(e){let t;const n=hl(e,this.backend.device);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(n):t=this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,s=n.get(e);if(s.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture){s.texture=e.sourceTexture,s.initialized=!0;return}t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);const{width:r,height:o,depth:a,levels:u}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const l=this._getDimension(e),c=e.internalFormat||t.format||hl(e,n.device);s.format=c;const{samples:d,primarySamples:h,isMSAA:f}=n.utils.getTextureSampleData(e);let p=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(p|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&c!==b.RGB9E5UFloat&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const g={label:e.name,size:{width:r,height:o,depthOrArrayLayers:a},mipLevelCount:u,sampleCount:h,dimension:l,format:c,usage:p};if(c===void 0){z("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(g.textureBindingViewDimension=tt.Cube);try{s.texture=n.device.createTexture(g)}catch{z("WebGPURenderer: Failed to create texture with descriptor:",g),this.createDefaultTexture(e);return}if(f){const m=Object.assign({},g);m.label=m.label+"-msaa",m.sampleCount=d,m.mipLevelCount=1,s.msaaTexture=n.device.createTexture(m)}s.initialized=!0,s.textureDescriptorGPU=g}destroyTexture(e,t=!1){const n=this.backend,s=n.get(e);s.texture!==void 0&&t===!1&&s.texture.destroy(),s.msaaTexture!==void 0&&s.msaaTexture.destroy(),n.delete(e)}generateMipmaps(e,t=null){const n=this.backend.get(e);this._generateMipmaps(n.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:s}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,o=t.colorTexture,a=e.get(o);if(o.width===n&&o.height===s&&o.samples===r)return a.texture;let u=a.texture;return u&&u.destroy(),u=e.device.createTexture({label:"colorBuffer",size:{width:n,height:s,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),o.source.width=n,o.source.height=s,o.samples=r,a.texture=u,u}getDepthBuffer(e=!0,t=!1){const n=this.backend,s=n.renderer.getCanvasTarget(),{width:r,height:o}=n.getDrawingBufferSize(),a=n.renderer.currentSamples,u=s.depthTexture;if(u.width===r&&u.height===o&&u.samples===a&&u.depth===e&&u.stencil===t)return n.get(u).texture;const l=n.get(u).texture;let c,d;if(t?(c=vn,d=n.renderer.reversedDepthBuffer===!0?rt:Sn):e&&(c=Tn,d=n.renderer.reversedDepthBuffer===!0?rt:Ve),l!==void 0){if(u.image.width===r&&u.image.height===o&&u.format===c&&u.type===d&&u.samples===a)return l;this.destroyTexture(u)}return u.name="depthBuffer",u.format=c,u.type=d,u.image.width=r,u.image.height=o,u.samples=a,this.createTexture(u,{width:r,height:o}),n.get(u).texture}updateTexture(e,t){const n=this.backend.get(e),s=e.mipmaps,{textureDescriptorGPU:r}=n;if(!(e.isRenderTargetTexture||r===void 0)){if(e.isDataTexture)if(s.length>0)for(let o=0,a=s.length;o<a;o++){const u=s[o];this._copyBufferToTexture(u,n.texture,r,0,e.flipY,0,o)}else this._copyBufferToTexture(t.image,n.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const o of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,r,o,e.flipY,o);e.clearLayerUpdates()}else for(let o=0;o<t.image.depth;o++)this._copyBufferToTexture(t.image,n.texture,r,o,e.flipY,o);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,n.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,r);else if(e.isHTMLTexture){const o=this.backend.device,a=this.backend.renderer.domElement,u=e.image;if(typeof o.queue.copyElementImageToTexture!="function")return;if(!n.hasPaintCallback){n.hasPaintCallback=!0,a.requestPaint();return}const l=r.size.width,c=r.size.height;o.queue.copyElementImageToTexture(u,l,c,{texture:n.texture}),e.flipY&&this._flipY(n.texture,r)}else if(s.length>0)for(let o=0,a=s.length;o<a;o++){const u=s[o];this._copyImageToTexture(u,n.texture,r,0,e.flipY,e.premultiplyAlpha,o)}else this._copyImageToTexture(t.image,n.texture,r,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,s,r,o){const a=this.backend.device,u=this.backend.get(e),l=u.texture,c=u.textureDescriptorGPU.format,d=this._getBytesPerTexel(c);let h=s*d;h=Math.ceil(h/256)*256;const f=a.createBuffer({size:(r-1)*h+s*d,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:l,origin:{x:t,y:n,z:o}},{buffer:f,bytesPerRow:h},{width:s,height:r});const g=this._getTypedArrayType(c);a.queue.submit([p.finish()]),await f.mapAsync(GPUMapMode.READ);const m=f.getMappedRange().slice();return f.destroy(),new g(m)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const n=new Ml;n.minFilter=xt,n.magFilter=xt,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(t===void 0){const n=new Vo;n.minFilter=xt,n.magFilter=xt,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,n){const s=e.images,r=e.mipmaps;for(let o=0;o<6;o++){const a=s[o],u=e.flipY===!0?iE[o]:o;a.isDataTexture?this._copyBufferToTexture(a.image,t,n,u,e.flipY):this._copyImageToTexture(a,t,n,u,e.flipY,e.premultiplyAlpha);for(let l=0;l<r.length;l++){const d=r[l].images[o];d.isDataTexture?this._copyBufferToTexture(d.image,t,n,u,e.flipY,0,l+1):this._copyImageToTexture(d,t,n,u,e.flipY,e.premultiplyAlpha,l+1)}}}_copyImageToTexture(e,t,n,s,r,o,a=0){const u=this.backend.device,l=a>0?e.width:n.size.width,c=a>0?e.height:n.size.height;try{u.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:a,origin:{x:0,y:0,z:s},premultipliedAlpha:o},{width:l,height:c,depthOrArrayLayers:1})}catch{}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new sE(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,s,r,o=0,a=0){const u=this.backend.device,l=e.data,c=this._getBytesPerTexel(n.format),d=e.width*c;u.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:s}},l,{offset:e.width*e.height*c*o,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),r===!0&&this._flipY(t,n,s)}_copyCompressedBufferToTexture(e,t,n){const s=this.backend.device,r=this._getBlockData(n.format),o=n.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const u=e[a],l=u.width,c=u.height,d=o?n.size.depthOrArrayLayers:1,h=Math.ceil(l/r.width)*r.byteLength,f=h*Math.ceil(c/r.height);for(let p=0;p<d;p++)s.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:p}},u.data,{offset:p*f,bytesPerRow:h,rowsPerImage:Math.ceil(c/r.height)},{width:Math.ceil(l/r.width)*r.width,height:Math.ceil(c/r.height)*r.height,depthOrArrayLayers:1})}}_getBlockData(e){if(e===b.BC1RGBAUnorm||e===b.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===b.BC2RGBAUnorm||e===b.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===b.BC3RGBAUnorm||e===b.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===b.BC4RUnorm||e===b.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===b.BC5RGUnorm||e===b.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===b.BC6HRGBUFloat||e===b.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===b.BC7RGBAUnorm||e===b.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===b.ETC2RGB8Unorm||e===b.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===b.ETC2RGB8A1Unorm||e===b.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===b.ETC2RGBA8Unorm||e===b.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===b.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===b.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===b.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===b.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===b.ASTC4x4Unorm||e===b.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===b.ASTC5x4Unorm||e===b.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===b.ASTC5x5Unorm||e===b.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===b.ASTC6x5Unorm||e===b.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===b.ASTC6x6Unorm||e===b.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===b.ASTC8x5Unorm||e===b.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===b.ASTC8x6Unorm||e===b.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===b.ASTC8x8Unorm||e===b.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===b.ASTC10x5Unorm||e===b.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===b.ASTC10x6Unorm||e===b.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===b.ASTC10x8Unorm||e===b.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===b.ASTC10x10Unorm||e===b.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===b.ASTC12x10Unorm||e===b.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===b.ASTC12x12Unorm||e===b.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=iu.ClampToEdge;return e===Go?t=iu.Repeat:e===ko&&(t=iu.MirrorRepeat),t}_convertFilterMode(e){let t=Ht.Linear;return(e===xt||e===Yh||e===Yr)&&(t=Ht.Nearest),t}_getBytesPerTexel(e){if(e===b.R8Unorm||e===b.R8Snorm||e===b.R8Uint||e===b.R8Sint)return 1;if(e===b.R16Uint||e===b.R16Sint||e===b.R16Float||e===b.RG8Unorm||e===b.RG8Snorm||e===b.RG8Uint||e===b.RG8Sint||e===b.R16Unorm||e===b.R16Snorm)return 2;if(e===b.R32Uint||e===b.R32Sint||e===b.R32Float||e===b.RG16Uint||e===b.RG16Sint||e===b.RG16Float||e===b.RGBA8Unorm||e===b.RGBA8UnormSRGB||e===b.RGBA8Snorm||e===b.RGBA8Uint||e===b.RGBA8Sint||e===b.BGRA8Unorm||e===b.BGRA8UnormSRGB||e===b.RG16Unorm||e===b.RG16Snorm||e===b.RGB9E5UFloat||e===b.RGB10A2Unorm||e===b.RG11B10UFloat||e===b.Depth32Float||e===b.Depth24Plus||e===b.Depth24PlusStencil8||e===b.Depth32FloatStencil8)return 4;if(e===b.RG32Uint||e===b.RG32Sint||e===b.RG32Float||e===b.RGBA16Uint||e===b.RGBA16Sint||e===b.RGBA16Float||e===b.RGBA16Unorm||e===b.RGBA16Snorm)return 8;if(e===b.RGBA32Uint||e===b.RGBA32Sint||e===b.RGBA32Float)return 16}_getTypedArrayType(e){if(e===b.R8Uint)return Uint8Array;if(e===b.R8Sint)return Int8Array;if(e===b.R8Unorm)return Uint8Array;if(e===b.R8Snorm)return Int8Array;if(e===b.RG8Uint)return Uint8Array;if(e===b.RG8Sint)return Int8Array;if(e===b.RG8Unorm)return Uint8Array;if(e===b.RG8Snorm)return Int8Array;if(e===b.RGBA8Uint)return Uint8Array;if(e===b.RGBA8Sint)return Int8Array;if(e===b.RGBA8Unorm||e===b.RGBA8UnormSRGB)return Uint8Array;if(e===b.RGBA8Snorm)return Int8Array;if(e===b.R16Uint)return Uint16Array;if(e===b.R16Sint)return Int16Array;if(e===b.RG16Uint)return Uint16Array;if(e===b.RG16Sint)return Int16Array;if(e===b.RGBA16Uint)return Uint16Array;if(e===b.RGBA16Sint)return Int16Array;if(e===b.R16Float||e===b.RG16Float||e===b.RGBA16Float||e===b.R16Unorm)return Uint16Array;if(e===b.R16Snorm)return Int16Array;if(e===b.RG16Unorm)return Uint16Array;if(e===b.RG16Snorm)return Int16Array;if(e===b.RGBA16Unorm)return Uint16Array;if(e===b.RGBA16Snorm)return Int16Array;if(e===b.R32Uint)return Uint32Array;if(e===b.R32Sint)return Int32Array;if(e===b.R32Float)return Float32Array;if(e===b.RG32Uint)return Uint32Array;if(e===b.RG32Sint)return Int32Array;if(e===b.RG32Float)return Float32Array;if(e===b.RGBA32Uint)return Uint32Array;if(e===b.RGBA32Sint)return Int32Array;if(e===b.RGBA32Float)return Float32Array;if(e===b.BGRA8Unorm||e===b.BGRA8UnormSRGB)return Uint8Array;if(e===b.RGB10A2Unorm||e===b.RGB9E5UFloat||e===b.RG11B10UFloat)return Uint32Array;if(e===b.Depth32Float)return Float32Array;if(e===b.Depth24Plus||e===b.Depth24PlusStencil8)return Uint32Array;if(e===b.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.is3DTexture||e.isData3DTexture?t=xh.ThreeD:t=xh.TwoD,t}}function hl(i,e){const t=i.format,n=i.type,s=i.normalized,r=i.colorSpace,o=Ge.getTransfer(r);let a,u=!1;if(s&&(u=e.features.has(Mo.TextureFormatsTier1),u===!1&&z("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),i.isCompressedTexture===!0||i.isCompressedArrayTexture===!0)switch(t){case Qi:case Zi:a=o===ae?b.BC1RGBAUnormSRGB:b.BC1RGBAUnorm;break;case Ji:a=o===ae?b.BC2RGBAUnormSRGB:b.BC2RGBAUnorm;break;case eo:a=o===ae?b.BC3RGBAUnormSRGB:b.BC3RGBAUnorm;break;case Gu:a=b.BC4RUnorm;break;case Vu:a=b.BC4RSnorm;break;case po:a=b.BC5RGUnorm;break;case $u:a=b.BC5RGSnorm;break;case ku:a=o===ae?b.BC7RGBAUnormSRGB:b.BC7RGBAUnorm;break;case xu:case _u:a=o===ae?b.ETC2RGB8UnormSRGB:b.ETC2RGB8Unorm;break;case Tu:a=o===ae?b.ETC2RGBA8UnormSRGB:b.ETC2RGBA8Unorm;break;case vu:a=b.EACR11Unorm;break;case Su:a=b.EACR11Snorm;break;case fo:a=b.EACRG11Unorm;break;case Nu:a=b.EACRG11Snorm;break;case Ru:a=o===ae?b.ASTC4x4UnormSRGB:b.ASTC4x4Unorm;break;case wu:a=o===ae?b.ASTC5x4UnormSRGB:b.ASTC5x4Unorm;break;case Eu:a=o===ae?b.ASTC5x5UnormSRGB:b.ASTC5x5Unorm;break;case Au:a=o===ae?b.ASTC6x5UnormSRGB:b.ASTC6x5Unorm;break;case Cu:a=o===ae?b.ASTC6x6UnormSRGB:b.ASTC6x6Unorm;break;case Mu:a=o===ae?b.ASTC8x5UnormSRGB:b.ASTC8x5Unorm;break;case Bu:a=o===ae?b.ASTC8x6UnormSRGB:b.ASTC8x6Unorm;break;case Pu:a=o===ae?b.ASTC8x8UnormSRGB:b.ASTC8x8Unorm;break;case Fu:a=o===ae?b.ASTC10x5UnormSRGB:b.ASTC10x5Unorm;break;case Du:a=o===ae?b.ASTC10x6UnormSRGB:b.ASTC10x6Unorm;break;case Lu:a=o===ae?b.ASTC10x8UnormSRGB:b.ASTC10x8Unorm;break;case Uu:a=o===ae?b.ASTC10x10UnormSRGB:b.ASTC10x10Unorm;break;case Ou:a=o===ae?b.ASTC12x10UnormSRGB:b.ASTC12x10Unorm;break;case Iu:a=o===ae?b.ASTC12x12UnormSRGB:b.ASTC12x12Unorm;break;case It:a=o===ae?b.RGBA8UnormSRGB:b.RGBA8Unorm;break;default:k("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case It:switch(n){case Ws:a=b.RGBA8Snorm;break;case js:a=u?b.RGBA16Snorm:b.RGBA16Sint;break;case ds:a=u?b.RGBA16Unorm:b.RGBA16Uint;break;case Ve:a=b.RGBA32Uint;break;case st:a=b.RGBA32Sint;break;case ht:a=o===ae?b.RGBA8UnormSRGB:b.RGBA8Unorm;break;case it:a=b.RGBA16Float;break;case rt:a=b.RGBA32Float;break;default:k("WebGPURenderer: Unsupported texture type with RGBAFormat.",n)}break;case Uo:switch(n){case Sl:a=b.RGB9E5UFloat;break;case Nl:a=b.RG11B10UFloat;break;default:k("WebGPURenderer: Unsupported texture type with RGBFormat.",n)}break;case Fo:switch(n){case Ws:a=b.R8Snorm;break;case js:a=u?b.R16Snorm:b.R16Sint;break;case ds:a=u?b.R16Unorm:b.R16Uint;break;case Ve:a=b.R32Uint;break;case st:a=b.R32Sint;break;case ht:a=b.R8Unorm;break;case it:a=b.R16Float;break;case rt:a=b.R32Float;break;default:k("WebGPURenderer: Unsupported texture type with RedFormat.",n)}break;case Jt:switch(n){case Ws:a=b.RG8Snorm;break;case js:a=u?b.RG16Snorm:b.RG16Sint;break;case ds:a=u?b.RG16Unorm:b.RG16Uint;break;case Ve:a=b.RG32Uint;break;case st:a=b.RG32Sint;break;case ht:a=b.RG8Unorm;break;case it:a=b.RG16Float;break;case rt:a=b.RG32Float;break;default:k("WebGPURenderer: Unsupported texture type with RGFormat.",n)}break;case Tn:switch(n){case ds:a=b.Depth16Unorm;break;case Ve:a=b.Depth24Plus;break;case rt:a=b.Depth32Float;break;default:k("WebGPURenderer: Unsupported texture type with DepthFormat.",n)}break;case vn:switch(n){case Sn:a=b.Depth24PlusStencil8;break;case rt:e&&e.features.has(Mo.Depth32FloatStencil8)===!1&&k('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=b.Depth32FloatStencil8;break;default:k("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",n)}break;case Do:switch(n){case st:a=b.R32Sint;break;case Ve:a=b.R32Uint;break;default:k("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",n)}break;case Lo:switch(n){case st:a=b.RG32Sint;break;case Ve:a=b.RG32Uint;break;default:k("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",n)}break;case Cl:switch(n){case st:a=b.RGBA32Sint;break;case Ve:a=b.RGBA32Uint;break;default:k("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",n)}break;default:k("WebGPURenderer: Unsupported texture format.",t)}return a}const aE=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,uE=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,vh={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"},lE=i=>{i=i.trim();const e=i.match(aE);if(e!==null&&e.length===4){const t=e[2],n=[];let s=null;for(;(s=uE.exec(t))!==null;)n.push({name:s[1],type:s[2]});const r=[];for(let c=0;c<n.length;c++){const{name:d,type:h}=n[c];let f=h;f.startsWith("ptr")?f="pointer":(f.startsWith("texture")&&(f=h.split("<")[0]),f=vh[f]),r.push(new ic(f,d))}const o=i.substring(e[0].length),a=e[3]||"void",u=e[1]!==void 0?e[1]:"";return{type:vh[a]||a,inputs:r,name:u,inputsCode:t,blockCode:o,outputType:a}}else throw new Error("FunctionNode: Function is not a WGSL code.")};class cE extends ac{constructor(e){const{type:t,inputs:n,name:s,inputsCode:r,blockCode:o,outputType:a}=lE(e);super(t,n,s),this.inputsCode=r,this.blockCode=o,this.outputType=a}getCode(e=this.name){const t=this.outputType!=="void"?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class dE extends kg{parseFunction(e){return new cE(e)}}const hE={[Mt.READ_ONLY]:"read",[Mt.WRITE_ONLY]:"write",[Mt.READ_WRITE]:"read_write"},Sh={[Go]:"repeat",[Kr]:"clamp",[ko]:"mirror"},uu={vertex:en.VERTEX,fragment:en.FRAGMENT,compute:en.COMPUTE},Nh={instance:!0,swizzleAssign:!1,storageBuffer:!0},fE={"^^":"tsl_xor"},pE={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},Rh={},Fr={tsl_xor:new Ke("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Ke("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Ke("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Ke("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Ke("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Ke("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Ke("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Ke("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new Ke("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new Ke("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Ke("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new Ke("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Ke(`
|
|
766
|
-
fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
|
|
767
|
-
|
|
768
|
-
let res = vec2f( iRes );
|
|
769
|
-
|
|
770
|
-
let uvScaled = coord * res;
|
|
771
|
-
let uvWrapping = ( ( uvScaled % res ) + res ) % res;
|
|
772
|
-
|
|
773
|
-
// https://www.shadertoy.com/view/WtyXRy
|
|
774
|
-
|
|
775
|
-
let uv = uvWrapping - 0.5;
|
|
776
|
-
let iuv = floor( uv );
|
|
777
|
-
let f = fract( uv );
|
|
778
|
-
|
|
779
|
-
let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
|
|
780
|
-
let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
|
|
781
|
-
let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
|
|
782
|
-
let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
|
|
783
|
-
|
|
784
|
-
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
|
|
785
|
-
|
|
786
|
-
}
|
|
787
|
-
`),biquadraticTextureArray:new Ke(`
|
|
788
|
-
fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
|
|
789
|
-
|
|
790
|
-
let res = vec2f( iRes );
|
|
791
|
-
|
|
792
|
-
let uvScaled = coord * res;
|
|
793
|
-
let uvWrapping = ( ( uvScaled % res ) + res ) % res;
|
|
794
|
-
|
|
795
|
-
// https://www.shadertoy.com/view/WtyXRy
|
|
796
|
-
|
|
797
|
-
let uv = uvWrapping - 0.5;
|
|
798
|
-
let iuv = floor( uv );
|
|
799
|
-
let f = fract( uv );
|
|
800
|
-
|
|
801
|
-
let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
|
|
802
|
-
let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
|
|
803
|
-
let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
|
|
804
|
-
let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
|
|
805
|
-
|
|
806
|
-
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
|
|
807
|
-
|
|
808
|
-
}
|
|
809
|
-
`)},gE={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let Yg="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(Yg+=`diagnostic( off, derivative_uniformity );
|
|
810
|
-
`);class mE extends Ig{constructor(e,t){super(e,t,new dE),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,n,s,r,o=this.shaderStage){return o==="fragment"?s?r?`textureSample( ${t}, ${t}_sampler, ${n}, ${s}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${s} )`:r?`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",s)}generateTextureSampleLevel(e,t,n,s,r,o){return this.isUnfilterable(e)===!1?r?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${s}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,s,r):this.generateTextureLod(e,t,n,r,o,s)}generateWrapFunction(e){const t=`tsl_coord_${Sh[e.wrapS]}S_${Sh[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let n=Rh[t];if(n===void 0){const s=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let o=`fn ${t}( coord : ${r} ) -> ${r} {
|
|
811
|
-
|
|
812
|
-
return ${r}(
|
|
813
|
-
`;const a=(u,l)=>{u===Go?(s.push(Fr.repeatWrapping_float),o+=` tsl_repeatWrapping_float( coord.${l} )`):u===Kr?(s.push(Fr.clampWrapping_float),o+=` tsl_clampWrapping_float( coord.${l} )`):u===ko?(s.push(Fr.mirrorWrapping_float),o+=` tsl_mirrorWrapping_float( coord.${l} )`):(o+=` coord.${l}`,z(`WebGPURenderer: Unsupported texture wrap type "${u}" for vertex shader.`))};a(e.wrapS,"x"),o+=`,
|
|
814
|
-
`,a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(o+=`,
|
|
815
|
-
`,a(e.wrapR,"z")),o+=`
|
|
816
|
-
);
|
|
817
|
-
|
|
818
|
-
}
|
|
819
|
-
`,Rh[t]=n=new Ke(o,s)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const s=this.getDataFromNode(e,this.shaderStage,this.cache);s.dimensionsSnippet===void 0&&(s.dimensionsSnippet={});let r=s.dimensionsSnippet[n];if(s.dimensionsSnippet[n]===void 0){let o,a;const{primarySamples:u}=this.renderer.backend.utils.getTextureSampleData(e),l=u>1;e.is3DTexture||e.isData3DTexture?a="vec3<u32>":a="vec2<u32>",l||e.isStorageTexture?o=t:o=`${t}${n?`, u32( ${n} )`:""}`,r=new ro(new io(`textureDimensions( ${o} )`,a)),s.dimensionsSnippet[n]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(s.arrayLayerCount=new ro(new io(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new ro(new io("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,n,s,r="0u",o){const a=this.generateWrapFunction(e),u=this.generateTextureDimension(e,t,r);return s&&(n=`${n} + vec2<f32>(${s}) / ${u}`),o?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${n} ), ${u}, u32( ${o} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${n} ), ${u}, u32( ${r} ) )`)}generateTextureLod(e,t,n,s,r,o="0u"){if(e.isCubeTexture===!0){r&&(n=`${n} + vec3<f32>(${r})`);const f=e.isDepthTexture?"u32":"f32";return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${f}( ${o} ) )`}const a=this.generateWrapFunction(e),u=this.generateTextureDimension(e,t,o),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",c=l==="vec3"?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )";r&&(n=`${n} + ${l}<f32>(${r}) / ${l}<f32>( ${u} )`);const d=`${l}<f32>( 0 )`,h=`${l}<f32>( ${u} - ${c} )`;return n=`${l}<u32>( clamp( floor( ${a}( ${n} ) * ${l}<f32>( ${u} ) ), ${d}, ${h} ) )`,this.generateTextureLoad(e,t,n,o,s,null)}generateStorageTextureLoad(e,t,n,s,r,o){o&&(n=`${n} + ${o}`);let a;return r?a=`textureLoad( ${t}, ${n}, ${r} )`:a=`textureLoad( ${t}, ${n} )`,a}generateTextureLoad(e,t,n,s,r,o){s===null&&(s="0u"),o&&(n=`${n} + ${o}`);let a;return r?a=`textureLoad( ${t}, ${n}, ${r}, u32( ${s} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,n,s,r){let o;return s?o=`textureStore( ${t}, ${n}, ${s}, ${r} )`:o=`textureStore( ${t}, ${n}, ${r} )`,o}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null&&this.renderer.hasCompatibility(Ns.TEXTURE_COMPARE)}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.type===rt||this.isSampleCompare(e)===!1&&e.minFilter===xt&&e.magFilter===xt||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,s,r,o=this.shaderStage){let a=null;return this.isUnfilterable(e)?a=this.generateTextureLod(e,t,n,s,r,"0",o):a=this._generateTextureSample(e,t,n,s,r,o),a}generateTextureGrad(e,t,n,s,r,o,a=this.shaderStage){if(a==="fragment")return r?o?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${s[0]}, ${s[1]}, ${o} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${s[0]}, ${s[1]} )`:o?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s[0]}, ${s[1]}, ${o} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s[0]}, ${s[1]} )`;k(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,s,r,o,a=this.shaderStage){if(a==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${s}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s} )`;k(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,n,s,r,o){return this.isUnfilterable(e)===!1?r?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${s}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,s,r):this.generateTextureLod(e,t,n,r,o,s)}generateTextureBias(e,t,n,s,r,o,a=this.shaderStage){if(a==="fragment")return r?o?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${s}, ${o} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:o?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s}, ${o} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s} )`;k(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(e.isNodeVarying===!0&&e.needsInterpolation===!0){if(t==="vertex")return`varyings.${e.name}`}else if(e.isNodeUniform===!0){const n=e.name,s=e.type;return s==="texture"||s==="cubeTexture"||s==="cubeDepthTexture"||s==="storageTexture"||s==="texture3D"?n:s==="buffer"||s==="storageBuffer"||s==="indirectStorageBuffer"?this.isCustomStruct(e)?n:n+".value":e.groupNode.name+"."+n}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=fE[e];return t!==void 0?(this._include(t),t):null}getNodeAccess(e,t){return t!=="compute"?e.isAtomic===!0?(z("WebGPURenderer: Atomic operations are only supported in compute shaders."),Mt.READ_WRITE):Mt.READ_ONLY:e.access}getStorageAccess(e,t){return hE[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,s=null){const r=super.getUniformFromNode(e,t,n,s),o=this.getDataFromNode(e,n,this.globalCache);if(o.uniformGPU===void 0){let a;const u=e.groupNode,l=u.name,c=this.getBindGroupArray(l,n);if(t==="texture"||t==="cubeTexture"||t==="cubeDepthTexture"||t==="storageTexture"||t==="texture3D"){let d=null;const h=this.getNodeAccess(e,n);if(t==="texture"||t==="storageTexture"?e.value.is3DTexture===!0?d=new dl(r.name,r.node,u,h):d=new ta(r.name,r.node,u,h):t==="cubeTexture"||t==="cubeDepthTexture"?d=new Hg(r.name,r.node,u,h):t==="texture3D"&&(d=new dl(r.name,r.node,u,h)),d.store=e.isStorageTextureNode===!0,d.mipLevel=d.store?e.mipLevel:0,d.setVisibility(uu[n]),e.value.isCubeTexture===!0||this.isUnfilterable(e.value)===!1&&d.store===!1){const p=new Jw(`${r.name}_sampler`,r.node,u);p.setVisibility(uu[n]),c.push(p,d),a=[p,d]}else c.push(d),a=[d]}else if(t==="buffer"||t==="storageBuffer"||t==="indirectStorageBuffer"){const d=this.getSharedDataFromNode(e);let h=d.buffer;if(h===void 0){const f=t==="buffer"?Wg:nE;h=new f(e,u),d.buffer=h}h.setVisibility(h.getVisibility()|uu[n]),c.push(h),a=h,r.name=s||"NodeBuffer_"+r.id}else{let d=this.uniformGroups[l];d===void 0&&(d=new jg(l,u),d.setVisibility(en.VERTEX|en.FRAGMENT|en.COMPUTE),this.uniformGroups[l]=d),c.indexOf(d)===-1&&c.push(d),a=this.getNodeUniform(r,t);const h=a.name;d.uniforms.some(p=>p.name===h)||d.addUniform(a)}o.uniformGPU=a}return r}getBuiltin(e,t,n,s=this.shaderStage){const r=this.builtins[s]||(this.builtins[s]=new Map);return r.has(e)===!1&&r.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return this.builtins[t]!==void 0&&this.builtins[t].has(e)}getVertexIndex(){return this.shaderStage==="vertex"?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),s=[];for(const o of t.inputs)s.push(o.name+" : "+this.getType(o.type));let r=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {
|
|
820
|
-
${n.vars}
|
|
821
|
-
${n.code}
|
|
822
|
-
`;return n.result&&(r+=` return ${n.result};
|
|
823
|
-
`),r+=`
|
|
824
|
-
}
|
|
825
|
-
`,r}getInstanceIndex(){return this.shaderStage==="vertex"?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],n=this.directives[e];if(n!==void 0)for(const s of n)t.push(`enable ${s};`);return t.join(`
|
|
826
|
-
`)}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],n=this.builtins[e];if(n!==void 0)for(const{name:s,property:r,type:o}of n.values())t.push(`@builtin( ${s} ) ${r} : ${o}`);return t.join(`,
|
|
827
|
-
`)}getScopedArray(e,t,n,s){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:s}),e}getScopedArrays(e){if(e!=="compute")return;const t=[];for(const{name:n,scope:s,bufferType:r,bufferCount:o}of this.scopedArrays.values()){const a=this.getType(r);t.push(`var<${s}> ${n}: array< ${a}, ${o} >;`)}return t.join(`
|
|
828
|
-
`)}getAttributes(e){const t=[];if(e==="compute"&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),e==="vertex"||e==="compute"){const n=this.getBuiltins("attribute");n&&t.push(n);const s=this.getAttributesArray();for(let r=0,o=s.length;r<o;r++){const a=s[r],u=a.name,l=this.getType(a.type);t.push(`@location( ${r} ) ${u} : ${l}`)}}return t.join(`,
|
|
829
|
-
`)}getStructMembers(e){const t=[];for(const n of e.members){const s=e.output?"@location( "+n.index+" ) ":"";let r=this.getType(n.type);n.atomic&&(r="atomic< "+r+" >"),t.push(` ${s+n.name} : ${r}`)}return e.output&&t.push(` ${this.getBuiltins("output")}`),t.join(`,
|
|
830
|
-
`)}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const s=[];for(const r of n){let o=`struct ${r.name} {
|
|
831
|
-
`;o+=this.getStructMembers(r),o+=`
|
|
832
|
-
};`,s.push(o)}t=`
|
|
833
|
-
`+s.join(`
|
|
834
|
-
|
|
835
|
-
`)+`
|
|
836
|
-
`}return t}getVar(e,t,n=null,s=""){let r=`var${s} ${t} : `;return n!==null?r+=this.generateArrayDeclaration(e,n):r+=this.getType(e),r}getVars(e,t=!1){let n="";t&&(n="<private>");const s=[],r=this.vars[e];if(r!==void 0)for(const o of r)s.push(`${this.getVar(o.type,o.name,o.count,n)};`);return t?s.join(`
|
|
837
|
-
`):`
|
|
838
|
-
${s.join(`
|
|
839
|
-
`)}
|
|
840
|
-
`}getVaryings(e){const t=[];if(e==="vertex"&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),e==="vertex"||e==="fragment"){const r=this.varyings,o=this.vars[e];let a=0;for(let u=0;u<r.length;u++){const l=r[u];if(l.needsInterpolation){let c=`@location( ${a++} )`;if(l.interpolationType){const d=l.interpolationSampling!==null?`, ${l.interpolationSampling} )`:" )";c+=` @interpolate( ${l.interpolationType}${d}`}else/^(int|uint|ivec|uvec)/.test(l.type)&&(c+=" @interpolate(flat, either)");t.push(`${c} ${l.name} : ${this.getType(l.type)}`)}else e==="vertex"&&o.includes(l)===!1&&o.push(l)}}const n=this.getBuiltins(e);n&&t.push(n);const s=t.join(`,
|
|
841
|
-
`);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+s):s}isCustomStruct(e){const t=e.value,n=e.node,s=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&n.structTypeNode!==null,r=n.value&&n.value.array&&typeof n.value.itemSize=="number"&&n.value.array.length>n.value.itemSize;return s&&!r}getUniforms(e){const t=this.renderer.backend,n=this.uniforms[e],s=[],r=[],o=[],a={};for(const l of n){const c=l.groupNode.name,d=this.bindingsIndexes[c];if(l.type==="texture"||l.type==="cubeTexture"||l.type==="cubeDepthTexture"||l.type==="storageTexture"||l.type==="texture3D"){const h=l.node.value;(h.isCubeTexture===!0||this.isUnfilterable(h)===!1&&l.node.isStorageTextureNode!==!0)&&(this.isSampleCompare(h)?s.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var ${l.name}_sampler : sampler_comparison;`):s.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var ${l.name}_sampler : sampler;`));let p,g="";const{primarySamples:m}=t.utils.getTextureSampleData(h);if(m>1&&(g="_multisampled"),h.isCubeTexture===!0&&h.isDepthTexture===!0)p="texture_depth_cube";else if(h.isCubeTexture===!0)p="texture_cube<f32>";else if(h.isDepthTexture===!0)t.compatibilityMode&&h.compareFunction===null?p=`texture${g}_2d<f32>`:p=`texture_depth${g}_2d${h.isArrayTexture===!0?"_array":""}`;else if(l.node.isStorageTextureNode===!0){const y=hl(h,t.device),_=this.getStorageAccess(l.node,e),T=l.node.value.is3DTexture,S=l.node.value.isArrayTexture;p=`texture_storage_${T?"3d":`2d${S?"_array":""}`}<${y}, ${_}>`}else if(h.isArrayTexture===!0||h.isDataArrayTexture===!0||h.isCompressedArrayTexture===!0)p="texture_2d_array<f32>";else if(h.is3DTexture===!0||h.isData3DTexture===!0)p="texture_3d<f32>";else{const y=this.getComponentTypeFromTexture(h).charAt(0);p=`texture${g}_2d<${y}32>`}s.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var ${l.name} : ${p};`)}else if(l.type==="buffer"||l.type==="storageBuffer"||l.type==="indirectStorageBuffer"){const h=l.node,f=this.getType(h.getNodeType(this)),p=h.bufferCount,g=p>0&&l.type==="buffer"?", "+p:"",m=h.isStorageBufferNode?`storage, ${this.getStorageAccess(h,e)}`:"uniform";if(this.isCustomStruct(l))r.push(`@binding( ${d.binding++} ) @group( ${d.group} ) var<${m}> ${l.name} : ${f};`);else{const _=` value : array< ${h.isAtomic?`atomic<${f}>`:`${f}`}${g} >`;r.push(this._getWGSLStructBinding(l.name,_,m,d.binding++,d.group))}}else{const h=l.groupNode.name;if(a[h]===void 0){const f=this.uniformGroups[h];if(f!==void 0){const p=[];for(const m of f.uniforms){const y=m.getType(),_=this.getType(this.getVectorType(y));p.push(` ${m.name} : ${_}`)}let g=this.uniformGroupsBindings[h];g===void 0&&(g={index:d.binding++,id:d.group},this.uniformGroupsBindings[h]=g),a[h]={index:g.index,id:g.id,snippets:p}}}}}for(const l in a){const c=a[l];o.push(this._getWGSLStructBinding(l,c.snippets.join(`,
|
|
842
|
-
`),"uniform",c.index,c.id))}return[...s,...r,...o].join(`
|
|
843
|
-
`)}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=this.allowGlobalVariables,s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t,n),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let r=`// code
|
|
844
|
-
|
|
845
|
-
`;r+=this.flowCode[t];const o=this.flowNodes[t],a=o[o.length-1],u=a.outputNode,l=u!==void 0&&u.isOutputStructNode===!0;for(const c of o){const d=this.getFlowData(c),h=c.name;if(h&&(r.length>0&&(r+=`
|
|
846
|
-
`),r+=` // flow -> ${h}
|
|
847
|
-
`),r+=`${d.code}
|
|
848
|
-
`,c===a&&t!=="compute"){if(r+=`// result
|
|
849
|
-
|
|
850
|
-
`,t==="vertex")r+=`varyings.builtinClipSpace = ${d.result};`;else if(t==="fragment")if(l)s.returnType=u.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",r+=`return ${d.result};`;else{let f=" @location( 0 ) color: vec4<f32>";const p=this.getBuiltins("output");p&&(f+=`,
|
|
851
|
-
`+p),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",f),s.structs+=`
|
|
852
|
-
var<private> output : OutputStruct;`,r+=`output.color = ${d.result};
|
|
853
|
-
|
|
854
|
-
return output;`}}}s.flow=r}if(this.shaderStage=null,this.material!==null)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return t!==null&&(n=this._getWGSLMethod(e+"_"+t)),n===void 0&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return pE[e]||e}isAvailable(e){let t=Nh[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),Nh[e]=t),t}_getWGSLMethod(e){return Fr[e]!==void 0&&this._include(e),gE[e]}_include(e){const t=Fr[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}
|
|
855
|
-
// directives
|
|
856
|
-
${e.directives}
|
|
857
|
-
|
|
858
|
-
// structs
|
|
859
|
-
${e.structs}
|
|
860
|
-
|
|
861
|
-
// uniforms
|
|
862
|
-
${e.uniforms}
|
|
863
|
-
|
|
864
|
-
// varyings
|
|
865
|
-
${e.varyings}
|
|
866
|
-
var<private> varyings : VaryingsStruct;
|
|
867
|
-
|
|
868
|
-
// vars
|
|
869
|
-
${e.vars}
|
|
870
|
-
|
|
871
|
-
// codes
|
|
872
|
-
${e.codes}
|
|
873
|
-
|
|
874
|
-
@vertex
|
|
875
|
-
fn main( ${e.attributes} ) -> VaryingsStruct {
|
|
876
|
-
|
|
877
|
-
// flow
|
|
878
|
-
${e.flow}
|
|
879
|
-
|
|
880
|
-
return varyings;
|
|
881
|
-
|
|
882
|
-
}
|
|
883
|
-
`}_getWGSLFragmentCode(e){return`${this.getSignature()}
|
|
884
|
-
// global
|
|
885
|
-
${Yg}
|
|
886
|
-
|
|
887
|
-
// structs
|
|
888
|
-
${e.structs}
|
|
889
|
-
|
|
890
|
-
// uniforms
|
|
891
|
-
${e.uniforms}
|
|
892
|
-
|
|
893
|
-
// vars
|
|
894
|
-
${e.vars}
|
|
895
|
-
|
|
896
|
-
// codes
|
|
897
|
-
${e.codes}
|
|
898
|
-
|
|
899
|
-
@fragment
|
|
900
|
-
fn main( ${e.varyings} ) -> ${e.returnType} {
|
|
901
|
-
|
|
902
|
-
// flow
|
|
903
|
-
${e.flow}
|
|
904
|
-
|
|
905
|
-
}
|
|
906
|
-
`}_getWGSLComputeCode(e,t){const[n,s,r]=t;return`${this.getSignature()}
|
|
907
|
-
// directives
|
|
908
|
-
${e.directives}
|
|
909
|
-
|
|
910
|
-
// system
|
|
911
|
-
var<private> instanceIndex : u32;
|
|
912
|
-
|
|
913
|
-
// locals
|
|
914
|
-
${e.scopedArrays}
|
|
915
|
-
|
|
916
|
-
// structs
|
|
917
|
-
${e.structs}
|
|
918
|
-
|
|
919
|
-
// uniforms
|
|
920
|
-
${e.uniforms}
|
|
921
|
-
|
|
922
|
-
// vars
|
|
923
|
-
${this.allowGlobalVariables?e.vars:""}
|
|
924
|
-
|
|
925
|
-
// codes
|
|
926
|
-
${e.codes}
|
|
927
|
-
|
|
928
|
-
@compute @workgroup_size( ${n}, ${s}, ${r} )
|
|
929
|
-
fn main( ${e.attributes} ) {
|
|
930
|
-
|
|
931
|
-
// local vars
|
|
932
|
-
${this.allowGlobalVariables?"":e.vars}
|
|
933
|
-
|
|
934
|
-
// system
|
|
935
|
-
instanceIndex = globalId.x
|
|
936
|
-
+ globalId.y * ( ${n} * numWorkgroups.x )
|
|
937
|
-
+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${s} * numWorkgroups.y );
|
|
938
|
-
|
|
939
|
-
// flow
|
|
940
|
-
${e.flow}
|
|
941
|
-
|
|
942
|
-
}
|
|
943
|
-
`}_getWGSLStruct(e,t){return`
|
|
944
|
-
struct ${e} {
|
|
945
|
-
${t}
|
|
946
|
-
};`}_getWGSLStructBinding(e,t,n,s=0,r=0){const o=e+"Struct";return`${this._getWGSLStruct(o,t)}
|
|
947
|
-
@binding( ${s} ) @group( ${r} )
|
|
948
|
-
var<${n}> ${e} : ${o};`}}class yE{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.stencil?this.backend.renderer.reversedDepthBuffer===!0?t=b.Depth32FloatStencil8:t=b.Depth24PlusStencil8:this.backend.renderer.reversedDepthBuffer===!0?t=b.Depth32Float:t=b.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const r=this.backend.renderer,o=r.getRenderTarget();t=o?o.samples:r.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return e.textures!==null?t=this.getTextureFormatGPU(e.textures[0]):t=this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return e.textures!==null?e.textures.map(t=>this.getTextureFormatGPU(t)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return $i.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return $i.LineList;if(e.isLine)return $i.LineStrip;if(e.isMesh)return $i.TriangleList}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const t=this.backend.parameters.outputType;if(t===void 0)return navigator.gpu.getPreferredCanvasFormat();if(t===ht)return b.BGRA8Unorm;if(t===it)return b.RGBA16Float;throw new Error("Unsupported output buffer type.")}}const Qg=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);typeof Float16Array<"u"&&Qg.set(Float16Array,["float16"]);const bE=new Map([[Rf,["float16"]]]),_E=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class xE{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),s=this.backend,r=s.get(n);let o=r.buffer;if(o===void 0){const a=s.device;let u=n.array;if(e.normalized===!1){if(u.constructor===Int16Array||u.constructor===Int8Array)u=new Int32Array(u);else if((u.constructor===Uint16Array||u.constructor===Uint8Array)&&(u=new Uint32Array(u),t&GPUBufferUsage.INDEX))for(let d=0;d<u.length;d++)u[d]===65535&&(u[d]=4294967295)}if(n.array=u,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&n.itemSize===3){u=new u.constructor(n.count*4);for(let d=0;d<n.count;d++)u.set(n.array.subarray(d*3,d*3+3),d*4);n.itemSize=4,n.array=u,r._force3to4BytesAlignment=!0}const l=u.byteLength,c=l+(4-l%4)%4;o=a.createBuffer({label:n.name,size:c,usage:t,mappedAtCreation:!0}),new u.constructor(o.getMappedRange()).set(u),o.unmap(),r.buffer=o}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,s=n.device,r=n.get(t),o=n.get(t).buffer;let a=t.array;if(r._force3to4BytesAlignment===!0){a=new a.constructor(t.count*4);for(let l=0;l<t.count;l++)a.set(t.array.subarray(l*3,l*3+3),l*4);t.array=a}const u=t.updateRanges;if(u.length===0)s.queue.writeBuffer(o,0,a,0);else{const l=co(a),c=l?1:a.BYTES_PER_ELEMENT;for(let d=0,h=u.length;d<h;d++){const f=u[d];let p,g;if(r._force3to4BytesAlignment===!0){const y=Math.floor(f.start/3),_=Math.ceil(f.count/3);p=y*4*c,g=_*4*c}else p=f.start*c,g=f.count*c;const m=p*(l?a.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(o,m,a,p,g)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let s=0;s<t.length;s++){const r=t[s],o=r.array.BYTES_PER_ELEMENT,a=this._getBufferAttribute(r);let u=n.get(a);if(u===void 0){let d,h;r.isInterleavedBufferAttribute===!0?(d=r.data.stride*o,h=r.data.isInstancedInterleavedBuffer?zi.Instance:zi.Vertex):(d=r.itemSize*o,h=r.isInstancedBufferAttribute?zi.Instance:zi.Vertex),r.normalized===!1&&(r.array.constructor===Int16Array||r.array.constructor===Uint16Array)&&(d=4),u={arrayStride:d,attributes:[],stepMode:h},n.set(a,u)}const l=this._getVertexFormat(r),c=r.isInterleavedBufferAttribute===!0?r.offset*o:0;u.attributes.push({shaderLocation:s,offset:c,format:l})}return Array.from(n.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,s=-1){const r=this.backend,o=r.device,u=r.get(this._getBufferAttribute(e)).buffer,l=s===-1?u.size-n:s;let c;if(t!==null&&t.isReadbackBuffer){const f=r.get(t);if(t._mapped===!0)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,f.readBufferGPU===void 0){c=o.createBuffer({label:`${t.name}_readback`,size:t.maxByteLength,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const p=()=>{t.buffer=null,t._mapped=!1,c.unmap()},g=()=>{t.buffer=null,t._mapped=!1,c.destroy(),r.delete(t),t.removeEventListener("release",p),t.removeEventListener("dispose",g)};t.addEventListener("release",p),t.addEventListener("dispose",g),f.readBufferGPU=c}else c=f.readBufferGPU}else c=o.createBuffer({label:`${e.name}_readback`,size:l,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const d=o.createCommandEncoder({label:`readback_encoder_${e.name}`});d.copyBufferToBuffer(u,n,c,0,l);const h=d.finish();if(o.queue.submit([h]),await c.mapAsync(GPUMapMode.READ,0,l),t===null){const p=c.getMappedRange(0,l).slice();return c.destroy(),p}else{if(t.isReadbackBuffer)return t.buffer=c.getMappedRange(0,l),t;{const f=c.getMappedRange(0,l);return new Uint8Array(t).set(new Uint8Array(f)),c.destroy(),t}}}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,s=e.array.constructor,r=e.constructor;let o;if(t===1)o=_E.get(s);else{const u=(bE.get(r)||Qg.get(s))[n?1:0];if(u){const l=s.BYTES_PER_ELEMENT*t,d=Math.floor((l+3)/4)*4/s.BYTES_PER_ELEMENT;if(d%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");o=`${u}x${d}`}}return o||k("WebGPUAttributeUtils: Vertex format not supported yet."),o}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class TE{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class vE{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,n=t.device,s=t.get(e);if(s.layout)return s.layout.layoutGPU;const r=this._createLayoutEntries(e),o=ur(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(o);return a===void 0&&(a=new TE(n.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(o,a)),a.usedTimes++,s.layout=a,s.layoutKey=o,a.layoutGPU}createBindings(e,t,n,s=0){const{backend:r}=this,o=r.get(e),a=this.createBindingsLayout(e);let u;n>0&&(o.groups===void 0&&(o.groups=[],o.versions=[]),o.versions[n]===s&&(u=o.groups[n])),u===void 0&&(u=this.createBindGroup(e,a),n>0&&(o.groups[n]=u,o.versions[n]=s)),o.group=u}updateBinding(e){const t=this.backend,n=t.device,s=e.buffer,r=t.get(e).buffer,o=e.updateRanges;if(o.length===0)n.queue.writeBuffer(r,0,s,0);else{const a=co(s),u=a?1:s.BYTES_PER_ELEMENT;for(let l=0,c=o.length;l<c;l++){const d=o[l],h=d.start*u,f=d.count*u,p=h*(a?s.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(r,p,s,h,f)}}}createBindGroupIndex(e,t){const s=this.backend.device,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,o=e[0],a=s.createBuffer({label:"bindingCameraIndex_"+o,size:16,usage:r});s.queue.writeBuffer(a,0,e,0);const u=[{binding:0,resource:{buffer:a}}];return s.createBindGroup({label:"bindGroupCameraIndex_"+o,layout:t,entries:u})}createBindGroup(e,t){const n=this.backend,s=n.device;let r=0;const o=[];for(const a of e.bindings){if(a.isUniformBuffer){const u=n.get(a);if(u.buffer===void 0){const l=a.byteLength,c=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,d=[];a.visibility&en.VERTEX&&d.push("vertex"),a.visibility&en.FRAGMENT&&d.push("fragment"),a.visibility&en.COMPUTE&&d.push("compute");const h=`(${d.join(",")})`,f=s.createBuffer({label:`bindingBuffer${a.id}_${a.name}_${h}`,size:l,usage:c});u.buffer=f}o.push({binding:r,resource:{buffer:u.buffer}})}else if(a.isStorageBuffer){const u=n.get(a.attribute).buffer;o.push({binding:r,resource:{buffer:u}})}else if(a.isSampledTexture){const u=n.get(a.texture);let l;if(u.externalTexture!==void 0)l=s.importExternalTexture({source:u.externalTexture});else{const c=a.store?1:u.texture.mipLevelCount,d=a.store?a.mipLevel:0;let h=`view-${u.texture.width}-${u.texture.height}`;if(u.texture.depthOrArrayLayers>1&&(h+=`-${u.texture.depthOrArrayLayers}`),h+=`-${c}-${d}`,l=u[h],l===void 0){const f=Zw.All;let p;a.isSampledCubeTexture?p=tt.Cube:a.isSampledTexture3D?p=tt.ThreeD:a.texture.isArrayTexture||a.texture.isDataArrayTexture||a.texture.isCompressedArrayTexture?p=tt.TwoDArray:p=tt.TwoD,l=u[h]=u.texture.createView({aspect:f,dimension:p,mipLevelCount:c,baseMipLevel:d})}}o.push({binding:r,resource:l})}else if(a.isSampler){const u=n.get(a.texture);o.push({binding:r,resource:u.sampler})}r++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:o})}_createLayoutEntries(e){const t=[];let n=0;for(const s of e.bindings){const r=this.backend,o={binding:n,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const a={};s.isStorageBuffer&&(s.visibility&en.COMPUTE&&(s.access===Mt.READ_WRITE||s.access===Mt.WRITE_ONLY)?a.type=ou.Storage:a.type=ou.ReadOnlyStorage),o.buffer=a}else if(s.isSampledTexture&&s.store){const a={};a.format=this.backend.get(s.texture).texture.format;const u=s.access;u===Mt.READ_WRITE?a.access=au.ReadWrite:u===Mt.WRITE_ONLY?a.access=au.WriteOnly:a.access=au.ReadOnly,s.texture.isArrayTexture?a.viewDimension=tt.TwoDArray:s.texture.is3DTexture&&(a.viewDimension=tt.ThreeD),o.storageTexture=a}else if(s.isSampledTexture){const a={},{primarySamples:u}=r.utils.getTextureSampleData(s.texture);if(u>1&&(a.multisampled=!0,s.texture.isDepthTexture||(a.sampleType=ts.UnfilterableFloat)),s.texture.isDepthTexture)r.compatibilityMode&&s.texture.compareFunction===null?a.sampleType=ts.UnfilterableFloat:a.sampleType=ts.Depth;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture||s.texture.isStorageTexture){const l=s.texture.type;l===st?a.sampleType=ts.SInt:l===Ve?a.sampleType=ts.UInt:l===rt&&(this.backend.hasFeature("float32-filterable")?a.sampleType=ts.Float:a.sampleType=ts.UnfilterableFloat)}s.isSampledCubeTexture?a.viewDimension=tt.Cube:s.texture.isArrayTexture||s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?a.viewDimension=tt.TwoDArray:s.isSampledTexture3D&&(a.viewDimension=tt.ThreeD),o.texture=a}else if(s.isSampler){const a={};s.texture.isDepthTexture&&(s.texture.compareFunction!==null&&r.hasCompatibility(Ns.TEXTURE_COMPARE)?a.type=_h.Comparison:a.type=_h.NonFiltering),o.sampler=a}else k(`WebGPUBindingUtils: Unsupported binding "${s}".`);t.push(o),n++}return t}deleteBindGroupData(e){const{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,n.layout.usedTimes===0&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class SE{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class NE{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:n,material:s,geometry:r,pipeline:o}=e,{vertexProgram:a,fragmentProgram:u}=o,l=this.backend,c=l.device,d=l.utils,h=l.get(o),f=[];for(const re of e.getBindings()){const se=l.get(re),{layoutGPU:Z}=se.layout;f.push(Z)}const p=l.attributeUtils.createShaderVertexBuffers(e);let g;s.blending!==Nn&&(s.blending!==gn||s.transparent!==!1)&&(g=this._getBlending(s));let m={};s.stencilWrite===!0&&(m={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const y=this._getColorWriteMask(s),_=[];if(e.context.textures!==null){const re=e.context.textures,se=e.context.mrt;for(let Z=0;Z<re.length;Z++){const oe=re[Z],F=d.getTextureFormatGPU(oe);let G;if(se!==null)if(this.backend.compatibilityMode!==!0){const Q=se.getBlendMode(oe.name);Q.blending===pf?G=g:Q.blending!==Nn&&(G=this._getBlending(Q))}else Oe("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),G=g;else G=g;_.push({format:F,blend:G,writeMask:y})}}else{const re=d.getCurrentColorFormat(e.context);_.push({format:re,blend:g,writeMask:y})}const T=l.get(a).module,S=l.get(u).module,N=this._getPrimitiveState(n,r,s),R=this._getDepthCompare(s),v=d.getCurrentDepthStencilFormat(e.context),P=this._getSampleCount(e.context),D={label:`renderPipeline_${s.name||s.type}_${s.id}`,vertex:Object.assign({},T,{buffers:p}),fragment:Object.assign({},S,{targets:_}),primitive:N,multisample:{count:P,alphaToCoverageEnabled:s.alphaToCoverage&&P>1},layout:c.createPipelineLayout({bindGroupLayouts:f})},L={},j=e.context.depth,ee=e.context.stencil;if((j===!0||ee===!0)&&(j===!0&&(L.format=v,L.depthWriteEnabled=s.depthWrite,L.depthCompare=R),ee===!0&&(L.stencilFront=m,L.stencilBack=m,L.stencilReadMask=s.stencilFuncMask,L.stencilWriteMask=s.stencilWriteMask),s.polygonOffset===!0&&(L.depthBias=s.polygonOffsetUnits,L.depthBiasSlopeScale=s.polygonOffsetFactor,L.depthBiasClamp=0),D.depthStencil=L),c.pushErrorScope("validation"),t===null)h.pipeline=c.createRenderPipeline(D),c.popErrorScope().then(re=>{re!==null&&(h.error=!0,k(re.message))});else{const re=new Promise(async se=>{try{h.pipeline=await c.createRenderPipelineAsync(D)}catch{}const Z=await c.popErrorScope();Z!==null&&(h.error=!0,k(Z.message)),se()});t.push(re)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:s,device:r}=n,o=s.getCurrentDepthStencilFormat(e),a=s.getCurrentColorFormats(e),u=this._getSampleCount(e),l={label:t,colorFormats:a,depthStencilFormat:o,sampleCount:u};return r.createRenderBundleEncoder(l)}createComputePipeline(e,t){const n=this.backend,s=n.device,r=n.get(e.computeProgram).module,o=n.get(e),a=[];for(const u of t){const l=n.get(u),{layoutGPU:c}=l.layout;a.push(c)}o.pipeline=s.createComputePipeline({compute:r,layout:s.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const s=e.blending,r=e.blendSrc,o=e.blendDst,a=e.blendEquation;if(s===qs){const u=e.blendSrcAlpha!==null?e.blendSrcAlpha:r,l=e.blendDstAlpha!==null?e.blendDstAlpha:o,c=e.blendEquationAlpha!==null?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(u),dstFactor:this._getBlendFactor(l),operation:this._getBlendOperation(c)}}else{const u=e.premultipliedAlpha,l=(c,d,h,f)=>{t={srcFactor:c,dstFactor:d,operation:es.Add},n={srcFactor:h,dstFactor:f,operation:es.Add}};if(u)switch(s){case gn:l(he.One,he.OneMinusSrcAlpha,he.One,he.OneMinusSrcAlpha);break;case Vs:l(he.One,he.One,he.One,he.One);break;case Gs:l(he.Zero,he.OneMinusSrc,he.Zero,he.One);break;case ks:l(he.Dst,he.OneMinusSrcAlpha,he.Zero,he.One);break}else switch(s){case gn:l(he.SrcAlpha,he.OneMinusSrcAlpha,he.One,he.OneMinusSrcAlpha);break;case Vs:l(he.SrcAlpha,he.One,he.One,he.One);break;case Gs:k(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case ks:k(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break}}if(t!==void 0&&n!==void 0)return{color:t,alpha:n};k("WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Un:t=he.Zero;break;case ff:t=he.One;break;case hf:t=he.Src;break;case af:t=he.OneMinusSrc;break;case df:t=he.SrcAlpha;break;case of:t=he.OneMinusSrcAlpha;break;case lf:t=he.Dst;break;case rf:t=he.OneMinusDst;break;case uf:t=he.DstAlpha;break;case sf:t=he.OneMinusDstAlpha;break;case cf:t=he.SrcAlphaSaturated;break;case iN:t=he.Constant;break;case oN:t=he.OneMinusConstant;break;default:k("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case ny:t=Ye.Never;break;case ty:t=Ye.Always;break;case ey:t=Ye.Less;break;case Jm:t=Ye.LessEqual;break;case Zm:t=Ye.Equal;break;case Qm:t=Ye.GreaterEqual;break;case Ym:t=Ye.Greater;break;case Km:t=Ye.NotEqual;break;default:k("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case cy:t=Dn.Keep;break;case ly:t=Dn.Zero;break;case uy:t=Dn.Replace;break;case ay:t=Dn.Invert;break;case oy:t=Dn.IncrementClamp;break;case iy:t=Dn.DecrementClamp;break;case ry:t=Dn.IncrementWrap;break;case sy:t=Dn.DecrementWrap;break;default:k("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case pn:t=es.Add;break;case nf:t=es.Subtract;break;case tf:t=es.ReverseSubtract;break;case hy:t=es.Min;break;case dy:t=es.Max;break;default:k("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const s={},r=this.backend.utils;s.topology=r.getPrimitiveTopology(e,n),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?Co.Uint16:Co.Uint32);let o=n.side===ot;return e.isMesh&&e.matrixWorld.determinant()<0&&(o=!o),s.frontFace=o===!0?mh.CW:mh.CCW,s.cullMode=n.side===xn?yh.None:yh.Back,s}_getColorWriteMask(e){return e.colorWrite===!0?bh.All:bh.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=Ye.Always;else{const n=this.backend.parameters.reversedDepthBuffer?Nf[e.depthFunc]:e.depthFunc;switch(n){case vf:t=Ye.Never;break;case Tf:t=Ye.Always;break;case xf:t=Ye.Less;break;case _f:t=Ye.LessEqual;break;case bf:t=Ye.Equal;break;case yf:t=Ye.GreaterEqual;break;case mf:t=Ye.Greater;break;case gf:t=Ye.NotEqual;break;default:k("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class RE extends Kg{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const s=this.maxQueries*8;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Oe(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||this.currentQueryIndex===0||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if(this.resultBuffer.mapState!=="unmapped")return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const r=s.finish();if(this.device.queue.submit([r]),this.resultBuffer.mapState!=="unmapped")return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue;const o=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),a={},u=[];for(const[c,d]of e){const h=c.match(/^(.*):f(\d+)$/),f=parseInt(h[2]);u.includes(f)===!1&&u.push(f),a[f]===void 0&&(a[f]=0);const p=o[d],g=o[d+1],m=Number(g-p)/1e6;this.timestamps.set(c,m),a[f]+=m}const l=a[u[u.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=u,l}catch(e){return k("Error resolving queries:",e),this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){k("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){k("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}const Ut={r:0,g:0,b:0,a:1};class wE extends Xg{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new yE(this),this.attributeUtils=new xE(this),this.bindingUtils=new vE(this),this.capabilities=new SE(this),this.pipelineUtils=new NE(this),this.textureUtils=new oE(this),this.occludedResolveCache=new Map;const t=typeof navigator>"u"?!0:/Android/.test(navigator.userAgent)===!1;this._compatibility={[Ns.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let n;if(t.device===void 0){const s={powerPreference:t.powerPreference,featureLevel:"compatibility"},r=typeof navigator<"u"?await navigator.gpu.requestAdapter(s):null;if(r===null)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const o=Object.values(Mo),a=[];for(const l of o)r.features.has(l)&&a.push(l);const u={requiredFeatures:a,requiredLimits:t.requiredLimits};n=await r.requestDevice(u)}else n=t.device;this.compatibilityMode=!n.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),n.lost.then(s=>{if(s.reason==="destroyed")return;const r={api:"WebGPU",message:s.message||"Unknown reason",reason:s.reason||null,originalEvent:s};e.onDeviceLost(r)}),this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(Mo.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let n=t.context;if(n===void 0){const s=this.parameters;e.isDefaultCanvasTarget===!0&&s.context!==void 0?n=s.context:n=e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${Io} webgpu`);const r=s.alpha?"premultiplied":"opaque",o=s.outputType===it?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:o}}),t.context=n}return n}get coordinateSystem(){return Xr}async getArrayBufferAsync(e,t=null,n=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,s)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),s=e.currentSamples;let r=n.descriptor;if(r===void 0||n.samples!==s){r={colorAttachments:[{view:null}]},(e.depth===!0||e.stencil===!0)&&(r.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const a=r.colorAttachments[0];s>0?a.view=this.textureUtils.getColorBuffer().createView():a.resolveTarget=void 0,n.descriptor=r,n.samples=s}const o=r.colorAttachments[0];return s>0?o.resolveTarget=this.context.getCurrentTexture().createView():o.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,s=this.get(n);let r=s.descriptors;(r===void 0||s.width!==n.width||s.height!==n.height||s.samples!==n.samples)&&(r={},s.descriptors=r);const o=e.getCacheKey();let a=r[o];if(a===void 0){const l=e.textures,c=[];let d;const h=this._isRenderCameraDepthArray(e);for(let f=0;f<l.length;f++){const p=this.get(l[f]),g={label:`colorAttachment_${f}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:tt.TwoD};if(n.isRenderTarget3D)d=e.activeCubeFace,g.baseArrayLayer=0,g.dimension=tt.ThreeD,g.depthOrArrayLayers=l[f].image.depth;else if(n.isRenderTarget&&l[f].image.depth>1)if(h===!0){const m=e.camera.cameras;for(let y=0;y<m.length;y++){const _={...g,baseArrayLayer:y,arrayLayerCount:1,dimension:tt.TwoD},T=p.texture.createView(_);c.push({view:T,resolveTarget:void 0,depthSlice:void 0})}}else g.dimension=tt.TwoDArray,g.depthOrArrayLayers=l[f].image.depth;if(h!==!0){const m=p.texture.createView(g);let y,_;p.msaaTexture!==void 0?(y=p.msaaTexture.createView(),_=m):(y=m,_=void 0),c.push({view:y,resolveTarget:_,depthSlice:d})}}if(a={textureViews:c},e.depth){const f=this.get(e.depthTexture),p={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(p.dimension=tt.TwoD,p.arrayLayerCount=1,p.baseArrayLayer=e.activeCubeFace),a.depthStencilView=f.texture.createView(p)}r[o]=a,s.width=n.width,s.height=n.height,s.samples=n.samples,s.activeMipmapLevel=e.activeMipmapLevel,s.activeCubeFace=e.activeCubeFace}const u={colorAttachments:[]};for(let l=0;l<a.textureViews.length;l++){const c=a.textureViews[l];let d={r:0,g:0,b:0,a:1};l===0&&t.clearValue&&(d=t.clearValue),u.colorAttachments.push({view:c.view,depthSlice:c.depthSlice,resolveTarget:c.resolveTarget,loadOp:t.loadOp||be.Load,storeOp:t.storeOp||ut.Store,clearValue:d})}return a.depthStencilView&&(u.depthStencilAttachment={view:a.depthStencilView}),u}beginRender(e){const t=this.get(e),n=this.device,s=e.occlusionQueryCount;let r;s>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=n.createQuerySet({type:"occlusion",count:s,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null);let o;e.textures===null?o=this._getDefaultRenderPassDescriptor():o=this._getRenderPassDescriptor(e,{loadOp:be.Load}),this.initTimestampQuery(Zt.RENDER,this.getTimestampUID(e),o),o.occlusionQuerySet=r;const a=o.depthStencilAttachment;if(e.textures!==null){const l=o.colorAttachments;for(let c=0;c<l.length;c++){const d=l[c];e.clearColor?(c===0?d.clearValue=e.clearColorValue:(Ut.r=0,Ut.g=0,Ut.b=0,Ut.a=1,d.clearValue=Ut),d.loadOp=be.Clear):d.loadOp=be.Load,d.storeOp=ut.Store}}else{const l=o.colorAttachments[0];e.clearColor?(l.clearValue=e.clearColorValue,l.loadOp=be.Clear):l.loadOp=be.Load,l.storeOp=ut.Store}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=be.Clear):a.depthLoadOp=be.Load,a.depthStoreOp=ut.Store),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=be.Clear):a.stencilLoadOp=be.Load,a.stencilStoreOp=ut.Store);const u=n.createCommandEncoder({label:"renderContext_"+e.id});if(this._isRenderCameraDepthArray(e)===!0){const l=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==l.length?this._createDepthLayerDescriptors(e,t,o,l):this._updateDepthLayerDescriptors(e,t,l),t.bundleEncoders=[],t.bundleSets=[];for(let c=0;c<l.length;c++){const d=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+c),h={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(d),t.bundleSets.push(h)}t.currentPass=null}else{const l=u.beginRenderPass(o);t.currentPass=l,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=o,t.encoder=u,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,n,s){const r=n.depthStencilAttachment;t.layerDescriptors=[];const o=this.get(e.depthTexture);o.viewCache||(o.viewCache=[]);for(let a=0;a<s.length;a++){const u={...n,colorAttachments:[{...n.colorAttachments[0],view:n.colorAttachments[a].view}]};if(n.depthStencilAttachment){const l=a;o.viewCache[l]||(o.viewCache[l]=o.texture.createView({dimension:tt.TwoD,baseArrayLayer:a,arrayLayerCount:1})),u.depthStencilAttachment={view:o.viewCache[l],depthLoadOp:r.depthLoadOp||be.Clear,depthStoreOp:r.depthStoreOp||ut.Store,depthClearValue:r.depthClearValue||1},e.stencil&&(u.depthStencilAttachment.stencilLoadOp=r.stencilLoadOp,u.depthStencilAttachment.stencilStoreOp=r.stencilStoreOp,u.depthStencilAttachment.stencilClearValue=r.stencilClearValue)}else u.depthStencilAttachment={...r};t.layerDescriptors.push(u)}}_updateDepthLayerDescriptors(e,t,n){for(let s=0;s<n.length;s++){const r=t.layerDescriptors[s];if(r.depthStencilAttachment){const o=r.depthStencilAttachment;e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=be.Clear):o.depthLoadOp=be.Load),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=be.Clear):o.stencilLoadOp=be.Load)}}}finishRender(e){const t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const r=[];for(let o=0;o<t.bundleEncoders.length;o++){const a=t.bundleEncoders[o];r.push(a.finish())}for(let o=0;o<t.layerDescriptors.length;o++)if(o<r.length){const a=t.layerDescriptors[o],u=s.beginRenderPass(a);if(e.viewport){const{x:l,y:c,width:d,height:h,minDepth:f,maxDepth:p}=e.viewportValue;u.setViewport(l,c,d,h,f,p)}if(e.scissor){const{x:l,y:c,width:d,height:h}=e.scissorValue;u.setScissorRect(l,c,d,h)}u.executeBundles([r[o]]),u.end()}}else t.currentPass&&t.currentPass.end();if(n>0){const r=n*8;let o=this.occludedResolveCache.get(r);o===void 0&&(o=this.device.createBuffer({size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(r,o));const a=this.device.createBuffer({size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,o,0),t.encoder.copyBufferToBuffer(o,0,a,0,r),t.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),e.textures!==null){const r=e.textures;for(let o=0;o<r.length;o++){const a=r[o];a.generateMipmaps===!0&&this.textureUtils.generateMipmaps(a)}}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:s}=t;if(n&&s){const r=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);const o=n.getMappedRange(),a=new BigUint64Array(o);for(let u=0;u<s.length;u++)a[u]===BigInt(0)&&r.add(s[u]);n.destroy(),t.occluded=r}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:s,width:r,height:o,minDepth:a,maxDepth:u}=e.viewportValue;t.setViewport(n,s,r,o,a,u)}updateScissor(e){const{currentPass:t}=this.get(e),{x:n,y:s,width:r,height:o}=e.scissorValue;t.setScissorRect(n,s,r,o)}getClearColor(){const e=super.getClearColor();return this.renderer.alpha===!0&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,n,s=null){const r=this.device,o=this.renderer;let a=[],u,l,c;if(e){const f=this.getClearColor();Ut.r=f.r,Ut.g=f.g,Ut.b=f.b,Ut.a=f.a}if(s===null){l=o.depth,c=o.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){a=f.colorAttachments;const p=a[0];p.clearValue=Ut,p.loadOp=be.Clear,p.storeOp=ut.Store}(l||c)&&(u=f.depthStencilAttachment)}else{l=s.depth,c=s.stencil;const f={loadOp:e?be.Clear:be.Load,clearValue:e?Ut:void 0};l&&(f.depthLoadOp=t?be.Clear:be.Load,f.depthClearValue=t?o.getClearDepth():void 0,f.depthStoreOp=ut.Store),c&&(f.stencilLoadOp=n?be.Clear:be.Load,f.stencilClearValue=n?o.getClearStencil():void 0,f.stencilStoreOp=ut.Store);const p=this._getRenderPassDescriptor(s,f);a=p.colorAttachments,u=p.depthStencilAttachment}l&&u&&(t?(u.depthLoadOp=be.Clear,u.depthClearValue=o.getClearDepth(),u.depthStoreOp=ut.Store):(u.depthLoadOp=be.Load,u.depthStoreOp=ut.Store)),c&&u&&(n?(u.stencilLoadOp=be.Clear,u.stencilClearValue=o.getClearStencil(),u.stencilStoreOp=ut.Store):(u.stencilLoadOp=be.Load,u.stencilStoreOp=ut.Store));const d=r.createCommandEncoder({label:"clear"});d.beginRenderPass({colorAttachments:a,depthStencilAttachment:u}).end(),r.queue.submit([d.finish()])}beginCompute(e){const t=this.get(e),n={label:"computeGroup_"+e.id};this.initTimestampQuery(Zt.COMPUTE,this.getTimestampUID(e),n),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(n)}compute(e,t,n,s,r=null){const o=this.get(t),{passEncoderGPU:a}=this.get(e),u=this.get(s).pipeline;this.pipelineUtils.setPipeline(a,u);for(let l=0,c=n.length;l<c;l++){const d=n[l],h=this.get(d);a.setBindGroup(l,h.group)}if(r===null&&(r=t.dispatchSize||t.count),r&&r.isIndirectStorageBufferAttribute){const l=this.get(r).buffer;a.dispatchWorkgroupsIndirect(l,0);return}if(typeof r=="number"){const l=r;if(o.dispatchSize===void 0||o.count!==l){o.dispatchSize=[0,1,1],o.count=l;const c=t.workgroupSize;let d=c[0];for(let p=1;p<c.length;p++)d*=c[p];const h=Math.ceil(l/d),f=this.device.limits.maxComputeWorkgroupsPerDimension;r=[h,1,1],h>f&&(r[0]=Math.min(h,f),r[1]=Math.ceil(h/f)),o.dispatchSize=r}r=o.dispatchSize}a.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}_draw(e,t,n,s,r,o,a,u,l){const{object:c,material:d,context:h}=e,f=e.getIndex(),p=f!==null;this.pipelineUtils.setPipeline(u,s),l.pipeline=s;const g=l.bindingGroups;for(let m=0,y=r.length;m<y;m++){const _=r[m],T=this.get(_);g[m]!==_.id&&(u.setBindGroup(m,T.group),g[m]=_.id)}if(p===!0&&l.index!==f){const m=this.get(f).buffer,y=f.array instanceof Uint16Array?Co.Uint16:Co.Uint32;u.setIndexBuffer(m,y),l.index=f}for(let m=0,y=o.length;m<y;m++){const _=o[m];if(l.attributes[m]!==_){const T=this.get(_).buffer;u.setVertexBuffer(m,T),l.attributes[m]=_}}if(h.stencil===!0&&d.stencilWrite===!0&&n.currentStencilRef!==d.stencilRef&&(u.setStencilReference(d.stencilRef),n.currentStencilRef=d.stencilRef),c.isBatchedMesh===!0){const m=c._multiDrawStarts,y=c._multiDrawCounts,_=c._multiDrawCount;let T=p===!0?f.array.BYTES_PER_ELEMENT:1;d.wireframe&&(T=c.geometry.attributes.position.count>65535?4:2);for(let S=0;S<_;S++)p===!0?u.drawIndexed(y[S],1,m[S]/T,0,S):u.draw(y[S],1,m[S],S),t.update(c,y[S],1)}else if(p===!0){const{vertexCount:m,instanceCount:y,firstVertex:_}=a,T=e.getIndirect();if(T!==null){const S=this.get(T).buffer,N=e.getIndirectOffset(),R=Array.isArray(N)?N:[N];for(let v=0;v<R.length;v++)u.drawIndexedIndirect(S,R[v])}else u.drawIndexed(m,y,_,0,0);t.update(c,m,y)}else{const{vertexCount:m,instanceCount:y,firstVertex:_}=a,T=e.getIndirect();if(T!==null){const S=this.get(T).buffer,N=e.getIndirectOffset(),R=Array.isArray(N)?N:[N];for(let v=0;v<R.length;v++)u.drawIndirect(S,R[v])}else u.draw(m,y,_,0);t.update(c,m,y)}}draw(e,t){const{object:n,context:s,pipeline:r}=e,o=this.get(s),a=this.get(r),u=a.pipeline;if(a.error===!0)return;const l=e.getDrawParameters();if(l===null)return;const c=e.getBindings(),d=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const h=this.get(e.camera),f=e.camera.cameras,p=e.getBindingGroup("cameraIndex");if(h.indexesGPU===void 0||h.indexesGPU.length!==f.length){const m=this.get(p),y=[],_=new Uint32Array([0,0,0,0]);for(let T=0,S=f.length;T<S;T++){_[0]=T;const{layoutGPU:N}=m.layout,R=this.bindingUtils.createBindGroupIndex(_,N);y.push(R)}h.indexesGPU=y}const g=this.renderer.getPixelRatio();for(let m=0,y=f.length;m<y;m++){const _=f[m];if(n.layers.test(_.layers)){const T=_.viewport;let S=o.currentPass,N=o.currentSets;if(o.bundleEncoders){const R=o.bundleEncoders[m],v=o.bundleSets[m];S=R,N=v}if(T&&S.setViewport(Math.floor(T.x*g),Math.floor(T.y*g),Math.floor(T.width*g),Math.floor(T.height*g),s.viewportValue.minDepth,s.viewportValue.maxDepth),p&&h.indexesGPU){const R=c.indexOf(p);S.setBindGroup(R,h.indexesGPU[m]),N.bindingGroups[R]=p.id}this._draw(e,t,o,u,c,d,l,S,N)}}}else if(o.currentPass){if(o.occlusionQuerySet!==void 0){const h=o.lastOcclusionObject;h!==n&&(h!==null&&h.occlusionTest===!0&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),n.occlusionTest===!0&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=n),o.lastOcclusionObject=n)}this._draw(e,t,o,u,c,d,l,o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:s}=e,r=this.utils,o=r.getSampleCountRenderContext(e.context),a=r.getCurrentColorSpace(e.context),u=r.getCurrentColorFormat(e.context),l=r.getCurrentDepthStencilFormat(e.context),c=r.getPrimitiveTopology(n,s);let d=!1;return(t.material!==s||t.materialVersion!==s.version||t.transparent!==s.transparent||t.blending!==s.blending||t.premultipliedAlpha!==s.premultipliedAlpha||t.blendSrc!==s.blendSrc||t.blendDst!==s.blendDst||t.blendEquation!==s.blendEquation||t.blendSrcAlpha!==s.blendSrcAlpha||t.blendDstAlpha!==s.blendDstAlpha||t.blendEquationAlpha!==s.blendEquationAlpha||t.colorWrite!==s.colorWrite||t.depthWrite!==s.depthWrite||t.depthTest!==s.depthTest||t.depthFunc!==s.depthFunc||t.stencilWrite!==s.stencilWrite||t.stencilFunc!==s.stencilFunc||t.stencilFail!==s.stencilFail||t.stencilZFail!==s.stencilZFail||t.stencilZPass!==s.stencilZPass||t.stencilFuncMask!==s.stencilFuncMask||t.stencilWriteMask!==s.stencilWriteMask||t.side!==s.side||t.alphaToCoverage!==s.alphaToCoverage||t.sampleCount!==o||t.colorSpace!==a||t.colorFormat!==u||t.depthStencilFormat!==l||t.primitiveTopology!==c||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=s,t.materialVersion=s.version,t.transparent=s.transparent,t.blending=s.blending,t.premultipliedAlpha=s.premultipliedAlpha,t.blendSrc=s.blendSrc,t.blendDst=s.blendDst,t.blendEquation=s.blendEquation,t.blendSrcAlpha=s.blendSrcAlpha,t.blendDstAlpha=s.blendDstAlpha,t.blendEquationAlpha=s.blendEquationAlpha,t.colorWrite=s.colorWrite,t.depthWrite=s.depthWrite,t.depthTest=s.depthTest,t.depthFunc=s.depthFunc,t.stencilWrite=s.stencilWrite,t.stencilFunc=s.stencilFunc,t.stencilFail=s.stencilFail,t.stencilZFail=s.stencilZFail,t.stencilZPass=s.stencilZPass,t.stencilFuncMask=s.stencilFuncMask,t.stencilWriteMask=s.stencilWriteMask,t.side=s.side,t.alphaToCoverage=s.alphaToCoverage,t.sampleCount=o,t.colorSpace=a,t.colorFormat=u,t.depthStencilFormat=l,t.primitiveTopology=c,t.clippingContextCacheKey=e.clippingContextCacheKey,d=!0),d}getRenderCacheKey(e){const{object:t,material:n}=e,s=this.utils,r=e.context,o=t.isMesh&&t.matrixWorld.determinant()<0;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.side,o,s.getSampleCountRenderContext(r),s.getCurrentColorSpace(r),s.getCurrentColorFormat(r),s.getCurrentDepthStencilFormat(r),s.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,s,r,o){return this.textureUtils.copyTextureToBuffer(e,t,n,s,r,o)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new RE(this.device,e,2048));const s=this.timestampQueryPool[e],r=s.allocateQueriesForContext(t);n.timestampWrites={querySet:s.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new mE(e,t)}createProgram(e){const t=this.get(e);t.module={module:this.device.createShaderModule({code:e.code,label:e.stage+(e.name!==""?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const n=this.get(e),r=n.currentPass.finish();this.get(t).bundleGPU=r,n.currentSets=n._currentSets,n.currentPass=n._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,n,s){this.bindingUtils.createBindings(e,t,n,s)}updateBindings(e,t,n,s){this.bindingUtils.createBindings(e,t,n,s)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}hasFeature(e){return Th[e]!==void 0&&(e=Th[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,s=null,r=0,o=0){let a=0,u=0,l=0,c=0,d=0,h=0,f=e.image.width,p=e.image.height,g=1;n!==null&&(n.isBox3===!0?(c=n.min.x,d=n.min.y,h=n.min.z,f=n.max.x-n.min.x,p=n.max.y-n.min.y,g=n.max.z-n.min.z):(c=n.min.x,d=n.min.y,f=n.max.x-n.min.x,p=n.max.y-n.min.y,g=1)),s!==null&&(a=s.x,u=s.y,l=s.z||0);const m=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),y=this.get(e).texture,_=this.get(t).texture;m.copyTextureToTexture({texture:y,mipLevel:r,origin:{x:c,y:d,z:h}},{texture:_,mipLevel:o,origin:{x:a,y:u,z:l}},[f,p,g]),this.device.queue.submit([m.finish()]),o===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const s=this.get(t);let r=null;t.renderTarget?e.isDepthTexture?r=this.get(t.depthTexture).texture:r=this.get(t.textures[0]).texture:e.isDepthTexture?r=this.textureUtils.getDepthBuffer(t.depth,t.stencil):r=this.context.getCurrentTexture();const o=this.get(e).texture;if(r.format!==o.format){k("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,o.format);return}let a;if(s.currentPass?(s.currentPass.end(),a=s.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:r,origin:[n.x,n.y,0]},{texture:o},[n.z,n.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),s.currentPass){const{descriptor:u}=s;for(let l=0;l<u.colorAttachments.length;l++)u.colorAttachments[l].loadOp=be.Load;t.depth&&(u.depthStencilAttachment.depthLoadOp=be.Load),t.stencil&&(u.depthStencilAttachment.stencilLoadOp=be.Load),s.currentPass=a.beginRenderPass(u),s.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([a.finish()])}hasCompatibility(e){return this._compatibility[e]!==void 0?this._compatibility[e]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))e!==null&&e.dispose();this.parameters.device===void 0&&this.device!==null&&this.device.destroy()}}class EE extends vl{constructor(e,t,n,s,r,o){super(e,t,n,s,r,o),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class AE extends vl{constructor(e,t,n,s,r,o){super(e,t,n,s,r,o),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class CE extends Gg{constructor(){super(),this.addMaterial(G0,"MeshPhongMaterial"),this.addMaterial(xg,"MeshStandardMaterial"),this.addMaterial(OS,"MeshPhysicalMaterial"),this.addMaterial(VS,"MeshToonMaterial"),this.addMaterial(F0,"MeshBasicMaterial"),this.addMaterial(I0,"MeshLambertMaterial"),this.addMaterial(A0,"MeshNormalMaterial"),this.addMaterial(WS,"MeshMatcapMaterial"),this.addMaterial(N0,"LineBasicMaterial"),this.addMaterial(w0,"LineDashedMaterial"),this.addMaterial(KS,"PointsMaterial"),this.addMaterial(vg,"SpriteMaterial"),this.addMaterial(JS,"ShadowMaterial"),this.addLight(AR,ym),this.addLight(rw,zh),this.addLight(cw,bm),this.addLight(oc,vl),this.addLight(sw,Wh),this.addLight(iw,_m),this.addLight(aw,xm),this.addLight(ow,EE),this.addLight(lw,AE),this.addToneMapping(FN,Tm),this.addToneMapping(DN,vm),this.addToneMapping(LN,Sm),this.addToneMapping(ON,Nm),this.addToneMapping(VN,Rm),this.addToneMapping($N,wm)}}class ME extends Bw{constructor(e={}){let t;e.forceWebGL?t=gh:(t=wE,e.getFallback=()=>(z("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new gh(e)));const n=new t(e);super(n,e),this.library=new CE,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const lu={type:"change"},uc={type:"start"},lc={type:"end"},wh=1e-6,_e={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4},Wi=new ce,Ln=new ce,BE=new V,ji=new V,cu=new V,Os=new Js,Eh=new V,qi=new V,du=new V,Hi=new V;class PE extends Po{constructor(e,t=null){super(e,t),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:Qe.ROTATE,MIDDLE:Qe.DOLLY,RIGHT:Qe.PAN},this.target=new V,this.state=_e.NONE,this.keyState=_e.NONE,this._lastPosition=new V,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new V,this._movePrev=new ce,this._moveCurr=new ce,this._lastAxis=new V,this._zoomStart=new ce,this._zoomEnd=new ce,this._panStart=new ce,this._panEnd=new ce,this._pointers=[],this._pointerPositions={},this._onPointerMove=DE.bind(this),this._onPointerDown=FE.bind(this),this._onPointerUp=LE.bind(this),this._onPointerCancel=UE.bind(this),this._onContextMenu=zE.bind(this),this._onMouseWheel=$E.bind(this),this._onKeyDown=IE.bind(this),this._onKeyUp=OE.bind(this),this._onTouchStart=WE.bind(this),this._onTouchMove=jE.bind(this),this._onTouchEnd=qE.bind(this),this._onMouseDown=kE.bind(this),this._onMouseMove=GE.bind(this),this._onMouseUp=VE.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,t!==null&&(this.connect(t),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>wh&&(this.dispatchEvent(lu),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>wh||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(lu),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=_e.NONE,this.keyState=_e.NONE,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(lu),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(Ln.copy(this._panEnd).sub(this._panStart),Ln.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;Ln.x*=e,Ln.y*=t}Ln.multiplyScalar(this._eye.length()*this.panSpeed),ji.copy(this._eye).cross(this.object.up).setLength(Ln.x),ji.add(BE.copy(this.object.up).setLength(Ln.y)),this.object.position.add(ji),this.target.add(ji),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(Ln.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){Hi.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=Hi.length();e?(this._eye.copy(this.object.position).sub(this.target),Eh.copy(this._eye).normalize(),qi.copy(this.object.up).normalize(),du.crossVectors(qi,Eh).normalize(),qi.setLength(this._moveCurr.y-this._movePrev.y),du.setLength(this._moveCurr.x-this._movePrev.x),Hi.copy(qi.add(du)),cu.crossVectors(Hi,this._eye).normalize(),e*=this.rotateSpeed,Os.setFromAxisAngle(cu,e),this._eye.applyQuaternion(Os),this.object.up.applyQuaternion(Os),this._lastAxis.copy(cu),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),Os.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(Os),this.object.up.applyQuaternion(Os)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===_e.TOUCH_ZOOM_PAN?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=mo.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,e!==1&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=mo.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return Wi.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),Wi}_getMouseOnCircle(e,t){return Wi.set((e-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-t))/this.screen.width),Wi}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId){this._pointers.splice(t,1);return}}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new ce,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){(!this.noZoom||!this.noPan)&&(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function FE(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i))}function DE(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function LE(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchEnd(i):this._onMouseUp(),this._removePointer(i),this._pointers.length===0&&(this.domElement.releasePointerCapture(i.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function UE(i){this._removePointer(i)}function OE(){this.enabled!==!1&&(this.keyState=_e.NONE,window.addEventListener("keydown",this._onKeyDown))}function IE(i){this.enabled!==!1&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===_e.NONE&&(i.code===this.keys[_e.ROTATE]&&!this.noRotate?this.keyState=_e.ROTATE:i.code===this.keys[_e.ZOOM]&&!this.noZoom?this.keyState=_e.ZOOM:i.code===this.keys[_e.PAN]&&!this.noPan&&(this.keyState=_e.PAN)))}function kE(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Qe.DOLLY:this.state=_e.ZOOM;break;case Qe.ROTATE:this.state=_e.ROTATE;break;case Qe.PAN:this.state=_e.PAN;break;default:this.state=_e.NONE}const t=this.keyState!==_e.NONE?this.keyState:this.state;t===_e.ROTATE&&!this.noRotate?(this._moveCurr.copy(this._getMouseOnCircle(i.pageX,i.pageY)),this._movePrev.copy(this._moveCurr)):t===_e.ZOOM&&!this.noZoom?(this._zoomStart.copy(this._getMouseOnScreen(i.pageX,i.pageY)),this._zoomEnd.copy(this._zoomStart)):t===_e.PAN&&!this.noPan&&(this._panStart.copy(this._getMouseOnScreen(i.pageX,i.pageY)),this._panEnd.copy(this._panStart)),this.dispatchEvent(uc)}function GE(i){const e=this.keyState!==_e.NONE?this.keyState:this.state;e===_e.ROTATE&&!this.noRotate?(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(i.pageX,i.pageY))):e===_e.ZOOM&&!this.noZoom?this._zoomEnd.copy(this._getMouseOnScreen(i.pageX,i.pageY)):e===_e.PAN&&!this.noPan&&this._panEnd.copy(this._getMouseOnScreen(i.pageX,i.pageY))}function VE(){this.state=_e.NONE,this.dispatchEvent(lc)}function $E(i){if(this.enabled!==!1&&this.noZoom!==!0){switch(i.preventDefault(),i.deltaMode){case 2:this._zoomStart.y-=i.deltaY*.025;break;case 1:this._zoomStart.y-=i.deltaY*.01;break;default:this._zoomStart.y-=i.deltaY*25e-5;break}this.dispatchEvent(uc),this.dispatchEvent(lc)}}function zE(i){this.enabled!==!1&&i.preventDefault()}function WE(i){switch(this._trackPointer(i),this._pointers.length){case 1:this.state=_e.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this.state=_e.TOUCH_ZOOM_PAN;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,s=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,s)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(uc)}function jE(i){switch(this._trackPointer(i),this._pointers.length){case 1:this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(i.pageX,i.pageY));break;default:const e=this._getSecondPointerPosition(i),t=i.pageX-e.x,n=i.pageY-e.y;this._touchZoomDistanceEnd=Math.sqrt(t*t+n*n);const s=(i.pageX+e.x)/2,r=(i.pageY+e.y)/2;this._panEnd.copy(this._getMouseOnScreen(s,r));break}}function qE(i){switch(this._pointers.length){case 0:this.state=_e.NONE;break;case 1:this.state=_e.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(i.pageX,i.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=_e.TOUCH_ZOOM_PAN;for(let e=0;e<this._pointers.length;e++)if(this._pointers[e].pointerId!==i.pointerId){const t=this._pointerPositions[this._pointers[e].pointerId];this._moveCurr.copy(this._getMouseOnCircle(t.x,t.y)),this._movePrev.copy(this._moveCurr);break}break}this.dispatchEvent(lc)}const Ah={type:"change"},cc={type:"start"},Zg={type:"end"},Xi=new My,Ch=new bl,HE=Math.cos(70*mo.DEG2RAD),He=new V,lt=2*Math.PI,Re={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},hu=1e-6;class XE extends Po{constructor(e,t=null){super(e,t),this.state=Re.NONE,this.target=new V,this.cursor=new V,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Qe.ROTATE,MIDDLE:Qe.DOLLY,RIGHT:Qe.PAN},this.touches={ONE:_n.ROTATE,TWO:_n.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new V,this._lastQuaternion=new Js,this._lastTargetPosition=new V,this._quat=new Js().setFromUnitVectors(e.up,new V(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new yc,this._sphericalDelta=new yc,this._scale=1,this._panOffset=new V,this._rotateStart=new ce,this._rotateEnd=new ce,this._rotateDelta=new ce,this._panStart=new ce,this._panEnd=new ce,this._panDelta=new ce,this._dollyStart=new ce,this._dollyEnd=new ce,this._dollyDelta=new ce,this._dollyDirection=new V,this._mouse=new ce,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=YE.bind(this),this._onPointerDown=KE.bind(this),this._onPointerUp=QE.bind(this),this._onContextMenu=rA.bind(this),this._onMouseWheel=eA.bind(this),this._onKeyDown=tA.bind(this),this._onTouchStart=nA.bind(this),this._onTouchMove=sA.bind(this),this._onMouseDown=ZE.bind(this),this._onMouseMove=JE.bind(this),this._interceptControlDown=iA.bind(this),this._interceptControlUp=oA.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Ah),this.update(),this.state=Re.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;He.copy(t).sub(this.target),He.applyQuaternion(this._quat),this._spherical.setFromVector3(He),this.autoRotate&&this.state===Re.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=lt:n>Math.PI&&(n-=lt),s<-Math.PI?s+=lt:s>Math.PI&&(s-=lt),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(He.setFromSpherical(this._spherical),He.applyQuaternion(this._quatInverse),t.copy(this.target).add(He),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=He.length();o=this._clampDistance(a*this._scale);const u=a-o;this.object.position.addScaledVector(this._dollyDirection,u),this.object.updateMatrixWorld(),r=!!u}else if(this.object.isOrthographicCamera){const a=new V(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const u=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=u!==this.object.zoom;const l=new V(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),o=He.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Xi.origin.copy(this.object.position),Xi.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Xi.direction))<HE?this.object.lookAt(this.target):(Ch.setFromNormalAndCoplanarPoint(this.object.up,this.target),Xi.intersectPlane(Ch,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>hu||8*(1-this._lastQuaternion.dot(this.object.quaternion))>hu||this._lastTargetPosition.distanceToSquared(this.target)>hu?(this.dispatchEvent(Ah),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?lt/60*this.autoRotateSpeed*e:lt/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){He.setFromMatrixColumn(t,0),He.multiplyScalar(-e),this._panOffset.add(He)}_panUp(e,t){this.screenSpacePanning===!0?He.setFromMatrixColumn(t,1):(He.setFromMatrixColumn(t,0),He.crossVectors(this.object.up,He)),He.multiplyScalar(e),this._panOffset.add(He)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;He.copy(s).sub(this.target);let r=He.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(lt*this._rotateDelta.x/t.clientHeight),this._rotateUp(lt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(lt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-lt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(lt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-lt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(lt*this._rotateDelta.x/t.clientHeight),this._rotateUp(lt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new ce,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function KE(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function YE(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function QE(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Zg),this.state=Re.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function ZE(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Qe.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Re.DOLLY;break;case Qe.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Re.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Re.ROTATE}break;case Qe.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Re.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Re.PAN}break;default:this.state=Re.NONE}this.state!==Re.NONE&&this.dispatchEvent(cc)}function JE(i){switch(this.state){case Re.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Re.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Re.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function eA(i){this.enabled===!1||this.enableZoom===!1||this.state!==Re.NONE||(i.preventDefault(),this.dispatchEvent(cc),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Zg))}function tA(i){this.enabled!==!1&&this._handleKeyDown(i)}function nA(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case _n.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Re.TOUCH_ROTATE;break;case _n.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Re.TOUCH_PAN;break;default:this.state=Re.NONE}break;case 2:switch(this.touches.TWO){case _n.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Re.TOUCH_DOLLY_PAN;break;case _n.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Re.TOUCH_DOLLY_ROTATE;break;default:this.state=Re.NONE}break;default:this.state=Re.NONE}this.state!==Re.NONE&&this.dispatchEvent(cc)}function sA(i){switch(this._trackPointer(i),this.state){case Re.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Re.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Re.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Re.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Re.NONE}}function rA(i){this.enabled!==!1&&i.preventDefault()}function iA(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function oA(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const aA={type:"change"},Mh=1e-6,Bh=new Js;class uA extends Po{constructor(e,t=null){super(e,t),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new V(0,0,0),this._rotationVector=new V(0,0,0),this._lastQuaternion=new Js,this._lastPosition=new V,this._status=0,this._onKeyDown=lA.bind(this),this._onKeyUp=cA.bind(this),this._onPointerMove=hA.bind(this),this._onPointerDown=dA.bind(this),this._onPointerUp=fA.bind(this),this._onPointerCancel=pA.bind(this),this._onContextMenu=gA.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(this.enabled===!1)return;const t=this.object,n=e*this.movementSpeed,s=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),Bh.set(this._rotationVector.x*s,this._rotationVector.y*s,this._rotationVector.z*s,1).normalize(),t.quaternion.multiply(Bh),(this._lastPosition.distanceToSquared(t.position)>Mh||8*(1-this._lastQuaternion.dot(t.quaternion))>Mh)&&(this.dispatchEvent(aA),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function lA(i){if(!(i.altKey||this.enabled===!1)){switch(i.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1;break}this._updateMovementVector(),this._updateRotationVector()}}function cA(i){if(this.enabled!==!1){switch(i.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0;break}this._updateMovementVector(),this._updateRotationVector()}}function dA(i){if(this.enabled!==!1)if(this.dragToLook)this._status++;else{switch(i.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1;break}this._updateMovementVector()}}function hA(i){if(this.enabled!==!1&&(!this.dragToLook||this._status>0)){const e=this._getContainerDimensions(),t=e.size[0]/2,n=e.size[1]/2;this._moveState.yawLeft=-(i.pageX-e.offset[0]-t)/t,this._moveState.pitchDown=(i.pageY-e.offset[1]-n)/n,this._updateRotationVector()}}function fA(i){if(this.enabled!==!1){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(i.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0;break}this._updateMovementVector()}this._updateRotationVector()}}function pA(){this.enabled!==!1&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function gA(i){this.enabled!==!1&&i.preventDefault()}const mA={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
|
|
949
|
-
|
|
950
|
-
varying vec2 vUv;
|
|
951
|
-
|
|
952
|
-
void main() {
|
|
953
|
-
|
|
954
|
-
vUv = uv;
|
|
955
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
956
|
-
|
|
957
|
-
}`,fragmentShader:`
|
|
958
|
-
|
|
959
|
-
uniform float opacity;
|
|
960
|
-
|
|
961
|
-
uniform sampler2D tDiffuse;
|
|
962
|
-
|
|
963
|
-
varying vec2 vUv;
|
|
964
|
-
|
|
965
|
-
void main() {
|
|
966
|
-
|
|
967
|
-
vec4 texel = texture2D( tDiffuse, vUv );
|
|
968
|
-
gl_FragColor = opacity * texel;
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
}`};class na{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const yA=new El(-1,1,1,-1,0,1);class bA extends si{constructor(){super(),this.setAttribute("position",new go([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new go([0,2,0,0,2,0],2))}}const _A=new bA;class xA{constructor(e){this._mesh=new kt(_A,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,yA)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class TA extends na{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof bc?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=By.clone(e.uniforms),this.material=new bc({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new xA(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class Ph extends na{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const s=e.getContext(),r=e.state;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0);let o,a;this.inverse?(o=0,a=1):(o=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(s.REPLACE,s.REPLACE,s.REPLACE),r.buffers.stencil.setFunc(s.ALWAYS,o,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(s.EQUAL,1,4294967295),r.buffers.stencil.setOp(s.KEEP,s.KEEP,s.KEEP),r.buffers.stencil.setLocked(!0)}}class vA extends na{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class SA{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const n=e.getSize(new ce);this._width=n.width,this._height=n.height,t=new Py(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:it}),t.texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new TA(mA),this.copyPass.material.blending=Nn,this.timer=new Cf}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),e===void 0&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let s=0,r=this.passes.length;s<r;s++){const o=this.passes[s];if(o.enabled!==!1){if(o.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(s),o.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),o.needsSwap){if(n){const a=this.renderer.getContext(),u=this.renderer.state.buffers.stencil;u.setFunc(a.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),u.setFunc(a.EQUAL,1,4294967295)}this.swapBuffers()}Ph!==void 0&&(o instanceof Ph?n=!0:o instanceof vA&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){const t=this.renderer.getSize(new ce);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,e=this.renderTarget1.clone(),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,s=this._height*this._pixelRatio;this.renderTarget1.setSize(n,s),this.renderTarget2.setSize(n,s);for(let r=0;r<this.passes.length;r++)this.passes[r].setSize(n,s)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class NA extends na{constructor(e,t,n=null,s=null,r=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=s,this.clearAlpha=r,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new Dt}render(e,t,n){const s=e.autoClear;e.autoClear=!1;let r,o;this.overrideMaterial!==null&&(o=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),this.clearAlpha!==null&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==!0&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:n),this.clear===!0&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),this.clearColor!==null&&e.setClearColor(this._oldClearColor),this.clearAlpha!==null&&e.setClearAlpha(r),this.overrideMaterial!==null&&(this.scene.overrideMaterial=o),e.autoClear=s}}function gt(){return gt=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(i[n]=t[n])}return i},gt.apply(null,arguments)}function RA(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}function ni(i,e){return ni=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},ni(i,e)}function wA(i,e){i.prototype=Object.create(e.prototype),i.prototype.constructor=i,ni(i,e)}function fl(i){return fl=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},fl(i)}function EA(i){try{return Function.toString.call(i).indexOf("[native code]")!==-1}catch{return typeof i=="function"}}function Jg(){try{var i=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Jg=function(){return!!i})()}function AA(i,e,t){if(Jg())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var s=new(i.bind.apply(i,n));return t&&ni(s,t.prototype),s}function pl(i){var e=typeof Map=="function"?new Map:void 0;return pl=function(n){if(n===null||!EA(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,s)}function s(){return AA(n,arguments,fl(this).constructor)}return s.prototype=Object.create(n.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),ni(s,n)},pl(i)}var tn=(function(i){wA(e,i);function e(t){var n;return n=i.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this,RA(n)}return e})(pl(Error));function fu(i){return Math.round(i*255)}function CA(i,e,t){return fu(i)+","+fu(e)+","+fu(t)}function Bo(i,e,t,n){if(n===void 0&&(n=CA),e===0)return n(t,t,t);var s=(i%360+360)%360/60,r=(1-Math.abs(2*t-1))*e,o=r*(1-Math.abs(s%2-1)),a=0,u=0,l=0;s>=0&&s<1?(a=r,u=o):s>=1&&s<2?(a=o,u=r):s>=2&&s<3?(u=r,l=o):s>=3&&s<4?(u=o,l=r):s>=4&&s<5?(a=o,l=r):s>=5&&s<6&&(a=r,l=o);var c=t-r/2,d=a+c,h=u+c,f=l+c;return n(d,h,f)}var Fh={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};function MA(i){if(typeof i!="string")return i;var e=i.toLowerCase();return Fh[e]?"#"+Fh[e]:i}var BA=/^#[a-fA-F0-9]{6}$/,PA=/^#[a-fA-F0-9]{8}$/,FA=/^#[a-fA-F0-9]{3}$/,DA=/^#[a-fA-F0-9]{4}$/,pu=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,LA=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,UA=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,OA=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function or(i){if(typeof i!="string")throw new tn(3);var e=MA(i);if(e.match(BA))return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16)};if(e.match(PA)){var t=parseFloat((parseInt(""+e[7]+e[8],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16),alpha:t}}if(e.match(FA))return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16)};if(e.match(DA)){var n=parseFloat((parseInt(""+e[4]+e[4],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16),alpha:n}}var s=pu.exec(e);if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10)};var r=LA.exec(e.substring(0,50));if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10),alpha:parseFloat(""+r[4])>1?parseFloat(""+r[4])/100:parseFloat(""+r[4])};var o=UA.exec(e);if(o){var a=parseInt(""+o[1],10),u=parseInt(""+o[2],10)/100,l=parseInt(""+o[3],10)/100,c="rgb("+Bo(a,u,l)+")",d=pu.exec(c);if(!d)throw new tn(4,e,c);return{red:parseInt(""+d[1],10),green:parseInt(""+d[2],10),blue:parseInt(""+d[3],10)}}var h=OA.exec(e.substring(0,50));if(h){var f=parseInt(""+h[1],10),p=parseInt(""+h[2],10)/100,g=parseInt(""+h[3],10)/100,m="rgb("+Bo(f,p,g)+")",y=pu.exec(m);if(!y)throw new tn(4,e,m);return{red:parseInt(""+y[1],10),green:parseInt(""+y[2],10),blue:parseInt(""+y[3],10),alpha:parseFloat(""+h[4])>1?parseFloat(""+h[4])/100:parseFloat(""+h[4])}}throw new tn(5)}function IA(i){var e=i.red/255,t=i.green/255,n=i.blue/255,s=Math.max(e,t,n),r=Math.min(e,t,n),o=(s+r)/2;if(s===r)return i.alpha!==void 0?{hue:0,saturation:0,lightness:o,alpha:i.alpha}:{hue:0,saturation:0,lightness:o};var a,u=s-r,l=o>.5?u/(2-s-r):u/(s+r);switch(s){case e:a=(t-n)/u+(t<n?6:0);break;case t:a=(n-e)/u+2;break;default:a=(e-t)/u+4;break}return a*=60,i.alpha!==void 0?{hue:a,saturation:l,lightness:o,alpha:i.alpha}:{hue:a,saturation:l,lightness:o}}function Yn(i){return IA(or(i))}var kA=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e},gl=kA;function rs(i){var e=i.toString(16);return e.length===1?"0"+e:e}function gu(i){return rs(Math.round(i*255))}function GA(i,e,t){return gl("#"+gu(i)+gu(e)+gu(t))}function em(i,e,t){return Bo(i,e,t,GA)}function VA(i,e,t){if(typeof i=="object"&&e===void 0&&t===void 0)return em(i.hue,i.saturation,i.lightness);throw new tn(1)}function $A(i,e,t,n){if(typeof i=="object"&&e===void 0&&t===void 0&&n===void 0)return i.alpha>=1?em(i.hue,i.saturation,i.lightness):"rgba("+Bo(i.hue,i.saturation,i.lightness)+","+i.alpha+")";throw new tn(2)}function tm(i,e,t){if(typeof i=="number"&&typeof e=="number"&&typeof t=="number")return gl("#"+rs(i)+rs(e)+rs(t));if(typeof i=="object"&&e===void 0&&t===void 0)return gl("#"+rs(i.red)+rs(i.green)+rs(i.blue));throw new tn(6)}function sa(i,e,t,n){if(typeof i=="object"&&e===void 0&&t===void 0&&n===void 0)return i.alpha>=1?tm(i.red,i.green,i.blue):"rgba("+i.red+","+i.green+","+i.blue+","+i.alpha+")";throw new tn(7)}var zA=function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||typeof e.alpha>"u")},WA=function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"},jA=function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||typeof e.alpha>"u")},qA=function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"};function Qn(i){if(typeof i!="object")throw new tn(8);if(WA(i))return sa(i);if(zA(i))return tm(i);if(qA(i))return $A(i);if(jA(i))return VA(i);throw new tn(8)}function nm(i,e,t){return function(){var s=t.concat(Array.prototype.slice.call(arguments));return s.length>=e?i.apply(this,s):nm(i,e,s)}}function Nt(i){return nm(i,i.length,[])}function HA(i,e){if(e==="transparent")return e;var t=Yn(e);return Qn(gt({},t,{hue:t.hue+parseFloat(i)}))}Nt(HA);function mr(i,e,t){return Math.max(i,Math.min(e,t))}function XA(i,e){if(e==="transparent")return e;var t=Yn(e);return Qn(gt({},t,{lightness:mr(0,1,t.lightness-parseFloat(i))}))}Nt(XA);function KA(i,e){if(e==="transparent")return e;var t=Yn(e);return Qn(gt({},t,{saturation:mr(0,1,t.saturation-parseFloat(i))}))}Nt(KA);function YA(i,e){if(e==="transparent")return e;var t=Yn(e);return Qn(gt({},t,{lightness:mr(0,1,t.lightness+parseFloat(i))}))}Nt(YA);function QA(i,e,t){if(e==="transparent")return t;if(t==="transparent")return e;if(i===0)return t;var n=or(e),s=gt({},n,{alpha:typeof n.alpha=="number"?n.alpha:1}),r=or(t),o=gt({},r,{alpha:typeof r.alpha=="number"?r.alpha:1}),a=s.alpha-o.alpha,u=parseFloat(i)*2-1,l=u*a===-1?u:u+a,c=1+u*a,d=(l/c+1)/2,h=1-d,f={red:Math.floor(s.red*d+o.red*h),green:Math.floor(s.green*d+o.green*h),blue:Math.floor(s.blue*d+o.blue*h),alpha:s.alpha*parseFloat(i)+o.alpha*(1-parseFloat(i))};return sa(f)}var ZA=Nt(QA),sm=ZA;function JA(i,e){if(e==="transparent")return e;var t=or(e),n=typeof t.alpha=="number"?t.alpha:1,s=gt({},t,{alpha:mr(0,1,(n*100+parseFloat(i)*100)/100)});return sa(s)}var eC=Nt(JA),tC=eC;function nC(i,e){if(e==="transparent")return e;var t=Yn(e);return Qn(gt({},t,{saturation:mr(0,1,t.saturation+parseFloat(i))}))}Nt(nC);function sC(i,e){return e==="transparent"?e:Qn(gt({},Yn(e),{hue:parseFloat(i)}))}Nt(sC);function rC(i,e){return e==="transparent"?e:Qn(gt({},Yn(e),{lightness:parseFloat(i)}))}Nt(rC);function iC(i,e){return e==="transparent"?e:Qn(gt({},Yn(e),{saturation:parseFloat(i)}))}Nt(iC);function oC(i,e){return e==="transparent"?e:sm(parseFloat(i),"rgb(0, 0, 0)",e)}Nt(oC);function aC(i,e){return e==="transparent"?e:sm(parseFloat(i),"rgb(255, 255, 255)",e)}Nt(aC);function uC(i,e){if(e==="transparent")return e;var t=or(e),n=typeof t.alpha=="number"?t.alpha:1,s=gt({},t,{alpha:mr(0,1,+(n*100-parseFloat(i)*100).toFixed(2)/100)});return sa(s)}Nt(uC);function lC(i,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t==="top"&&n.firstChild?n.insertBefore(s,n.firstChild):n.appendChild(s),s.styleSheet?s.styleSheet.cssText=i:s.appendChild(document.createTextNode(i))}}var cC=`.scene-nav-info {
|
|
972
|
-
position: absolute;
|
|
973
|
-
bottom: 5px;
|
|
974
|
-
width: 100%;
|
|
975
|
-
text-align: center;
|
|
976
|
-
color: slategrey;
|
|
977
|
-
opacity: 0.7;
|
|
978
|
-
font-size: 10px;
|
|
979
|
-
font-family: sans-serif;
|
|
980
|
-
pointer-events: none;
|
|
981
|
-
user-select: none;
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
.scene-container canvas:focus {
|
|
985
|
-
outline: none;
|
|
986
|
-
}`;lC(cC);function ml(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function dC(i){if(Array.isArray(i))return i}function hC(i){if(Array.isArray(i))return ml(i)}function fC(i,e,t){return(e=xC(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function pC(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function gC(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,s,r,o,a=[],u=!0,l=!1;try{if(r=(t=t.call(i)).next,e!==0)for(;!(u=(n=r.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,s=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}function mC(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
987
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yC(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
988
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function bC(i,e){return dC(i)||gC(i,e)||rm(i,e)||mC()}function ns(i){return hC(i)||pC(i)||rm(i)||yC()}function _C(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function xC(i){var e=_C(i,"string");return typeof e=="symbol"?e:e+""}function rm(i,e){if(i){if(typeof i=="string")return ml(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?ml(i,e):void 0}}var im=function(e){e instanceof Array?e.forEach(im):(e.map&&e.map.dispose(),e.dispose())},om=function(e){e.geometry&&e.geometry.dispose(),e.material&&im(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(om)},TC=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),om(t)}},De=window.THREE?window.THREE:{WebGLRenderer:Dy,Scene:Tl,PerspectiveCamera:Hr,Raycaster:Lh,SRGBColorSpace:xl,TextureLoader:Fy,Vector2:ce,Vector3:V,Box3:kh,Color:Dt,Mesh:kt,SphereGeometry:_l,MeshBasicMaterial:On,BackSide:ot,Timer:Cf},am=Pl({props:{width:{default:window.innerWidth,onChange:function(e,t,n){isNaN(e)&&(t.width=n)}},height:{default:window.innerHeight,onChange:function(e,t,n){isNaN(e)&&(t.height=n)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange:function(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:function(){return!0},triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:function(){},triggerUpdate:!1},onClick:{default:function(){},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(function(o){return o.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var s=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&s.sort(function(o,a){return e.hoverOrderComparator(o.object,a.object)});var r=s.find(function(o){return e.hoverFilter(o.object)})||null;n=r?r.object:null,e.intersection=r||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&fe(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos,n=t.x,s=t.y;return{x:n,y:s}},cameraPosition:function(e,t,n,s){var r=e.camera;if(t&&e.initialised){var o,a,u=t,l=n||{x:0,y:0,z:0};if((o=e.povPosTween)===null||o===void 0||o.end(),(a=e.povTgtTween)===null||a===void 0||a.end(),!s)h(u),f(l);else{var c=Object.assign({},r.position),d=p();e.tweenGroup.add(e.povPosTween=new _c(c).to(u,s).easing(xc.Quadratic.Out).onUpdate(h).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new _c(d).to(l,s/3).easing(xc.Quadratic.Out).onUpdate(f).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}return this}return Object.assign({},r.position,{lookAt:p()});function h(g){var m=g.x,y=g.y,_=g.z;m!==void 0&&(r.position.x=m),y!==void 0&&(r.position.y=y),_!==void 0&&(r.position.z=_)}function f(g){var m=new De.Vector3(g.x,g.y,g.z);e.controls.enabled&&e.controls.target?e.controls.target=m:r.lookAt(m)}function p(){return Object.assign(new De.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:10,s=arguments.length,r=new Array(s>3?s-3:0),o=3;o<s;o++)r[o-3]=arguments[o];return this.fitToBbox(this.getBbox.apply(this,r),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:10,r=e.camera;if(t){var o=new De.Vector3(0,0,0),a=Math.max.apply(Math,ns(Object.entries(t).map(function(f){var p=bC(f,2),g=p[0],m=p[1];return Math.max.apply(Math,ns(m.map(function(y){return Math.abs(o[g]-y)})))})))*2,u=(1-s*2/e.height)*r.fov,l=a/Math.atan(u*Math.PI/180),c=l/r.aspect,d=Math.max(l,c);if(d>0){var h=o.clone().sub(r.position).normalize().multiplyScalar(-d);this.cameraPosition(h,o,n)}}return this},getBbox:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){return!0},n=new De.Box3(new De.Vector3(0,0,0),new De.Vector3(0,0,0)),s=e.objects.filter(t);return s.length?(s.forEach(function(r){return n.expandByObject(r)}),Object.assign.apply(Object,ns(["x","y","z"].map(function(r){return fC({},r,[n.min[r],n.max[r]])})))):null},getScreenCoords:function(e,t,n,s){var r=new De.Vector3(t,n,s);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,r=new De.Vector2(t/e.width*2-1,-(n/e.height)*2+1),o=new De.Raycaster;return o.setFromCamera(r,e.camera),Object.assign({},o.ray.at(s,new De.Vector3))},intersectingObjects:function(e,t,n){var s=new De.Vector2(t/e.width*2-1,-(n/e.height)*2+1),r=new De.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(s,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,n,s;TC(e.scene),(t=e.controls)===null||t===void 0||t.dispose(),(n=e.renderer)===null||n===void 0||n.dispose(),(s=e.postProcessingComposer)===null||s===void 0||s.dispose()}},stateInit:function(){return{scene:new De.Scene,camera:new De.PerspectiveCamera,timer:new De.Timer,tweenGroup:new zy,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=n.controlType,r=s===void 0?"trackball":s,o=n.useWebGPU,a=o===void 0?!1:o,u=n.rendererConfig,l=u===void 0?{}:u,c=n.extraRenderers,d=c===void 0?[]:c,h=n.waitForLoadComplete,f=h===void 0?!0:h;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[r]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new $y(t.container),t.pointerPos=new De.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(p){return t.container.addEventListener(p,function(g){if(p==="pointerdown"&&(t.isPointerPressed=!0),!t.isPointerDragging&&g.type==="pointermove"&&(g.pressure>0||t.isPointerPressed)&&(g.pointerType==="mouse"||g.movementX===void 0||[g.movementX,g.movementY].some(function(_){return Math.abs(_)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var m=y(t.container);t.pointerPos.x=g.pageX-m.left,t.pointerPos.y=g.pageY-m.top}function y(_){var T=_.getBoundingClientRect(),S=window.pageXOffset||document.documentElement.scrollLeft,N=window.pageYOffset||document.documentElement.scrollTop;return{top:T.top+N,left:T.left+S}}},{passive:!0})}),t.container.addEventListener("pointerup",function(p){t.isPointerPressed&&(t.isPointerPressed=!1,!(t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag))&&requestAnimationFrame(function(){p.button===0&&t.onClick(t.hoverObj||null,p,t.intersection),p.button===2&&t.onRightClick&&t.onRightClick(t.hoverObj||null,p,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(p){t.onRightClick&&p.preventDefault()}),t.renderer=new(a?ME:De.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=d,t.extraRenderers.forEach(function(p){p.domElement.style.position="absolute",p.domElement.style.top="0px",p.domElement.style.pointerEvents="none",t.container.appendChild(p.domElement)}),t.postProcessingComposer=new SA(t.renderer),t.postProcessingComposer.addPass(new NA(t.scene,t.camera)),t.controls=new{trackball:PE,orbit:XE,fly:uA}[r](t.camera,t.renderer.domElement),r==="fly"&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),(r==="trackball"||r==="orbit")&&(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",function(){t.controlsEngaged=!0}),t.controls.addEventListener("change",function(){t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",function(){t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer].concat(ns(t.extraRenderers)).forEach(function(p){return p.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new De.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!f,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,s=e.width,r=e.height;e.container.style.width="".concat(s,"px"),e.container.style.height="".concat(r,"px"),[e.renderer,e.postProcessingComposer].concat(ns(e.extraRenderers)).forEach(function(f){return f.setSize(s,r)}),e.camera.aspect=s/r;var o=e.viewOffset.slice(0,2);o.some(function(f){return f})&&(n=e.camera).setViewOffset.apply(n,[s,r].concat(ns(o),[s,r])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,u=e.width,l=e.height,c=e.viewOffset.slice(0,2);c.some(function(f){return f})?(a=e.camera).setViewOffset.apply(a,[u,l].concat(ns(c),[u,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=e.skyRadius*2.5,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new De.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var d=or(e.backgroundColor).alpha;d===void 0&&(d=1),e.renderer.setClearColor(new De.Color(tC(1,e.backgroundColor)),d)}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?new De.TextureLoader().load(e.backgroundImageUrl,function(f){f.colorSpace=De.SRGBColorSpace,e.skysphere.material=new De.MeshBasicMaterial({map:f,side:De.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&h()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&h())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(f){return e.scene.remove(f)}),e.lights.forEach(function(f){return e.scene.add(f)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(f){return e.scene.remove(f)}),e.objects.forEach(function(f){return e.scene.add(f)}));function h(){e.loadComplete=e.scene.visible=!0}}});function vC(i,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t==="top"&&n.firstChild?n.insertBefore(s,n.firstChild):n.appendChild(s),s.styleSheet?s.styleSheet.cssText=i:s.appendChild(document.createTextNode(i))}}var SC=`.graph-info-msg {
|
|
989
|
-
top: 50%;
|
|
990
|
-
width: 100%;
|
|
991
|
-
text-align: center;
|
|
992
|
-
color: lavender;
|
|
993
|
-
opacity: 0.7;
|
|
994
|
-
font-size: 22px;
|
|
995
|
-
position: absolute;
|
|
996
|
-
font-family: Sans-serif;
|
|
997
|
-
}
|
|
998
|
-
|
|
999
|
-
.scene-container .clickable {
|
|
1000
|
-
cursor: pointer;
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
.scene-container .grabbable {
|
|
1004
|
-
cursor: move;
|
|
1005
|
-
cursor: grab;
|
|
1006
|
-
cursor: -moz-grab;
|
|
1007
|
-
cursor: -webkit-grab;
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
.scene-container .grabbable:active {
|
|
1011
|
-
cursor: grabbing;
|
|
1012
|
-
cursor: -moz-grabbing;
|
|
1013
|
-
cursor: -webkit-grabbing;
|
|
1014
|
-
}`;vC(SC);function yl(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function NC(i){if(Array.isArray(i))return yl(i)}function di(i,e,t){return(e=AC(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function RC(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function wC(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
1015
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Dh(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,n)}return t}function Ki(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Dh(Object(t),!0).forEach(function(n){di(i,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Dh(Object(t)).forEach(function(n){Object.defineProperty(i,n,Object.getOwnPropertyDescriptor(t,n))})}return i}function ra(i){return NC(i)||RC(i)||CC(i)||wC()}function EC(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function AC(i){var e=EC(i,"string");return typeof e=="symbol"?e:e+""}function CC(i,e){if(i){if(typeof i=="string")return yl(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?yl(i,e):void 0}}function um(i,e){var t=new e;return t._destructor&&t._destructor(),{linkProp:function(s){return{default:t[s](),onChange:function(o,a){a[i][s](o)},triggerUpdate:!1}},linkMethod:function(s){return function(r){for(var o=r[i],a=arguments.length,u=new Array(a>1?a-1:0),l=1;l<a;l++)u[l-1]=arguments[l];var c=o[s].apply(o,u);return c===o?this:c}}}}var mu=window.THREE?window.THREE:{AmbientLight:Wh,DirectionalLight:zh,REVISION:Io},MC=170,lm=um("forceGraph",Kf),BC=Object.assign.apply(Object,ra(["jsonUrl","graphData","numDimensions","dagMode","dagLevelDistance","dagNodeFilter","onDagError","nodeRelSize","nodeId","nodeVal","nodeResolution","nodeColor","nodeAutoColorBy","nodeOpacity","nodeVisibility","nodeThreeObject","nodeThreeObjectExtend","nodePositionUpdate","linkSource","linkTarget","linkVisibility","linkColor","linkAutoColorBy","linkOpacity","linkWidth","linkResolution","linkCurvature","linkCurveRotation","linkMaterial","linkThreeObject","linkThreeObjectExtend","linkPositionUpdate","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowRelPos","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleSpeed","linkDirectionalParticleOffset","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject","forceEngine","d3AlphaDecay","d3VelocityDecay","d3AlphaMin","ngraphPhysics","warmupTicks","cooldownTicks","cooldownTime","onEngineTick","onEngineStop"].map(function(i){return di({},i,lm.linkProp(i))}))),PC=Object.assign.apply(Object,ra(["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(function(i){return di({},i,lm.linkMethod(i))}))),ao=um("renderObjs",am),FC=Object.assign.apply(Object,ra(["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(function(i){return di({},i,ao.linkProp(i))}))),DC=Object.assign.apply(Object,ra(["lights","cameraPosition","postProcessingComposer"].map(function(i){return di({},i,ao.linkMethod(i))})).concat([{graph2ScreenCoords:ao.linkMethod("getScreenCoords"),screen2GraphCoords:ao.linkMethod("getSceneCoords")}])),GC=Pl({props:Ki(Ki({nodeLabel:{default:"name",triggerUpdate:!1},linkLabel:{default:"name",triggerUpdate:!1},linkHoverPrecision:{default:1,onChange:function(e,t){return t.renderObjs.lineHoverPrecision(e)},triggerUpdate:!1},enableNavigationControls:{default:!0,onChange:function(e,t){var n=t.renderObjs.controls();n&&(n.enabled=e,e&&n.domElement&&n.domElement.dispatchEvent(new PointerEvent("pointerup")))},triggerUpdate:!1},enableNodeDrag:{default:!0,triggerUpdate:!1},onNodeDrag:{default:function(){},triggerUpdate:!1},onNodeDragEnd:{default:function(){},triggerUpdate:!1},onNodeClick:{triggerUpdate:!1},onNodeRightClick:{triggerUpdate:!1},onNodeHover:{triggerUpdate:!1},onLinkClick:{triggerUpdate:!1},onLinkRightClick:{triggerUpdate:!1},onLinkHover:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1},onBackgroundRightClick:{triggerUpdate:!1},showPointerCursor:{default:!0,triggerUpdate:!1}},BC),FC),methods:Ki(Ki({zoomToFit:function(e,t,n){for(var s,r=arguments.length,o=new Array(r>3?r-3:0),a=3;a<r;a++)o[a-3]=arguments[a];return e.renderObjs.fitToBbox((s=e.forceGraph).getGraphBbox.apply(s,o),t,n),this},pauseAnimation:function(e){return e.animationFrameRequestId!==null&&(cancelAnimationFrame(e.animationFrameRequestId),e.animationFrameRequestId=null),this},resumeAnimation:function(e){return e.animationFrameRequestId===null&&this._animationCycle(),this},_animationCycle:function(e){e.enablePointerInteraction&&(this.renderer().domElement.style.cursor=null),e.forceGraph.tickFrame(),e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:function(e){return e.renderObjs.scene()},camera:function(e){return e.renderObjs.camera()},renderer:function(e){return e.renderObjs.renderer()},controls:function(e){return e.renderObjs.controls()},_destructor:function(e){var t,n;this.pauseAnimation(),this.graphData({nodes:[],links:[]}),(t=(n=e.forceGraph)._destructor)===null||t===void 0||t.call(n),e.renderObjs._destructor()}},PC),DC),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,s=e.extraRenderers,r=new Kf;return{forceGraph:r,renderObjs:am({controlType:t,rendererConfig:n,extraRenderers:s}).objects([r]).lights([new mu.AmbientLight(13421772,Math.PI),new mu.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.style.position="relative";var n=document.createElement("div");t.container.appendChild(n),t.renderObjs(n);var s=t.renderObjs.camera(),r=t.renderObjs.renderer(),o=t.renderObjs.controls();o.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=s.position.z;var a;t.container.appendChild(a=document.createElement("div")),a.className="graph-info-msg",a.textContent="",t.forceGraph.onLoading(function(){a.textContent="Loading..."}).onFinishLoading(function(){a.textContent=""}).onUpdate(function(){t.graphData=t.forceGraph.graphData(),s.position.x===0&&s.position.y===0&&s.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(s.lookAt(t.forceGraph.position),t.lastSetCameraZ=s.position.z=Math.cbrt(t.graphData.nodes.length)*MC)}).onFinishUpdate(function(){if(t._dragControls){var u=t.graphData.nodes.find(function(c){return c.__initialFixedPos&&!c.__disposeControlsAfterDrag});u?u.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&t.forceEngine==="d3"){var l=t._dragControls=new Hy(t.graphData.nodes.map(function(c){return c.__threeObj}).filter(function(c){return c}),s,r.domElement);l.addEventListener("dragstart",function(c){var d=fn(c.object);if(d){o.enabled=!1,c.object.__initialPos=c.object.position.clone(),c.object.__prevPos=c.object.position.clone();var h=d.__data;!h.__initialFixedPos&&(h.__initialFixedPos={fx:h.fx,fy:h.fy,fz:h.fz}),!h.__initialPos&&(h.__initialPos={x:h.x,y:h.y,z:h.z}),["x","y","z"].forEach(function(f){return h["f".concat(f)]=h[f]}),r.domElement.classList.add("grabbable")}}),l.addEventListener("drag",function(c){var d=fn(c.object);if(d){if(!c.object.hasOwnProperty("__graphObjType")){var h=c.object.__initialPos,f=c.object.__prevPos,p=c.object.position;d.position.add(p.clone().sub(f)),f.copy(p),p.copy(h)}var g=d.__data,m=d.position,y={x:m.x-g.x,y:m.y-g.y,z:m.z-g.z};["x","y","z"].forEach(function(_){return g["f".concat(_)]=g[_]=m[_]}),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),g.__dragged=!0,t.onNodeDrag(g,y)}}),l.addEventListener("dragend",function(c){var d=fn(c.object);if(d){delete c.object.__initialPos,delete c.object.__prevPos;var h=d.__data;h.__disposeControlsAfterDrag&&(l.dispose(),delete h.__disposeControlsAfterDrag);var f=h.__initialFixedPos,p=h.__initialPos,g={x:p.x-h.x,y:p.y-h.y,z:p.z-h.z};if(f&&(["x","y","z"].forEach(function(y){var _="f".concat(y);f[_]===void 0&&delete h[_]}),delete h.__initialFixedPos,delete h.__initialPos,h.__dragged&&(delete h.__dragged,t.onNodeDragEnd(h,g))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls){var m;o.enabled=!0,o._status&&((m=o._onPointerCancel)===null||m===void 0||m.call(o)),o.domElement&&o.domElement.ownerDocument&&o.domElement.ownerDocument.dispatchEvent(new PointerEvent("pointerup",{pointerType:"touch"}))}r.domElement.classList.remove("grabbable")}})}}),mu.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(u,l){var c=fn(u);if(!c)return 1;var d=fn(l);if(!d)return-1;var h=function(p){return p.__graphObjType==="node"};return h(d)-h(c)}).tooltipContent(function(u){var l=fn(u);return l&&fe(t["".concat(l.__graphObjType,"Label")])(l.__data)||""}).hoverDuringDrag(!1).onHover(function(u){var l=fn(u);if(l!==t.hoverObj){var c=t.hoverObj?t.hoverObj.__graphObjType:null,d=t.hoverObj?t.hoverObj.__data:null,h=l?l.__graphObjType:null,f=l?l.__data:null;if(c&&c!==h){var p=t["on".concat(c==="node"?"Node":"Link","Hover")];p&&p(null,d)}if(h){var g=t["on".concat(h==="node"?"Node":"Link","Hover")];g&&g(f,c===h?d:null)}r.domElement.classList[(l&&t["on".concat(h==="node"?"Node":"Link","Click")]||!l&&t.onBackgroundClick)&&fe(t.showPointerCursor)(f)?"add":"remove"]("clickable"),t.hoverObj=l}}).clickAfterDrag(!1).onClick(function(u,l){var c=fn(u);if(c){var d=t["on".concat(c.__graphObjType==="node"?"Node":"Link","Click")];d&&d(c.__data,l)}else t.onBackgroundClick&&t.onBackgroundClick(l)}).onRightClick(function(u,l){var c=fn(u);if(c){var d=t["on".concat(c.__graphObjType==="node"?"Node":"Link","RightClick")];d&&d(c.__data,l)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(l)}),this._animationCycle()}});function fn(i){for(var e=i;e&&!e.hasOwnProperty("__graphObjType");)e=e.parent;return e}export{GC as default};
|