@origintrail-official/dkg-node-ui 0.0.1-dev.1773506972.23bf9c0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +49 -0
  3. package/dist/api.d.ts +30 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +805 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/chat-assistant.d.ts +68 -0
  8. package/dist/chat-assistant.d.ts.map +1 -0
  9. package/dist/chat-assistant.js +663 -0
  10. package/dist/chat-assistant.js.map +1 -0
  11. package/dist/chat-memory.d.ts +171 -0
  12. package/dist/chat-memory.d.ts.map +1 -0
  13. package/dist/chat-memory.js +985 -0
  14. package/dist/chat-memory.js.map +1 -0
  15. package/dist/chat-persistence-queue.d.ts +67 -0
  16. package/dist/chat-persistence-queue.d.ts.map +1 -0
  17. package/dist/chat-persistence-queue.js +245 -0
  18. package/dist/chat-persistence-queue.js.map +1 -0
  19. package/dist/db.d.ts +402 -0
  20. package/dist/db.d.ts.map +1 -0
  21. package/dist/db.js +887 -0
  22. package/dist/db.js.map +1 -0
  23. package/dist/gelf-push-worker.d.ts +67 -0
  24. package/dist/gelf-push-worker.d.ts.map +1 -0
  25. package/dist/gelf-push-worker.js +147 -0
  26. package/dist/gelf-push-worker.js.map +1 -0
  27. package/dist/index.d.ts +20 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +12 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/llm/capability-resolver.d.ts +3 -0
  32. package/dist/llm/capability-resolver.d.ts.map +1 -0
  33. package/dist/llm/capability-resolver.js +21 -0
  34. package/dist/llm/capability-resolver.js.map +1 -0
  35. package/dist/llm/client.d.ts +23 -0
  36. package/dist/llm/client.d.ts.map +1 -0
  37. package/dist/llm/client.js +91 -0
  38. package/dist/llm/client.js.map +1 -0
  39. package/dist/llm/provider-adapter.d.ts +16 -0
  40. package/dist/llm/provider-adapter.d.ts.map +1 -0
  41. package/dist/llm/provider-adapter.js +199 -0
  42. package/dist/llm/provider-adapter.js.map +1 -0
  43. package/dist/llm/types.d.ts +64 -0
  44. package/dist/llm/types.d.ts.map +1 -0
  45. package/dist/llm/types.js +2 -0
  46. package/dist/llm/types.js.map +1 -0
  47. package/dist/metrics-collector.d.ts +36 -0
  48. package/dist/metrics-collector.d.ts.map +1 -0
  49. package/dist/metrics-collector.js +155 -0
  50. package/dist/metrics-collector.js.map +1 -0
  51. package/dist/operation-tracker.d.ts +43 -0
  52. package/dist/operation-tracker.d.ts.map +1 -0
  53. package/dist/operation-tracker.js +195 -0
  54. package/dist/operation-tracker.js.map +1 -0
  55. package/dist/structured-logger.d.ts +16 -0
  56. package/dist/structured-logger.d.ts.map +1 -0
  57. package/dist/structured-logger.js +41 -0
  58. package/dist/structured-logger.js.map +1 -0
  59. package/dist/telemetry.d.ts +35 -0
  60. package/dist/telemetry.d.ts.map +1 -0
  61. package/dist/telemetry.js +45 -0
  62. package/dist/telemetry.js.map +1 -0
  63. package/dist-ui/assets/3d-force-graph-nMUNmvtB.js +964 -0
  64. package/dist-ui/assets/AgentHub-XKCM9uYQ.js +65 -0
  65. package/dist-ui/assets/AppHost-DoLIi89g.js +1 -0
  66. package/dist-ui/assets/Apps-Cc8HfqfD.js +1 -0
  67. package/dist-ui/assets/Dashboard-D5q6MK78.js +2 -0
  68. package/dist-ui/assets/Explorer-B80RVksc.js +64 -0
  69. package/dist-ui/assets/N3Parser-Q_-1ZY5E.js +7 -0
  70. package/dist-ui/assets/Settings-CG7-7GM-.js +71 -0
  71. package/dist-ui/assets/hooks-BLTFNmyP.js +1 -0
  72. package/dist-ui/assets/index-8_35CUX2.js +192 -0
  73. package/dist-ui/assets/index-CKZq_ZB-.css +1 -0
  74. package/dist-ui/assets/index-DH-l6lM0.js +76 -0
  75. package/dist-ui/assets/jsonld-32FQRO67-DhbO8O6B.js +2 -0
  76. package/dist-ui/assets/jsonld-BFI4wECl.js +62 -0
  77. package/dist-ui/assets/ntriples-ZWBY2WET-nIpilpjf.js +1 -0
  78. package/dist-ui/assets/ordinal-DIohFSkg.js +1 -0
  79. package/dist-ui/assets/renderer-3d-2EVDZII7-DsxBsJvs.js +2 -0
  80. package/dist-ui/assets/three.module-uCjFke6H.js +4019 -0
  81. package/dist-ui/assets/turtle-JJPK7LJ5-zezDJZEp.js +1 -0
  82. package/dist-ui/favicon.png +0 -0
  83. package/dist-ui/index.html +14 -0
  84. package/package.json +58 -0
@@ -0,0 +1,964 @@
1
+ import{C as To,R as yh,M as Ze,T as dn,V as ce,P as vo,a as I,b as Et,B as Zs,c as Ut,S as Zu,d as Ct,e as bh,f as Gi,L as jg,G as _h,g as xh,h as Th,i as qg,Q as Hg,j as vh,k as Xg,l as Kg,w as z,H as it,m as Ju,N as tr,n as Yg,o as So,p as Ge,q as G,r as Ve,s as Yr,t as Ot,u as Ft,v as Oe,F as Qg,x as Zg,y as ht,z as Cs,D as rr,W as Ji,A as Kt,E as Jg,I as Sh,J as em,K as el,O as Nh,U as tm,X as nm,Y as rm,Z as sm,_ as im,$ as om,a0 as am,a1 as um,a2 as tl,a3 as Rh,a4 as Qt,a5 as nl,a6 as Hl,a7 as Ws,a8 as lm,a9 as cm,aa as bt,ab as Bn,ac as je,ad as Dn,ae as Fn,af as An,ag as Ms,ah as an,ai as wn,aj as kr,ak as dm,al as rl,am as sl,an as Ya,ao as Mr,ap as re,aq as hm,ar as Js,as as No,at as Gr,au as fm,av as eo,aw as st,ax as Ro,ay as js,az as wo,aA as sr,aB as Qa,aC as qs,aD as wh,aE as Bt,aF as Ah,aG as Eh,aH as Ch,aI as Mh,aJ as Ph,aK as Ao,aL as Bh,aM as Dh,aN as Xl,aO as Vr,aP as vt,aQ as pm,aR as Fh,aS as Lh,aT as Uh,aU as Oh,aV as Ih,aW as kh,aX as Gh,aY as Vh,aZ as $h,a_ as zh,a$ as Wh,b0 as jh,b1 as gm,b2 as mm,b3 as ym,b4 as $r,b5 as to,b6 as no,b7 as ro,b8 as ir,b9 as qh,ba as Hh,bb as Xh,bc as Kh,bd as Yh,be as Qh,bf as Zh,bg as Jh,bh as bm,bi as _m,bj as ef,bk as tf,bl as Ps,bm as Bs,bn as Pr,bo as xm,bp as il,bq as ol,br as al,bs as hn,bt as ul,bu as ll,bv as Vi,bw as $i,bx as zi,by as Wi,bz as Kl,bA as Yl,bB as Ql,bC as Zl,bD as Za,bE as Ja,bF as eu,bG as tu,bH as nu,bI as so,bJ as ru,bK as su,bL as iu,bM as ou,bN as au,bO as uu,bP as lu,bQ as cu,bR as du,bS as hu,bT as fu,bU as pu,bV as gu,bW as mu,bX as yu,bY as bu,bZ as _u,b_ as xu,b$ as io,c0 as Tu,c1 as nf,c2 as Tm,c3 as vm,c4 as Sm,c5 as Nm,c6 as Rm,c7 as wm,c8 as Am,c9 as Em,ca as Cm,cb as Mm,cc as oo,cd as Pm,ce as cl,cf as dl,cg as Bm,ch as Dm,ci as Fm,cj as Lm,ck as Um,cl as Om,cm as Im,cn as km,co as Gm,cp as Vm,cq as $m,cr as zm,cs as Wm,ct as jm,cu as qm,cv as Hm,cw as Xm,cx as Km,cy as Ym,cz as Qm,cA as Zm,cB as rf,cC as Jm,cD as ey,cE as ty,cF as ny,cG as ao,cH as sf,cI as ry,cJ as of,cK as af,cL as sy,cM as uf,cN as iy,cO as oy,cP as ay,cQ as uy,cR as ji,cS as uo,cT as lo,cU as Wo,cV as jo,cW as ly,cX as cy,cY as dy,cZ as hy,c_ as fy,c$ as hl,d0 as py,d1 as gy,d2 as my,d3 as yy,d4 as Jl,d5 as by,d6 as ec,d7 as _y,d8 as xy,d9 as lf,da as Ty,db as vy}from"./three.module-uCjFke6H.js";import{J as Sy}from"./index-DH-l6lM0.js";import{i as fe,s as Ny,a as fl,f as Ry,b as wy,c as Ay,d as Ey,e as Cy,t as cf,g as My,G as Py,T as tc,E as nc}from"./index-8_35CUX2.js";import{o as By,m as Dy,d as Fy}from"./ordinal-DIohFSkg.js";function ft(){return ft=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},ft.apply(null,arguments)}function Hs(i,e){return Hs=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},Hs(i,e)}function Ly(i,e){i.prototype=Object.create(e.prototype),i.prototype.constructor=i,Hs(i,e)}function Uy(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}const Lr=new vo,un=new ce,df=new I,qo=new ce,qi=new ce,co=new I,vu=new I,hf=new Et,ff=new I,pf=new I;let tt=null,jt=null;const ln=[],Ln={NONE:-1,PAN:0,ROTATE:1};class Oy extends To{constructor(e,t,n=null){super(t,n),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new yh,this.mouseButtons={LEFT:Ze.PAN,MIDDLE:Ze.PAN,RIGHT:Ze.ROTATE},this.touches={ONE:dn.PAN},this._onPointerMove=Iy.bind(this),this._onPointerDown=ky.bind(this),this._onPointerCancel=Gy.bind(this),this._onContextMenu=Vy.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="auto",this.domElement.style.cursor=""}dispose(){this.disconnect()}_updatePointer(e){const t=this.domElement.getBoundingClientRect();un.x=(e.clientX-t.left)/t.width*2-1,un.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 Ze.PAN:case dn.PAN:this.state=Ln.PAN;break;case Ze.ROTATE:case dn.ROTATE:this.state=Ln.ROTATE;break;default:this.state=Ln.NONE}}}function Iy(i){const e=this.object,t=this.domElement,n=this.raycaster;if(this.enabled!==!1){if(this._updatePointer(i),n.setFromCamera(un,e),tt)this.state===Ln.PAN?n.ray.intersectPlane(Lr,co)&&(tt.position.copy(co.sub(df).applyMatrix4(hf)),this.dispatchEvent({type:"drag",object:tt})):this.state===Ln.ROTATE&&(qo.subVectors(un,qi).multiplyScalar(this.rotateSpeed),tt.rotateOnWorldAxis(ff,qo.x),tt.rotateOnWorldAxis(pf.normalize(),-qo.y),this.dispatchEvent({type:"drag",object:tt})),qi.copy(un);else if(i.pointerType==="mouse"||i.pointerType==="pen")if(ln.length=0,n.setFromCamera(un,e),n.intersectObjects(this.objects,this.recursive,ln),ln.length>0){const r=ln[0].object;Lr.setFromNormalAndCoplanarPoint(e.getWorldDirection(Lr.normal),vu.setFromMatrixPosition(r.matrixWorld)),jt!==r&&jt!==null&&(this.dispatchEvent({type:"hoveroff",object:jt}),t.style.cursor="auto",jt=null),jt!==r&&(this.dispatchEvent({type:"hoveron",object:r}),t.style.cursor="pointer",jt=r)}else jt!==null&&(this.dispatchEvent({type:"hoveroff",object:jt}),t.style.cursor="auto",jt=null);qi.copy(un)}}function ky(i){const e=this.object,t=this.domElement,n=this.raycaster;this.enabled!==!1&&(this._updatePointer(i),this._updateState(i),ln.length=0,n.setFromCamera(un,e),n.intersectObjects(this.objects,this.recursive,ln),ln.length>0&&(this.transformGroup===!0?tt=gf(ln[0].object):tt=ln[0].object,Lr.setFromNormalAndCoplanarPoint(e.getWorldDirection(Lr.normal),vu.setFromMatrixPosition(tt.matrixWorld)),n.ray.intersectPlane(Lr,co)&&(this.state===Ln.PAN?(hf.copy(tt.parent.matrixWorld).invert(),df.copy(co).sub(vu.setFromMatrixPosition(tt.matrixWorld)),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:tt})):this.state===Ln.ROTATE&&(ff.set(0,1,0).applyQuaternion(e.quaternion).normalize(),pf.set(1,0,0).applyQuaternion(e.quaternion).normalize(),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:tt})))),qi.copy(un))}function Gy(){this.enabled!==!1&&(tt&&(this.dispatchEvent({type:"dragend",object:tt}),tt=null),this.domElement.style.cursor=jt?"pointer":"auto",this.state=Ln.NONE)}function Vy(i){this.enabled!==!1&&i.preventDefault()}function gf(i,e=null){return i.isGroup&&(e=i),i.parent===null?e:gf(i.parent,e)}function $y(i){Wy(i);const e=zy(i);return i.on=e.on,i.off=e.off,i.fire=e.fire,i}function zy(i){let e=Object.create(null);return{on:function(t,n,r){if(typeof n!="function")throw new Error("callback is expected to be a function");let s=e[t];return s||(s=e[t]=[]),s.push({callback:n,ctx:r}),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 r;arguments.length>1&&(r=Array.prototype.slice.call(arguments,1));for(let s=0;s<n.length;++s){const o=n[s];o.callback.apply(o.ctx,r)}return i}}}function Wy(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 jy(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={},r=0,s=i.multigraph?A:T,o=[],a=F,u=F,l=F,c=F,d={version:20,addNode:g,addLink:_,removeLink:E,removeNode:y,getNode:m,getNodeCount:B,getLinkCount:S,getEdgeCount:S,getLinksCount:S,getNodesCount:B,getLinks:v,forEachNode:ye,forEachLinkedNode:ne,forEachLink:te,beginUpdate:l,endUpdate:c,clear:ee,hasLink:O,hasNode:m,getLink:O,getLinkById:Y};return $y(d),h(),d;function h(){var k=d.on;d.on=q;function q(){return d.beginUpdate=l=V,d.endUpdate=c=K,a=p,u=f,d.on=k,k.apply(d,arguments)}}function p(k,q){o.push({link:k,changeType:q})}function f(k,q){o.push({node:k,changeType:q})}function g(k,q){if(k===void 0)throw new Error("Invalid node identifier");l();var ie=m(k);return ie?(ie.data=q,u(ie,"update")):(ie=new qy(k,q),u(ie,"add")),e.set(k,ie),c(),ie}function m(k){return e.get(k)}function y(k){var q=m(k);if(!q)return!1;l();var ie=q.links;return ie&&(ie.forEach(D),q.links=null),e.delete(k),u(q,"remove"),c(),!0}function _(k,q,ie){l();var Be=m(k)||g(k),M=m(q)||g(q),L=s(k,q,ie),X=t.has(L.id);return t.set(L.id,L),rc(Be,L),k!==q&&rc(M,L),a(L,X?"update":"add"),c(),L}function T(k,q,ie){var Be=oi(k,q),M=t.get(Be);return M?(M.data=ie,M):new sc(k,q,ie,Be)}function A(k,q,ie){var Be=oi(k,q),M=n.hasOwnProperty(Be);if(M||O(k,q)){M||(n[Be]=0);var L="@"+ ++n[Be];Be=oi(k+L,q+L)}return new sc(k,q,ie,Be)}function B(){return e.size}function S(){return t.size}function v(k){var q=m(k);return q?q.links:null}function E(k,q){return q!==void 0&&(k=O(k,q)),D(k)}function D(k){if(!k||!t.get(k.id))return!1;l(),t.delete(k.id);var q=m(k.fromId),ie=m(k.toId);return q&&q.links.delete(k),ie&&ie.links.delete(k),a(k,"remove"),c(),!0}function O(k,q){if(!(k===void 0||q===void 0))return t.get(oi(k,q))}function Y(k){if(k!==void 0)return t.get(k)}function ee(){l(),ye(function(k){y(k.id)}),c()}function te(k){if(typeof k=="function")for(var q=t.values(),ie=q.next();!ie.done;){if(k(ie.value))return!0;ie=q.next()}}function ne(k,q,ie){var Be=m(k);if(Be&&Be.links&&typeof q=="function")return ie?le(Be.links,k,q):ue(Be.links,k,q)}function ue(k,q,ie){for(var Be,M=k.values(),L=M.next();!L.done;){var X=L.value,be=X.fromId===q?X.toId:X.fromId;if(Be=ie(e.get(be),X),Be)return!0;L=M.next()}}function le(k,q,ie){for(var Be,M=k.values(),L=M.next();!L.done;){var X=L.value;if(X.fromId===q&&(Be=ie(e.get(X.toId),X),Be))return!0;L=M.next()}}function F(){}function V(){r+=1}function K(){r-=1,r===0&&o.length>0&&(d.fire("changed",o),o.length=0)}function ye(k){if(typeof k!="function")throw new Error("Function is expected to iterate over graph nodes. You passed "+k);for(var q=e.values(),ie=q.next();!ie.done;){if(k(ie.value))return!0;ie=q.next()}}}function qy(i,e){this.id=i,this.links=null,this.data=e}function rc(i,e){i.links?i.links.add(e):i.links=new Set([e])}function sc(i,e,t,n){this.fromId=i,this.toId=e,this.data=t,this.id=n}function oi(i,e){return i.toString()+"👉 "+e.toString()}var ai={exports:{}},br={exports:{}},Ho,ic;function mf(){return ic||(ic=1,Ho=function(e){return e===0?"x":e===1?"y":e===2?"z":"c"+(e+1)}),Ho}var Xo,oc;function Qr(){if(oc)return Xo;oc=1;const i=mf();return Xo=function(t){return n;function n(r,s){let o=s&&s.indent||0,a=s&&s.join!==void 0?s.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+r.replace(/{var}/g,d))}return l.join(a)}},Xo}var ac;function Hy(){if(ac)return br.exports;ac=1;const i=Qr();br.exports=e,br.exports.generateCreateBodyFunctionBody=t,br.exports.getVectorCode=r,br.exports.getBodyCode=n;function e(s,o){let a=t(s,o),{Body:u}=new Function(a)();return u}function t(s,o){return`
5
+ ${r(s,o)}
6
+ ${n(s)}
7
+ return {Body: Body, Vector: Vector};
8
+ `}function n(s){let o=i(s),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 r(s,o){let a=i(s),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 br.exports}var rn={exports:{}},uc;function Xy(){if(uc)return rn.exports;uc=1;const i=Qr(),e=mf();rn.exports=t,rn.exports.generateQuadTreeFunctionBody=n,rn.exports.getInsertStackCode=u,rn.exports.getQuadNodeCode=a,rn.exports.isSamePosition=r,rn.exports.getChildBodyCode=o,rn.exports.setChildBodyCode=s;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
+ ${r(l)}
54
+ ${o(l)}
55
+ ${s(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
+ ${f()}
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
+ ${p(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 p(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 f(){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 r(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 s(l){var c=Math.pow(2,l);return`
303
+ function setChild(node, idx, child) {
304
+ ${d()}
305
+ }`;function d(){let h=[];for(let p=0;p<c;++p){let f=p===0?" ":" else ";h.push(`${f}if (idx === ${p}) node.quad${p} = 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 p=0;p<h;++p)d.push(` if (idx === ${p}) return node.quad${p};`);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
+ ${p(" 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 p(f){let g=[];for(let m=0;m<d;++m)g.push(`${f}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 rn.exports}var ui={exports:{}},lc;function Ky(){if(lc)return ui.exports;lc=1,ui.exports=e,ui.exports.generateFunctionBody=t;const i=Qr();function e(n){let r=t(n);return new Function("bodies","settings","random",r)}function t(n){let r=i(n);return`
375
+ var boundingBox = {
376
+ ${r("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 ${r("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
+ ${r("base_{var} += neighborPos.{var};",{indent:10})}
393
+ }
394
+
395
+ ${r("base_{var} /= neighbors.length;",{indent:8})}
396
+ } else {
397
+ ${r("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}
398
+ }
399
+
400
+ var springLength = settings.springLength;
401
+ return {
402
+ ${r("{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
+ ${r("var max_{var} = -Infinity;",{indent:4})}
412
+ ${r("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
+ ${r("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}
418
+ ${r("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}
419
+ }
420
+
421
+ ${r("boundingBox.min_{var} = min_{var};",{indent:4})}
422
+ ${r("boundingBox.max_{var} = max_{var};",{indent:4})}
423
+ }
424
+
425
+ function resetBoundingBox() {
426
+ ${r("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}
427
+ }
428
+ `}return ui.exports}var li={exports:{}},cc;function Yy(){if(cc)return li.exports;cc=1;const i=Qr();li.exports=e,li.exports.generateCreateDragForceFunctionBody=t;function e(n){let r=t(n);return new Function("options",r)}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 li.exports}var ci={exports:{}},dc;function Qy(){if(dc)return ci.exports;dc=1;const i=Qr();ci.exports=e,ci.exports.generateCreateSpringForceFunctionBody=t;function e(n){let r=t(n);return new Function("options","random",r)}function t(n){let r=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
+ ${r("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}
449
+ var r = Math.sqrt(${r("d{var} * d{var}",{join:" + "})});
450
+
451
+ if (r === 0) {
452
+ ${r("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}
453
+ r = Math.sqrt(${r("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
+ ${r("body1.force.{var} += coefficient * d{var}",{indent:6})};
460
+ body1.springCount += 1;
461
+ body1.springLength += r;
462
+
463
+ ${r("body2.force.{var} -= coefficient * d{var}",{indent:6})};
464
+ body2.springCount += 1;
465
+ body2.springLength += r;
466
+ }
467
+ };
468
+ `}return ci.exports}var di={exports:{}},hc;function Zy(){if(hc)return di.exports;hc=1;const i=Qr();di.exports=e,di.exports.generateIntegratorFunctionBody=t;function e(n){let r=t(n);return new Function("bodies","timeStep","adaptiveTimeStepWeight",r)}function t(n){let r=i(n);return`
469
+ var length = bodies.length;
470
+ if (length === 0) return 0;
471
+
472
+ ${r("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
+ ${r("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}
485
+ ${r("var v{var} = body.velocity.{var};",{indent:4})}
486
+ var v = Math.sqrt(${r("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
+ ${r("body.velocity.{var} = v{var} / v;",{indent:6})}
492
+ }
493
+
494
+ ${r("d{var} = timeStep * body.velocity.{var};",{indent:4})}
495
+
496
+ ${r("body.pos.{var} += d{var};",{indent:4})}
497
+
498
+ ${r("t{var} += Math.abs(d{var});",{indent:4})}
499
+ }
500
+
501
+ return (${r("t{var} * t{var}",{join:" + "})})/length;
502
+ `}return di.exports}var Ko,fc;function Jy(){if(fc)return Ko;fc=1,Ko=i;function i(e,t,n,r){this.from=e,this.to=t,this.length=n,this.coefficient=r}return Ko}var Yo,pc;function eb(){if(pc)return Yo;pc=1,Yo=i;function i(e,t){var n;if(e||(e={}),t){for(n in t)if(t.hasOwnProperty(n)){var r=e.hasOwnProperty(n),s=typeof t[n],o=!r||typeof e[n]!==s;o?e[n]=t[n]:s==="object"&&(e[n]=i(e[n],t[n]))}}return e}return Yo}var Qo,gc;function yf(){if(gc)return Qo;gc=1;function i(n){t(n);const r=e(n);return n.on=r.on,n.off=r.off,n.fire=r.fire,n}function e(n){let r=Object.create(null);return{on:function(s,o,a){if(typeof o!="function")throw new Error("callback is expected to be a function");let u=r[s];return u||(u=r[s]=[]),u.push({callback:o,ctx:a}),n},off:function(s,o){if(typeof s>"u")return r=Object.create(null),n;if(r[s])if(typeof o!="function")delete r[s];else{const a=r[s];for(let u=0;u<a.length;++u)a[u].callback===o&&a.splice(u,1)}return n},fire:function(s){const o=r[s];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 r=["on","fire","off"];for(let s=0;s<r.length;++s)if(n.hasOwnProperty(r[s]))throw new Error("Subject cannot be eventified, since it already has property '"+r[s]+"'")}return Qo=i,Qo}var us={exports:{}},mc;function tb(){if(mc)return us.exports;mc=1,us.exports=i,us.exports.random=i,us.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=s,e.prototype.uniform=s,e.prototype.gaussian=t,e.prototype.random=s;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(r(1+u)*Math.sin(Math.PI*u/2)/(r((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 r(u){return Math.sqrt(2*Math.PI/u)*Math.pow(1/Math.E*(u+1/(12*u-1/(10*u))),u)}function s(){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 p,f,g;for(p=u.length-1;p>0;--p)f=c.next(p+1),g=u[f],u[f]=u[p],u[p]=g;return u}function h(p){var f,g,m;for(f=u.length-1;f>0;--f)g=c.next(f+1),m=u[g],u[g]=u[f],u[f]=m,p(m);u.length&&p(u[0])}}return us.exports}var Zo,yc;function bc(){if(yc)return Zo;yc=1,Zo=a;var i=Hy(),e=Xy(),t=Ky(),n=Yy(),r=Qy(),s=Zy(),o={};function a(c){var d=Jy(),h=eb(),p=yf();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 f=o[c.dimensions];if(!f){var g=c.dimensions;f={Body:i(g,c.debug),createQuadTree:e(g),createBounds:t(g),createDragForce:n(g),createSpringForce:r(g),integrate:s(g)},o[g]=f}var m=f.Body,y=f.createQuadTree,_=f.createBounds,T=f.createDragForce,A=f.createSpringForce,B=f.integrate,S=M=>new m(M),v=tb().random(42),E=[],D=[],O=y(c,v),Y=_(E,c,v),ee=A(c,v),te=T(c),ne=0,ue=[],le=new Map,F=0;ye("nbody",ie),ye("spring",Be);var V={bodies:E,quadTree:O,springs:D,settings:c,addForce:ye,removeForce:k,getForces:q,step:function(){for(var M=0;M<ue.length;++M)ue[M](F);var L=B(E,c.timeStep,c.adaptiveTimeStepWeight);return F+=1,L},addBody:function(M){if(!M)throw new Error("Body is required");return E.push(M),M},addBodyAt:function(M){if(!M)throw new Error("Body position is required");var L=S(M);return E.push(L),L},removeBody:function(M){if(M){var L=E.indexOf(M);if(!(L<0))return E.splice(L,1),E.length===0&&Y.reset(),!0}},addSpring:function(M,L,X,be){if(!M||!L)throw new Error("Cannot add null spring to force simulator");typeof X!="number"&&(X=-1);var Ue=new d(M,L,X,be>=0?be:-1);return D.push(Ue),Ue},getTotalMovement:function(){return ne},removeSpring:function(M){if(M){var L=D.indexOf(M);if(L>-1)return D.splice(L,1),!0}},getBestNewBodyPosition:function(M){return Y.getBestNewPosition(M)},getBBox:K,getBoundingBox:K,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(M){return M!==void 0?(c.gravity=M,O.options({gravity:M}),this):c.gravity},theta:function(M){return M!==void 0?(c.theta=M,O.options({theta:M}),this):c.theta},random:v};return u(c,V),p(V),V;function K(){return Y.update(),Y.box}function ye(M,L){if(le.has(M))throw new Error("Force "+M+" is already added");le.set(M,L),ue.push(L)}function k(M){var L=ue.indexOf(le.get(M));L<0||(ue.splice(L,1),le.delete(M))}function q(){return le}function ie(){if(E.length!==0){O.insertBodies(E);for(var M=E.length;M--;){var L=E[M];L.isPinned||(L.reset(),O.updateBodyForce(L),te.update(L))}}}function Be(){for(var M=D.length;M--;)ee.update(D[M])}}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 p=Number.isFinite(c[h]);p?d[h]=function(f){if(f!==void 0){if(!Number.isFinite(f))throw new Error("Value of "+h+" should be a valid number.");return c[h]=f,d}return c[h]}:d[h]=function(f){return f!==void 0?(c[h]=f,d):c[h]}}}return Zo}var _c;function nb(){if(_c)return ai.exports;_c=1,ai.exports=e,ai.exports.simulator=bc();var i=yf();function e(n,r){if(!n)throw new Error("Graph structure cannot be undefined");var s=r&&r.createSimulator||bc(),o=s(r);if(Array.isArray(r))throw new Error("Physics settings is expected to be an object");var a=n.version>19?le:ue;r&&typeof r.nodeMass=="function"&&(a=r.nodeMass);var u=new Map,l={},c=0,d=o.settings.springTransform||t;S(),T();var h=!1,p={step:function(){if(c===0)return f(!0),!0;var F=o.step();p.lastMove=F,p.fire("step");var V=F/c,K=V<=.01;return f(K),K},getNodePosition:function(F){return ne(F).pos},setNodePosition:function(F){var V=ne(F);V.setPosition.apply(V,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(F){var V=l[F];if(V)return{from:V.from.pos,to:V.to.pos}},getGraphRect:function(){return o.getBBox()},forEachBody:g,pinNode:function(F,V){var K=ne(F.id);K.isPinned=!!V},isNodePinned:function(F){return ne(F.id).isPinned},dispose:function(){n.off("changed",B),p.fire("disposed")},getBody:_,getSpring:y,getForceVectorLength:m,simulator:o,graph:n,lastMove:0};return i(p),p;function f(F){h!==F&&(h=F,A(F))}function g(F){u.forEach(F)}function m(){var F=0,V=0;return g(function(K){F+=Math.abs(K.force.x),V+=Math.abs(K.force.y)}),Math.sqrt(F*F+V*V)}function y(F,V){var K;if(V===void 0)typeof F!="object"?K=F:K=F.id;else{var ye=n.hasLink(F,V);if(!ye)return;K=ye.id}return l[K]}function _(F){return u.get(F)}function T(){n.on("changed",B)}function A(F){p.fire("stable",F)}function B(F){for(var V=0;V<F.length;++V){var K=F[V];K.changeType==="add"?(K.node&&v(K.node.id),K.link&&D(K.link)):K.changeType==="remove"&&(K.node&&E(K.node),K.link&&O(K.link))}c=n.getNodesCount()}function S(){c=0,n.forEachNode(function(F){v(F.id),c+=1}),n.forEachLink(D)}function v(F){var V=u.get(F);if(!V){var K=n.getNode(F);if(!K)throw new Error("initBody() was called with unknown node id");var ye=K.position;if(!ye){var k=Y(K);ye=o.getBestNewBodyPosition(k)}V=o.addBodyAt(ye),V.id=F,u.set(F,V),ee(F),te(K)&&(V.isPinned=!0)}}function E(F){var V=F.id,K=u.get(V);K&&(u.delete(V),o.removeBody(K))}function D(F){ee(F.fromId),ee(F.toId);var V=u.get(F.fromId),K=u.get(F.toId),ye=o.addSpring(V,K,F.length);d(F,ye),l[F.id]=ye}function O(F){var V=l[F.id];if(V){var K=n.getNode(F.fromId),ye=n.getNode(F.toId);K&&ee(K.id),ye&&ee(ye.id),delete l[F.id],o.removeSpring(V)}}function Y(F){var V=[];if(!F.links)return V;for(var K=Math.min(F.links.length,2),ye=0;ye<K;++ye){var k=F.links[ye],q=k.fromId!==F.id?u.get(k.fromId):u.get(k.toId);q&&q.pos&&V.push(q)}return V}function ee(F){var V=u.get(F);if(V.mass=a(F),Number.isNaN(V.mass))throw new Error("Node mass should be a number")}function te(F){return F&&(F.isPinned||F.data&&F.data.isPinned)}function ne(F){var V=u.get(F);return V||(v(F),V=u.get(F)),V}function ue(F){var V=n.getLinks(F);return V?1+V.length/3:1}function le(F){var V=n.getLinks(F);return V?1+V.size/3:1}}function t(){}return ai.exports}var rb=nb();const sb=Sy(rb);function Su(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 ib(i){if(Array.isArray(i))return i}function ob(i){if(Array.isArray(i))return Su(i)}function bf(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 ab(i,e){if(e.has(i))throw new TypeError("Cannot initialize the same private elements twice on an object")}function ub(i,e){if(!(i instanceof e))throw new TypeError("Cannot call a class as a function")}function et(i,e){return i.get(bf(i,e))}function _r(i,e,t){ab(i,e),e.set(i,t)}function hi(i,e,t){return i.set(bf(i,e),t),t}function lb(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,bb(n.key),n)}}function cb(i,e,t){return e&&lb(i.prototype,e),Object.defineProperty(i,"prototype",{writable:!1}),i}function db(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function hb(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,r,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(i)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,r=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw r}}return a}}function fb(){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 pb(){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 gb(i,e){return ib(i)||hb(i,e)||_f(i,e)||fb()}function mb(i){return ob(i)||db(i)||_f(i)||pb()}function yb(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 bb(i){var e=yb(i,"string");return typeof e=="symbol"?e:e+""}function _f(i,e){if(i){if(typeof i=="string")return Su(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)?Su(i,e):void 0}}var xr=new WeakMap,ls=new WeakMap,Tr=new WeakMap,Jo=new WeakMap,ea=new WeakMap,ta=new WeakMap,_b=(function(){function i(){ub(this,i),_r(this,xr,new Map),_r(this,ls,new Map),_r(this,Tr,function(e){return e}),_r(this,Jo,function(){return{}}),_r(this,ea,function(){}),_r(this,ta,function(){})}return cb(i,[{key:"getObj",value:function(t){return et(xr,this).get(et(Tr,this).call(this,t))}},{key:"getData",value:function(t){return et(ls,this).get(t)}},{key:"entries",value:function(){return mb(et(ls,this).entries()).map(function(t){var n=gb(t,2),r=n[0],s=n[1];return[s,r]})}},{key:"id",value:function(t){return hi(Tr,this,fe(t)),this}},{key:"onCreateObj",value:function(t){return hi(Jo,this,t),this}},{key:"onUpdateObj",value:function(t){return hi(ea,this,t),this}},{key:"onRemoveObj",value:function(t){return hi(ta,this,t),this}},{key:"digest",value:function(t){var n=this;t.filter(function(s){return!et(xr,n).has(et(Tr,n).call(n,s))}).forEach(function(s){var o=et(Jo,n).call(n,s);et(xr,n).set(et(Tr,n).call(n,s),o),et(ls,n).set(o,s)});var r=new Map(t.map(function(s){return[et(Tr,n).call(n,s),s]}));return et(xr,this).forEach(function(s,o){r.has(o)?et(ea,n).call(n,s,r.get(o)):(et(ta,n).call(n,s,o),et(xr,n).delete(o),et(ls,n).delete(s))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])})();function Nu(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 xb(i){if(Array.isArray(i))return i}function Tb(i){if(Array.isArray(i))return Nu(i)}function xf(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 vb(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}function Tf(i,e,t){return e=zr(e),Mb(i,pl()?Reflect.construct(e,t||[],zr(i).constructor):e.apply(i,t))}function Sb(i,e){if(e.has(i))throw new TypeError("Cannot initialize the same private elements twice on an object")}function vf(i,e){if(!(i instanceof e))throw new TypeError("Cannot call a class as a function")}function na(i,e){return i.get(xf(i,e))}function xc(i,e,t){Sb(i,e),e.set(i,t)}function Tc(i,e,t){return i.set(xf(i,e),t),t}function Sf(i,e,t){if(pl())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var r=new(i.bind.apply(i,n));return r}function Nb(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,wf(n.key),n)}}function Nf(i,e,t){return e&&Nb(i.prototype,e),Object.defineProperty(i,"prototype",{writable:!1}),i}function Eo(i,e,t){return(e=wf(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Ru(){return Ru=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(i,e,t){var n=Pb(i,e);if(n){var r=Object.getOwnPropertyDescriptor(n,e);return r.get?r.get.call(arguments.length<3?i:t):r.value}},Ru.apply(null,arguments)}function zr(i){return zr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},zr(i)}function Rf(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&&wu(i,e)}function pl(){try{var i=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(pl=function(){return!!i})()}function Rb(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function wb(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,r,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(i)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,r=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw r}}return a}}function Ab(){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 Eb(){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 vc(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,n)}return t}function Cb(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?vc(Object(t),!0).forEach(function(n){Eo(i,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):vc(Object(t)).forEach(function(n){Object.defineProperty(i,n,Object.getOwnPropertyDescriptor(t,n))})}return i}function Mb(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 vb(i)}function wu(i,e){return wu=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},wu(i,e)}function Ds(i,e){return xb(i)||wb(i,e)||Af(i,e)||Ab()}function Pb(i,e){for(;!{}.hasOwnProperty.call(i,e)&&(i=zr(i))!==null;);return i}function ra(i,e,t,n){var r=Ru(zr(i.prototype),e,t);return typeof r=="function"?function(s){return r.apply(t,s)}:r}function Pt(i){return Tb(i)||Rb(i)||Af(i)||Eb()}function Bb(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 wf(i){var e=Bb(i,"string");return typeof e=="symbol"?e:e+""}function Au(i){"@babel/helpers - typeof";return Au=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},Au(i)}function Af(i,e){if(i){if(typeof i=="string")return Nu(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)?Nu(i,e):void 0}}var Ef=function(e){e instanceof Array?e.forEach(Ef):(e.map&&e.map.dispose(),e.dispose())},Cf=function(e){e.geometry&&e.geometry.dispose(),e.material&&Ef(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Cf)},Eu=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),Cf(t)}},sa=new WeakMap,fi=new WeakMap,cs=(function(i){function e(t){var n,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=r.dataBindAttr,o=s===void 0?"__data":s,a=r.objBindAttr,u=a===void 0?"__threeObj":a;return vf(this,e),n=Tf(this,e),Eo(n,"scene",void 0),xc(n,sa,void 0),xc(n,fi,void 0),n.scene=t,Tc(sa,n,o),Tc(fi,n,u),n.onRemoveObj(function(){}),n}return Rf(e,i),Nf(e,[{key:"onCreateObj",value:function(n){var r=this;return ra(e,"onCreateObj",this)([function(s){var o=n(s);return s[na(fi,r)]=o,o[na(sa,r)]=s,r.scene.add(o),o}]),this}},{key:"onRemoveObj",value:function(n){var r=this;return ra(e,"onRemoveObj",this)([function(s,o){var a=ra(e,"getData",r)([s]);n(s,o),r.scene.remove(s),Eu(s),delete a[na(fi,r)]}]),this}}])})(_b),ds=function(e){return isNaN(e)?parseInt(cf(e).toHex(),16):e},ia=function(e){return isNaN(e)?cf(e).getAlpha():1},Db=By(Ny);function Sc(i,e,t){!e||typeof t!="string"||i.filter(function(n){return!n[t]}).forEach(function(n){n[t]=Db(e(n))})}function Fb(i,e){var t=i.nodes,n=i.links,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=r.nodeFilter,o=s===void 0?function(){return!0}:s,a=r.onLoopError,u=a===void 0?function(p){throw"Invalid DAG structure! Found cycle in node path: ".concat(p.join(" -> "),".")}:a,l={};t.forEach(function(p){return l[e(p)]={data:p,out:[],depth:-1,skip:!o(p)}}),n.forEach(function(p){var f=p.source,g=p.target,m=A(f),y=A(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 A(B){return Au(B)==="object"?e(B):B}});var c=[];h(Object.values(l));var d=Object.assign.apply(Object,[{}].concat(Pt(Object.entries(l).filter(function(p){var f=Ds(p,2),g=f[1];return!g.skip}).map(function(p){var f=Ds(p,2),g=f[0],m=f[1];return Eo({},g,m.depth)}))));return d;function h(p){for(var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,m=function(){var A=p[y];if(f.indexOf(A)!==-1){var B=[].concat(Pt(f.slice(f.indexOf(A))),[A]).map(function(S){return e(S.data)});return c.some(function(S){return S.length===B.length&&S.every(function(v,E){return v===B[E]})})||(c.push(B),u(B)),1}g>A.depth&&(A.depth=g,h(A.out,[].concat(Pt(f),[A]),g+(A.skip?0:1)))},y=0,_=p.length;y<_;y++)m()}}var J=window.THREE?window.THREE:{Group:_h,Mesh:Ut,MeshLambertMaterial:bh,Color:Ct,BufferGeometry:Zs,BufferAttribute:Gi,Matrix4:Et,Vector3:I,SphereGeometry:Zu,CylinderGeometry:xh,TubeGeometry:Kg,ConeGeometry:Xg,Line:jg,LineBasicMaterial:vh,QuadraticBezierCurve3:Hg,CubicBezierCurve3:qg,Box3:Th},Nc={graph:jy,forcelayout:sb},Lb=2,oa=new J.BufferGeometry().setAttribute?"setAttribute":"addAttribute",pi=new J.BufferGeometry().applyMatrix4?"applyMatrix4":"applyMatrix",Ub=fl({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(r){return r.json()}).then(function(r){t.fetchingJson=!1,t.onFinishLoading(r),n.graphData(r)}))},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&&r(t.graphData.nodes,"z"),e<2&&r(t.graphData.nodes,"y");function r(s,o){s.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(),r(),s(),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 p=Ds(h,2),f=p[0],g=p[1];if(g){var m=t?f:e.layout.getNodePosition(f[e.nodeId]),y=o(f);(!e.nodePositionUpdate||!e.nodePositionUpdate(y?g.children[0]:g,{x:m.x,y:m.y,z:m.z},f)||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 p=Ds(h,2),f=p[0],g=p[1];if(g){var m=t?f:e.layout.getLinkPosition(e.layout.graph.getLink(f.source,f.target).id),y=m[t?"source":"from"],_=m[t?"target":"to"];if(!(!y||!_||!y.hasOwnProperty("x")||!_.hasOwnProperty("x"))){d(f);var T=c(f);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}},f)&&!T)){var A=30,B=f.__curve,S=g.children.length?g.children[0]:g;if(S.type==="Line"){if(B){var E=B.getPoints(A);S.geometry.getAttribute("position").array.length!==E.length*3&&S.geometry[oa]("position",new J.BufferAttribute(new Float32Array(E.length*3),3)),S.geometry.setFromPoints(E)}else{var v=S.geometry.getAttribute("position");(!v||!v.array||v.array.length!==6)&&S.geometry[oa]("position",v=new J.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}S.geometry.computeBoundingSphere()}else if(S.type==="Mesh")if(B){S.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(S.position.set(0,0,0),S.rotation.set(0,0,0),S.scale.set(1,1,1));var ue=Math.ceil(a(f)*10)/10,le=ue/2,F=new J.TubeGeometry(B,A,le,e.linkResolution,!1);S.geometry.dispose(),S.geometry=F}else{if(!S.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var D=Math.ceil(a(f)*10)/10,O=D/2,Y=new J.CylinderGeometry(O,O,1,e.linkResolution,1,!1);Y[pi](new J.Matrix4().makeTranslation(0,1/2,0)),Y[pi](new J.Matrix4().makeRotationX(Math.PI/2)),S.geometry.dispose(),S.geometry=Y}var ee=new J.Vector3(y.x,y.y||0,y.z||0),te=new J.Vector3(_.x,_.y||0,_.z||0),ne=ee.distanceTo(te);S.position.x=ee.x,S.position.y=ee.y,S.position.z=ee.z,S.scale.z=ne,S.parent.localToWorld(te),S.lookAt(te)}}}}});function d(h){var p=t?h:e.layout.getLinkPosition(e.layout.graph.getLink(h.source,h.target).id),f=p[t?"source":"from"],g=p[t?"target":"to"];if(!(!f||!g||!f.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var m=u(h);if(!m)h.__curve=null;else{var y=new J.Vector3(f.x,f.y||0,f.z||0),_=new J.Vector3(g.x,g.y||0,g.z||0),T=y.distanceTo(_),A,B=l(h);if(T>0){var S=g.x-f.x,v=g.y-f.y||0,E=new J.Vector3().subVectors(_,y),D=E.clone().multiplyScalar(m).cross(S!==0||v!==0?new J.Vector3(0,0,1):new J.Vector3(0,1,0)).applyAxisAngle(E.normalize(),B).add(new J.Vector3().addVectors(y,_).divideScalar(2));A=new J.QuadraticBezierCurve3(y,D,_)}else{var O=m*70,Y=-B,ee=Y+Math.PI/2;A=new J.CubicBezierCurve3(y,new J.Vector3(O*Math.cos(ee),O*Math.sin(ee),0).add(y),new J.Vector3(O*Math.cos(Y),O*Math.sin(Y),0).add(y),_)}h.__curve=A}}}}function r(){var o=fe(e.linkDirectionalArrowRelPos),a=fe(e.linkDirectionalArrowLength),u=fe(e.nodeVal);e.arrowDataMapper.entries().forEach(function(l){var c=Ds(l,2),d=c[0],h=c[1];if(h){var p=t?d:e.layout.getLinkPosition(e.layout.graph.getLink(d.source,d.target).id),f=p[t?"source":"from"],g=p[t?"target":"to"];if(!(!f||!g||!f.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var m=Math.cbrt(Math.max(0,u(f)||1))*e.nodeRelSize,y=Math.cbrt(Math.max(0,u(g)||1))*e.nodeRelSize,_=a(d),T=o(d),A=d.__curve?function(O){return d.__curve.getPoint(O)}:function(O){var Y=function(te,ne,ue,le){return ne[te]+(ue[te]-ne[te])*le||0};return{x:Y("x",f,g,O),y:Y("y",f,g,O),z:Y("z",f,g,O)}},B=d.__curve?d.__curve.getLength():Math.sqrt(["x","y","z"].map(function(O){return Math.pow((g[O]||0)-(f[O]||0),2)}).reduce(function(O,Y){return O+Y},0)),S=m+_+(B-m-y-_)*T,v=A(S/B),E=A((S-_)/B);["x","y","z"].forEach(function(O){return h.position[O]=E[O]});var D=Sf(J.Vector3,Pt(["x","y","z"].map(function(O){return v[O]})));h.parent.localToWorld(D),h.lookAt(D)}}})}function s(){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),p=h[t?"source":"from"],f=h[t?"target":"to"];if(!(!p||!f||!p.hasOwnProperty("x")||!f.hasOwnProperty("x"))){var g=o(u),m=Math.abs(a(u)),y=u.__curve?function(T){return u.__curve.getPoint(T)}:function(T){var A=function(S,v,E,D){return v[S]+(E[S]-v[S])*D||0};return{x:A("x",p,f,T),y:A("y",p,f,T),z:A("z",p,f,T)}},_=[].concat(Pt(c||[]),Pt(d||[]));_.forEach(function(T,A){var B=T.parent.__linkThreeObjType==="singleHopPhotons";if(T.hasOwnProperty("__progressRatio")||(T.__progressRatio=B?0:(A+m)/c.length),T.__progressRatio+=g,T.__progressRatio>=1)if(!B)T.__progressRatio=T.__progressRatio%1;else{T.parent.remove(T),Eu(T);return}var S=T.__progressRatio,v=y(S);T.geometry.type!=="SphereGeometry"&&T.lookAt(v.x,v.y,v.z),["x","y","z"].forEach(function(E){return T.position[E]=v[E]})})}}})}},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new J.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var r=fe(e.linkDirectionalParticleThreeObject)(t);if(r&&e.linkDirectionalParticleThreeObject===r&&(r=r.clone()),!r){var s=fe(e.linkDirectionalParticleWidth),o=Math.ceil(s(t)*10)/10/2,a=e.linkDirectionalParticleResolution,u=new J.SphereGeometry(o,a,a),l=fe(e.linkColor),c=fe(e.linkDirectionalParticleColor),d=c(t)||l(t)||"#f0f0f0",h=new J.Color(ds(d)),p=e.linkOpacity*3,f=new J.MeshLambertMaterial({color:h,transparent:!0,opacity:p});r=new J.Mesh(u,f)}t.__singleHopPhotonsObj.add(r)}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 r(s){var o=[];if(s.geometry){s.geometry.computeBoundingBox();var a=new J.Box3;a.copy(s.geometry.boundingBox).applyMatrix4(s.matrixWorld),o.push(a)}return o.concat.apply(o,Pt((s.children||[]).filter(function(u){return!u.hasOwnProperty("__graphObjType")||u.__graphObjType==="node"&&t(u.__data)}).map(r)))})(e.graphScene);return n.length?Object.assign.apply(Object,Pt(["x","y","z"].map(function(r){return Eo({},r,[Dy(n,function(s){return s.min[r]}),Fy(n,function(s){return s.max[r]})])}))):null}},stateInit:function(){return{d3ForceLayout:wy().force("link",Ay()).force("charge",Ey()).force("center",Cy()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new cs(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new cs(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new cs(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new cs(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(L){return L.some(function(X){return t.hasOwnProperty(X)})};if(e.engineRunning=!1,typeof e.onUpdate=="function"&&e.onUpdate(),e.nodeAutoColorBy!==null&&n(["nodeAutoColorBy","graphData","nodeColor"])&&Sc(e.graphData.nodes,fe(e.nodeAutoColorBy),e.nodeColor),e.linkAutoColorBy!==null&&n(["linkAutoColorBy","graphData","linkColor"])&&Sc(e.graphData.links,fe(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var r=fe(e.nodeThreeObject),s=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(M){var L=r(M),X=s(M);L&&e.nodeThreeObject===L&&(L=L.clone());var be;return L&&!X?be=L:(be=new J.Mesh,be.__graphDefaultObj=!0,L&&X&&be.add(L)),be.__graphObjType="node",be}).onUpdateObj(function(M,L){if(M.__graphDefaultObj){var X=o(L)||1,be=Math.cbrt(X)*e.nodeRelSize,Ue=e.nodeResolution;(!M.geometry.type.match(/^Sphere(Buffer)?Geometry$/)||M.geometry.parameters.radius!==be||M.geometry.parameters.widthSegments!==Ue)&&(l.hasOwnProperty(X)||(l[X]=new J.SphereGeometry(be,Ue,Ue)),M.geometry.dispose(),M.geometry=l[X]);var Ie=a(L),ke=new J.Color(ds(Ie||"#ffffaa")),kt=e.nodeOpacity*ia(Ie);(M.material.type!=="MeshLambertMaterial"||!M.material.color.equals(ke)||M.material.opacity!==kt)&&(c.hasOwnProperty(Ie)||(c[Ie]=new J.MeshLambertMaterial({color:ke,transparent:!0,opacity:kt})),M.material.dispose(),M.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),p=fe(e.linkMaterial),f=fe(e.linkVisibility),g=fe(e.linkColor),m=fe(e.linkWidth),y={},_={},T={},A=e.graphData.links.filter(f);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(M){var L=M.__data&&M.__data.__singleHopPhotonsObj;L&&(L.parent.remove(L),Eu(L),delete M.__data.__singleHopPhotonsObj)}).onCreateObj(function(M){var L=d(M),X=h(M);L&&e.linkThreeObject===L&&(L=L.clone());var be;if(!L||X){var Ue=!!m(M);if(Ue)be=new J.Mesh;else{var Ie=new J.BufferGeometry;Ie[oa]("position",new J.BufferAttribute(new Float32Array(6),3)),be=new J.Line(Ie)}}var ke;return L?X?(ke=new J.Group,ke.__graphDefaultObj=!0,ke.add(be),ke.add(L)):ke=L:(ke=be,ke.__graphDefaultObj=!0),ke.renderOrder=10,ke.__graphObjType="link",ke}).onUpdateObj(function(M,L){if(M.__graphDefaultObj){var X=M.children.length?M.children[0]:M,be=Math.ceil(m(L)*10)/10,Ue=!!be;if(Ue){var Ie=be/2,ke=e.linkResolution;if(!X.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||X.geometry.parameters.radiusTop!==Ie||X.geometry.parameters.radialSegments!==ke){if(!y.hasOwnProperty(be)){var kt=new J.CylinderGeometry(Ie,Ie,1,ke,1,!1);kt[pi](new J.Matrix4().makeTranslation(0,1/2,0)),kt[pi](new J.Matrix4().makeRotationX(Math.PI/2)),y[be]=kt}X.geometry.dispose(),X.geometry=y[be]}}var zn=p(L);if(zn)X.material=zn;else{var xn=g(L),os=new J.Color(ds(xn||"#f0f0f0")),yr=e.linkOpacity*ia(xn),Tn=Ue?"MeshLambertMaterial":"LineBasicMaterial";if(X.material.type!==Tn||!X.material.color.equals(os)||X.material.opacity!==yr){var as=Ue?_:T;as.hasOwnProperty(xn)||(as[xn]=new J[Tn]({color:os,transparent:yr<1,opacity:yr,depthWrite:yr>=1})),X.material.dispose(),X.material=as[xn]}}}}).digest(A),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var B=fe(e.linkDirectionalArrowLength),S=fe(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var M=new J.Mesh(void 0,new J.MeshLambertMaterial({transparent:!0}));return M.__linkThreeObjType="arrow",M}).onUpdateObj(function(M,L){var X=B(L),be=e.linkDirectionalArrowResolution;if(!M.geometry.type.match(/^Cone(Buffer)?Geometry$/)||M.geometry.parameters.height!==X||M.geometry.parameters.radialSegments!==be){var Ue=new J.ConeGeometry(X*.25,X,be);Ue.translate(0,X/2,0),Ue.rotateX(Math.PI/2),M.geometry.dispose(),M.geometry=Ue}var Ie=S(L)||g(L)||"#f0f0f0";M.material.color=new J.Color(ds(Ie)),M.material.opacity=e.linkOpacity*3*ia(Ie)}).digest(A.filter(B))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var v=fe(e.linkDirectionalParticles),E=fe(e.linkDirectionalParticleWidth),D=fe(e.linkDirectionalParticleColor),O=fe(e.linkDirectionalParticleThreeObject),Y={},ee={};e.particlesDataMapper.onCreateObj(function(){var M=new J.Group;return M.__linkThreeObjType="photons",M.__photonDataMapper=new cs(M),M}).onUpdateObj(function(M,L){var X=!!M.children.length&&M.children[0],be=O(L),Ue,Ie;if(be)Ue=be.geometry,Ie=be.material;else{var ke=Math.ceil(E(L)*10)/10/2,kt=e.linkDirectionalParticleResolution;X&&X.geometry.parameters.radius===ke&&X.geometry.parameters.widthSegments===kt?Ue=X.geometry:(ee.hasOwnProperty(ke)||(ee[ke]=new J.SphereGeometry(ke,kt,kt)),Ue=ee[ke]);var zn=D(L)||g(L)||"#f0f0f0",xn=new J.Color(ds(zn)),os=e.linkOpacity*3;X&&X.material.color.equals(xn)&&X.material.opacity===os?Ie=X.material:(Y.hasOwnProperty(zn)||(Y[zn]=new J.MeshLambertMaterial({color:xn,transparent:!0,opacity:os})),Ie=Y[zn])}X&&(X.geometry!==Ue&&X.geometry.dispose(),X.material!==Ie&&X.material.dispose());var yr=Math.round(Math.abs(v(L)));M.__photonDataMapper.id(function(Tn){return Tn.idx}).onCreateObj(function(){return new J.Mesh(Ue,Ie)}).onUpdateObj(function(Tn){Tn.geometry=Ue,Tn.material=Ie}).digest(Pt(new Array(yr)).map(function(Tn,as){return{idx:as}}))}).digest(A.filter(v))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(M){M.source=M[e.linkSource],M.target=M[e.linkTarget]});var te=e.forceEngine!=="ngraph",ne;if(te){(ne=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var ue=e.d3ForceLayout.force("link");ue&&ue.id(function(M){return M[e.nodeId]}).links(e.graphData.links);var le=e.dagMode&&Fb(e.graphData,function(M){return M[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),F=Math.max.apply(Math,Pt(Object.values(le||[]))),V=e.dagLevelDistance||e.graphData.nodes.length/(F||1)*Lb*(["radialin","radialout"].indexOf(e.dagMode)!==-1?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){var K=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(M){return delete M[K]})}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){var ye=["rl","td","zout"].includes(e.dagMode),k=function(L){return(le[L[e.nodeId]]-F/2)*V*(ye?-1:1)},q=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(M){return M[q]=k(M)})}e.d3ForceLayout.force("dagRadial",["radialin","radialout"].indexOf(e.dagMode)!==-1?Ry(function(M){var L=le[M[e.nodeId]]||-1;return(e.dagMode==="radialin"?F-L:L)*V}).strength(function(M){return e.dagNodeFilter(M)?1:0}):null)}else{var ie=Nc.graph();e.graphData.nodes.forEach(function(M){ie.addNode(M[e.nodeId])}),e.graphData.links.forEach(function(M){ie.addLink(M.source,M.target)}),ne=Nc.forcelayout(ie,Cb({dimensions:e.numDimensions},e.ngraphPhysics)),ne.graph=ie}for(var Be=0;Be<e.warmupTicks&&!(te&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);Be++)ne[te?"tick":"step"]();e.layout=ne,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});function Ob(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(r){function s(){var o;vf(this,s);for(var a=arguments.length,u=new Array(a),l=0;l<a;l++)u[l]=arguments[l];return o=Tf(this,s,[].concat(u)),o.__kapsuleInstance=Sf(i,[].concat(Pt(t?[o]:[]),u)),o}return Rf(s,r),Nf(s)})(e);return Object.keys(i()).forEach(function(r){return n.prototype[r]=function(){var s,o=(s=this.__kapsuleInstance)[r].apply(s,arguments);return o===this.__kapsuleInstance?this:o}}),n}var Ib=window.THREE?window.THREE:{Group:_h},Mf=Ob(Ub,Ib.Group,!0);/**
507
+ * @license
508
+ * Copyright 2010-2025 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"],aa=new WeakMap;class Gb{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,material:r,object:s}=e;if(t={material:this.getMaterialData(r),geometry:{id:n.id,attributes:this.getAttributesData(n.attributes),indexVersion:n.index?n.index.version:null,drawRange:{start:n.drawRange.start,count:n.drawRange.count}},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),t.material.transmission>0){const{width:o,height:a}=e.context;t.bufferWidth=o,t.bufferHeight=a}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const r=e[n];t[n]={version:r.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)}getMaterialData(e){const t={};for(const n of this.refreshUniforms){const r=e[n];r!=null&&(typeof r=="object"&&r.clone!==void 0?r.isTexture===!0?t[n]={id:r.id,version:r.version}:t[n]=r.clone():t[n]=r)}return t}equals(e,t){const{object:n,material:r,geometry:s}=e,o=this.getRenderObjectData(e);if(o.worldMatrix.equals(n.matrixWorld)!==!0)return o.worldMatrix.copy(n.matrixWorld),!1;const a=o.material;for(const m in a){const y=a[m],_=r[m];if(y.equals!==void 0){if(y.equals(_)===!1)return y.copy(_),!1}else if(_.isTexture===!0){if(y.id!==_.id||y.version!==_.version)return y.id=_.id,y.version=_.version,!1}else if(y!==_)return a[m]=_,!1}if(a.transmission>0){const{width:m,height:y}=e.context;if(o.bufferWidth!==m||o.bufferHeight!==y)return o.bufferWidth=m,o.bufferHeight=y,!1}const u=o.geometry,l=s.attributes,c=u.attributes,d=Object.keys(c),h=Object.keys(l);if(u.id!==s.id)return u.id=s.id,!1;if(d.length!==h.length)return o.geometry.attributes=this.getAttributesData(l),!1;for(const m of d){const y=c[m],_=l[m];if(_===void 0)return delete c[m],!1;if(y.version!==_.version)return y.version=_.version,!1}const p=s.index,f=u.indexVersion,g=p?p.version:null;if(f!==g)return u.indexVersion=g,!1;if(u.drawRange.start!==s.drawRange.start||u.drawRange.count!==s.drawRange.count)return u.drawRange.start=s.drawRange.start,u.drawRange.count=s.drawRange.count,!1;if(o.morphTargetInfluences){let m=!1;for(let y=0;y<o.morphTargetInfluences.length;y++)o.morphTargetInfluences[y]!==n.morphTargetInfluences[y]&&(o.morphTargetInfluences[y]=n.morphTargetInfluences[y],m=!0);if(m)return!1}if(o.lights){for(let m=0;m<t.length;m++)if(o.lights[m].map!==t[m].map)return!1}return o.center&&o.center.equals(n.center)===!1?(o.center.copy(n.center),!0):(e.bundle!==null&&(o.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(aa.has(e)){const r=aa.get(e);if(r.renderId===t)return r.lightsData}const n=this.getLightsData(e.getLights());return aa.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 r=e.object.static===!0,s=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;if(r||s)return!1;const o=this.getLights(e.lightsNode,n);return this.equals(e,o)!==!0}}function gl(i,e=0){let t=3735928559^e,n=1103547991^e;if(i instanceof Array)for(let r=0,s;r<i.length;r++)s=i[r],t=Math.imul(t^s,2654435761),n=Math.imul(n^s,1597334677);else for(let r=0,s;r<i.length;r++)s=i.charCodeAt(r),t=Math.imul(t^s,2654435761),n=Math.imul(n^s,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 Co=i=>gl(i),ei=i=>gl(i),Fs=(...i)=>gl(i),Vb=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Rc=new WeakMap;function Pf(i){return Vb.get(i)}function ho(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 ml(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 Ct(...e):t==="vec2"?new ce(...e):t==="vec3"?new I(...e):t==="vec4"?new Oe(...e):t==="mat2"?new af(...e):t==="mat3"?new Js(...e):t==="mat4"?new Et(...e):i==="bool"?e[0]||!1:i==="float"||i==="int"||i==="uint"?e[0]||0:i==="string"?e[0]||"":i==="ArrayBuffer"?zb(e[0]):null}function Bf(i){let e=Rc.get(i);return e===void 0&&(e={},Rc.set(i,e)),e}function $b(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 zb(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer}const gi={VERTEX:"vertex"},oe={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Nt={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},Wb=["fragment","vertex"],wc=["setup","analyze","generate"],Ac=[...Wb,"compute"],Zr=["x","y","z","w"],jb={analyze:"setup",generate:"analyze"};let qb=0;class H extends tl{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=oe.NONE,this.updateBeforeType=oe.NONE,this.updateAfterType=oe.NONE,this.uuid=ao.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:qb++})}set needsUpdate(e){e===!0&&this.version++}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,oe.FRAME)}onRenderUpdate(e){return this.onUpdate(e,oe.RENDER)}onObjectUpdate(e){return this.onUpdate(e,oe.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 r=this[n];if(!(n.startsWith("_")===!0||e.has(r))){if(Array.isArray(r)===!0)for(let s=0;s<r.length;s++){const o=r[s];o&&o.isNode===!0&&t.push({property:n,index:s,childNode:o})}else if(r&&r.isNode===!0)t.push({property:n,childNode:r});else if(r&&Object.getPrototypeOf(r)===Object.prototype)for(const s in r){if(s.startsWith("_")===!0)continue;const o=r[s];o&&o.isNode===!0&&t.push({property:n,index:s,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:r,childNode:s}of this._getChildren(t))n.push(Co(r.slice(0,-4)),s.getCacheKey(e,t));this._cacheKey=Fs(ei(n),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return this.uuid}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){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):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 r of this.getChildren())t["node"+n++]=r;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(this.parents===!0){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(n===1){const r=e.getNodeProperties(this);for(const s of Object.values(r))s&&s.isNode===!0&&s.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 r=e.getDataFromNode(this);r.buildStages=r.buildStages||{},r.buildStages[e.buildStage]=!0;const s=jb[e.buildStage];if(s&&r.buildStages[s]!==!0){const u=e.getBuildStage();e.setBuildStage(s),this.build(e),e.setBuildStage(u)}e.addNode(this),e.addChain(this);let o=null;const a=e.getBuildStage();if(a==="setup"){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)}}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"&&(G(`TSL: Invalid generated code, expected a "${t}".`),o=e.generateConst(t))}return e.removeChain(this),e.addSequentialNode(this),o}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:r,index:s,childNode:o}of t)s!==void 0?(n[r]===void 0&&(n[r]=Number.isInteger(s)?[]:{}),n[r][s]=o.toJSON(e.meta).uuid):n[r]=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 r=[];for(const s of e.inputNodes[n])r.push(t[s]);this[n]=r}else if(typeof e.inputNodes[n]=="object"){const r={};for(const s in e.inputNodes[n]){const o=e.inputNodes[n][s];r[s]=t[o]}this[n]=r}else{const r=e.inputNodes[n];this[n]=t[r]}}}toJSON(e){const{uuid:t,type:n}=this,r=e===void 0||typeof e=="string";r&&(e={textures:{},images:{},nodes:{}});let s=e.nodes[t];s===void 0&&(s={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},r!==!0&&(e.nodes[s.uuid]=s),this.serialize(s),delete s.meta);function o(a){const u=[];for(const l in a){const c=a[l];delete c.metadata,u.push(c)}return u}if(r){const a=o(e.textures),u=o(e.images),l=o(e.nodes);a.length>0&&(s.textures=a),u.length>0&&(s.images=u),l.length>0&&(s.nodes=l)}return s}}class Jr extends H{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(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),r=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${n}[ ${r} ]`}}class Df extends H{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const r of this.convertTo.split("|"))(n===null||e.getTypeLength(t)===e.getTypeLength(r))&&(n=r);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,r=this.getNodeType(e),s=n.build(e,r);return e.format(s,r,t)}}class qe extends H{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 r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(s.propertyName!==void 0)return e.format(s.propertyName,r,t);if(r!=="void"&&t!=="void"&&this.hasDependencies(e)){const o=super.build(e,r),a=e.getVarFromNode(this,null,r),u=e.getPropertyName(a);return e.addLineFlowCode(`${u} = ${o}`,this),s.snippet=o,s.propertyName=u,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class Hb extends qe{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(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),r=e.getTypeLength(n),s=this.nodes,o=e.getComponentType(n),a=[];let u=0;for(const c of s){if(u>=r){G(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`);break}let d=c.getNodeType(e),h=e.getTypeLength(d),p;if(u+h>r&&(G(`TSL: Length of '${n}()' data exceeds maximum length of output type.`),h=r-u,d=e.getTypeFromLength(h)),u+=h,p=c.build(e,d),e.getComponentType(d)!==o){const g=e.getTypeFromLength(h,o);p=e.format(p,d,g)}a.push(p)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const Xb=Zr.join("");class Kb extends H{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(Zr.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const n=this.node,r=e.getTypeLength(n.getNodeType(e));let s=null;if(r>1){let o=null;this.getVectorLength()>=r&&(o=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const u=n.build(e,o);this.components.length===r&&this.components===Xb.slice(0,this.components.length)?s=e.format(u,o,t):s=e.format(`${u}.${this.components}`,this.getNodeType(e),t)}else s=n.build(e,t);return s}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Yb extends qe{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:r}=this,s=this.getNodeType(e),o=e.getComponentType(r.getNodeType(e)),a=e.getTypeFromLength(n.length,o),u=r.build(e,a),l=t.build(e,s),c=e.getTypeLength(s),d=[];for(let h=0;h<c;h++){const p=Zr[h];p===n[0]?(d.push(u),h+=n.length-1):d.push(l+"."+p)}return`${e.getType(s)}( ${d.join(", ")} )`}}class Qb extends qe{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,r=this.getNodeType(e),s=n.build(e),o=e.getVarFromNode(this),a=e.getPropertyName(o);e.addLineFlowCode(a+" = "+s,this);const u=e.getTypeLength(r),l=[];let c=0;for(let d=0;d<u;d++){const h=Zr[d];h===t[c]?(l.push("1.0 - "+(a+"."+h)),c++):l.push(a+"."+h)}return`${e.getType(r)}( ${l.join(", ")} )`}}class yl extends H{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return this.nodeType===null?ho(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=ho(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=$b(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?ml(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 Ec=/float|u?int/;class tn extends yl{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 Ec.test(n)&&Ec.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class Zb extends H{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"}getNodeType(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.`);const n=this.getNodeType(e);return e.generateConst(n)}return this.structNode.build(e)+"."+this.property}}let cr=null;const Cu=new Map;function w(i,e){if(Cu.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`);Cu.set(i,e),i!=="assign"&&(H.prototype[i]=function(...t){return this.isStackNode?this.addToStack(e(...t)):e(this,...t)},H.prototype[i+"Assign"]=function(...t){return this.isStackNode?this.assign(t[0],e(...t)):this.assign(e(this,...t))})}const Jb=i=>i.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Cc=i=>Jb(i).split("").sort().join("");H.prototype.assign=function(...i){if(this.isStackNode!==!0)return cr!==null?cr.assign(this,...i):G("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn()."),this;{const e=Cu.get("assign");return this.addToStack(e(...i))}};H.prototype.toVarIntent=function(){return this};H.prototype.get=function(i){return new Zb(this,i)};const Ls={};function mi(i,e,t){Ls[i]=Ls[e]=Ls[t]={get(){this._cache=this._cache||{};let o=this._cache[i];return o===void 0&&(o=new Kb(this,i),this._cache[i]=o),o},set(o){this[i].assign($(o))}};const n=i.toUpperCase(),r=e.toUpperCase(),s=t.toUpperCase();H.prototype["set"+n]=H.prototype["set"+r]=H.prototype["set"+s]=function(o){const a=Cc(i);return new Yb(this,a,$(o))},H.prototype["flip"+n]=H.prototype["flip"+r]=H.prototype["flip"+s]=function(){const o=Cc(i);return new Qb(this,o)}}const Gt=["x","y","z","w"],Vt=["r","g","b","a"],$t=["s","t","p","q"];for(let i=0;i<4;i++){let e=Gt[i],t=Vt[i],n=$t[i];mi(e,t,n);for(let r=0;r<4;r++){e=Gt[i]+Gt[r],t=Vt[i]+Vt[r],n=$t[i]+$t[r],mi(e,t,n);for(let s=0;s<4;s++){e=Gt[i]+Gt[r]+Gt[s],t=Vt[i]+Vt[r]+Vt[s],n=$t[i]+$t[r]+$t[s],mi(e,t,n);for(let o=0;o<4;o++)e=Gt[i]+Gt[r]+Gt[s]+Gt[o],t=Vt[i]+Vt[r]+Vt[s]+Vt[o],n=$t[i]+$t[r]+$t[s]+$t[o],mi(e,t,n)}}}for(let i=0;i<32;i++)Ls[i]={get(){this._cache=this._cache||{};let e=this._cache[i];return e===void 0&&(e=new Jr(this,new tn(i,"uint")),this._cache[i]=e),e},set(e){this[i].assign($(e))}};Object.defineProperties(H.prototype,Ls);const Mc=new WeakMap,e_=function(i,e=null){const t=ho(i);return t==="node"?i:e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string"?$(Mu(i,e)):t==="shader"?i.isFn?i:P(i):i},t_=function(i,e=null){for(const t in i)i[t]=$(i[t],e);return i},n_=function(i,e=null){const t=i.length;for(let n=0;n<t;n++)i[n]=$(i[n],e);return i},Ff=function(i,e=null,t=null,n=null){function r(c){return n!==null?(c=$(Object.assign(c,n)),n.intent===!0&&(c=c.toVarIntent())):c=$(c),c}let s,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?(G(`TSL: "${d}" parameter length is less than minimum required.`),c.concat(new Array(a-c.length).fill(0))):u!==void 0&&c.length>u?(G(`TSL: "${d}" parameter length exceeds limit.`),c.slice(0,u)):c}return e===null?s=(...c)=>r(new i(...Ur(l(c)))):t!==null?(t=$(t),s=(...c)=>r(new i(e,...Ur(l(c)),t))):s=(...c)=>r(new i(e,...Ur(l(c)))),s.setParameterLength=(...c)=>(c.length===1?a=u=c[0]:c.length===2&&([a,u]=c),s),s.setName=c=>(o=c,s),s},r_=function(i,...e){return new i(...Ur(e))};class s_ extends H{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(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,r=e.getNodeProperties(t),s=e.getClosestSubBuild(t.subBuilds)||"",o=s||"default";if(r[o])return r[o];const a=e.subBuildFn,u=e.fnCall;e.subBuildFn=s,e.fnCall=this;let l=null;if(t.layout){let c=Mc.get(e.constructor);c===void 0&&(c=new WeakMap,Mc.set(e.constructor,c));let d=c.get(t);d===void 0&&(d=$(e.buildFunctionNode(t)),c.set(t,d)),e.addInclude(d);const h=n?i_(n):null;l=$(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?o_(n):null,h=Array.isArray(n)?n.length>0:n!==null,p=t.jsFunc,f=h||p.length>1?p(d,c):p(c);l=$(f)}return e.subBuildFn=a,e.fnCall=u,t.once&&(r[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 r=e.getBuildStage(),s=e.getNodeProperties(this),o=e.getSubBuildOutput(this),a=this.getOutputNode(e),u=e.fnCall;if(e.fnCall=this,r==="setup"){const l=e.getSubBuildProperty("initialized",this);if(s[l]!==!0&&(s[l]=!0,s[o]=this.getOutputNode(e),s[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=s[o]}else r==="analyze"?a.build(e,t):r==="generate"&&(n=a.build(e,t)||"");return e.fnCall=u,n}}function i_(i){let e;return Tl(i),i[0]&&(i[0].isNode||Object.getPrototypeOf(i[0])!==Object.prototype)?e=[...i]:e=i[0],e}function o_(i){let e=0;return Tl(i),new Proxy(i,{get:(t,n,r)=>{let s;if(n==="length")return s=i.length,s;if(Symbol.iterator===n)s=function*(){for(const o of i)yield $(o)};else{if(i.length>0)if(Object.getPrototypeOf(i[0])===Object.prototype){const o=i[0];o[n]===void 0?s=o[e++]:s=Reflect.get(o,n,r)}else i[0]instanceof H&&(i[n]===void 0?s=i[e++]:s=Reflect.get(i,n,r));else s=Reflect.get(t,n,r);s=$(s)}return s}})}class a_ extends H{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 s_(this,e)}setup(){return this.call()}}const u_=[!1,!0],l_=[0,1,2,3],c_=[-1,-2],Lf=[.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],bl=new Map;for(const i of u_)bl.set(i,new tn(i));const _l=new Map;for(const i of l_)_l.set(i,new tn(i,"uint"));const xl=new Map([..._l].map(i=>new tn(i.value,"int")));for(const i of c_)xl.set(i,new tn(i,"int"));const Mo=new Map([...xl].map(i=>new tn(i.value)));for(const i of Lf)Mo.set(i,new tn(i));for(const i of Lf)Mo.set(-i,new tn(-i));const Po={bool:bl,uint:_l,ints:xl,float:Mo},Pc=new Map([...bl,...Mo]),Mu=(i,e)=>Pc.has(i)?Pc.get(i):i.isNode===!0?i:new tn(i,e),He=function(i,e=null){return(...t)=>{for(const r of t)if(r===void 0)return G(`TSL: Invalid parameter for the type "${i}".`),new tn(0,i);if((t.length===0||!["bool","float","int","uint"].includes(i)&&t.every(r=>{const s=typeof r;return s!=="object"&&s!=="function"}))&&(t=[ml(i,...t)]),t.length===1&&e!==null&&e.has(t[0]))return yi(e.get(t[0]));if(t.length===1){const r=Mu(t[0],i);return r.nodeType===i?yi(r):yi(new Df(r,i))}const n=t.map(r=>Mu(r));return yi(new Hb(n,i))}},Bc=i=>typeof i=="object"&&i!==null?i.value:i,d_=i=>i!=null?i.nodeType||i.convertTo||(typeof i=="string"?i:null):null;function ws(i,e){return new a_(i,e)}const $=(i,e=null)=>e_(i,e),yi=(i,e=null)=>$(i,e).toVarIntent(),Tl=(i,e=null)=>new t_(i,e),Ur=(i,e=null)=>new n_(i,e),me=(i,e=null,t=null,n=null)=>new Ff(i,e,t,n),U=(i,...e)=>new r_(i,...e),W=(i,e=null,t=null,n={})=>new Ff(i,e,t,{...n,intent:!0});let h_=0;class f_ extends H{constructor(e,t=null){super();let n=null;t!==null&&(typeof t=="object"?n=t.return:(typeof t=="string"?n=t:G("TSL: Invalid layout type."),t=null)),this.shaderNode=new ws(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"+h_++,type:t,inputs:[]};for(const r in e)r!=="return"&&n.inputs.push({name:r,type:e[r]});e=n}return this.shaderNode.setLayout(e),this}getNodeType(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 G('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".'),e.generateConst(t)}}function P(i,e=null){const t=new f_(i,e);return new Proxy(()=>{},{apply(n,r,s){return t.call(...s)},get(n,r,s){return Reflect.get(t,r,s)},set(n,r,s,o){return Reflect.set(t,r,s,o)}})}const fo=i=>{cr=i},Uf=()=>cr,Re=(...i)=>cr.If(...i);function Of(i){return cr&&cr.addToStack(i),i}w("toStack",Of);const p_=new He("color"),N=new He("float",Po.float),Me=new He("int",Po.ints),de=new He("uint",Po.uint),vl=new He("bool",Po.bool),j=new He("vec2"),qt=new He("ivec2"),If=new He("uvec2"),g_=new He("bvec2"),R=new He("vec3"),kf=new He("ivec3"),Gf=new He("uvec3"),m_=new He("bvec3"),se=new He("vec4"),Vf=new He("ivec4"),$f=new He("uvec4"),y_=new He("bvec4"),Sl=new He("mat2"),nt=new He("mat3"),or=new He("mat4");w("toColor",p_);w("toFloat",N);w("toInt",Me);w("toUint",de);w("toBool",vl);w("toVec2",j);w("toIVec2",qt);w("toUVec2",If);w("toBVec2",g_);w("toVec3",R);w("toIVec3",kf);w("toUVec3",Gf);w("toBVec3",m_);w("toVec4",se);w("toIVec4",Vf);w("toUVec4",$f);w("toBVec4",y_);w("toMat2",Sl);w("toMat3",nt);w("toMat4",or);const b_=me(Jr).setParameterLength(2),__=(i,e)=>$(new Df($(i),e));w("element",b_);w("convert",__);w("append",i=>(z("TSL: .append() has been renamed to .toStack()."),Of(i)));class _e extends H{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 Co(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 Un=(i,e)=>new _e(i,e),po=(i,e)=>new _e(i,e,!0),ve=U(_e,"vec4","DiffuseColor"),Cr=U(_e,"vec3","DiffuseContribution"),Dc=U(_e,"vec3","EmissiveColor"),cn=U(_e,"float","Roughness"),Mn=U(_e,"float","Metalness"),Pu=U(_e,"float","Clearcoat"),go=U(_e,"float","ClearcoatRoughness"),xt=U(_e,"vec3","Sheen"),Yn=U(_e,"float","SheenRoughness"),Nl=U(_e,"float","Iridescence"),Bu=U(_e,"float","IridescenceIOR"),Du=U(_e,"float","IridescenceThickness"),Fu=U(_e,"float","AlphaT"),Xn=U(_e,"float","Anisotropy"),Hi=U(_e,"vec3","AnisotropyT"),Or=U(_e,"vec3","AnisotropyB"),dr=U(_e,"color","SpecularColor"),Br=U(_e,"color","SpecularColorBlended"),Us=U(_e,"float","SpecularF90"),Lu=U(_e,"float","Shininess"),Os=U(_e,"vec4","Output"),ua=U(_e,"float","dashSize"),Fc=U(_e,"float","gapSize"),Xi=U(_e,"float","IOR"),Uu=U(_e,"float","Transmission"),zf=U(_e,"float","Thickness"),Wf=U(_e,"float","AttenuationDistance"),jf=U(_e,"color","AttenuationColor"),qf=U(_e,"float","Dispersion");class Hf extends H{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1){super("string"),this.name=e,this.shared=t,this.order=n,this.isUniformGroup=!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 x_=i=>new Hf(i),Rl=(i,e=0)=>new Hf(i,!0,e),T_=Rl("frame"),Q=Rl("render"),Xf=x_("object");class ti extends yl{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Xf}setName(e){return this.name=e,this}label(e){return z('TSL: "label()" has been deprecated. Use "setName()" instead.'),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 r=e(n,this);r!==void 0&&(this.value=r)},t)}getInputType(e){let t=super.getInputType(e);return t==="bool"&&(t="uint"),t}generate(e,t){const n=this.getNodeType(e),r=this.getUniformHash(e);let s=e.getNodeFromHash(r);s===void 0&&(e.setHashNode(this,r),s=this);const o=s.getInputType(e),a=e.getUniformFromNode(s,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 Z=(i,e)=>{const t=d_(e||i);if(t===i&&(i=ml(t)),i&&i.isNode===!0){let n=i.value;i.traverse(r=>{r.isConstNode===!0&&(n=r.value)}),i=n}return new ti(i,t)};class Lc extends qe{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}getNodeType(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 v_=(...i)=>{let e;if(i.length===1){const t=i[0];e=new Lc(null,t.length,t)}else{const t=i[0],n=i[1];e=new Lc(t,n)}return $(e)};w("toArray",(i,e)=>v_(Array(e).fill(i)));class S_ extends qe{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(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 Zr.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,r=t.getScope(),s=e.getDataFromNode(r);s.assign=!0;const o=e.getNodeProperties(this);o.sourceNode=n,o.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:r}=e.getNodeProperties(this),s=this.needsSplitAssign(e),o=n.build(e),a=n.getNodeType(e),u=r.build(e,a),l=r.getNodeType(e),c=e.getDataFromNode(this);let d;if(c.initialized===!0)t!=="void"&&(d=o);else if(s){const h=e.getVarFromNode(this,null,a),p=e.getPropertyName(h);e.addLineFlowCode(`${p} = ${u}`,this);const f=n.node,m=f.node.context({assign:!0}).build(e);for(let y=0;y<f.components.length;y++){const _=f.components[y];e.addLineFlowCode(`${m}.${_} = ${p}[ ${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 N_=me(S_).setParameterLength(2);w("assign",N_);class R_ extends qe{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}getNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],n=this.functionNode,r=n.getInputs(e),s=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(s)){if(s.length>r.length)G("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),s.length=r.length;else if(s.length<r.length)for(G("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");s.length<r.length;)s.push(N(0));for(let u=0;u<s.length;u++)t.push(o(s[u],r[u]))}else for(const u of r){const l=s[u.name];l!==void 0?t.push(o(l,u)):(G(`TSL: Input '${u.name}' not found in 'Fn()'.`),t.push(o(N(0),u)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}const w_=(i,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?Ur(e):Tl(e[0]),new R_($(i),e));w("call",w_);const A_={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Le extends qe{static get type(){return"OperatorNode"}constructor(e,t,n,...r){if(super(),r.length>0){let s=new Le(e,t,n);for(let o=0;o<r.length-1;o++)s=new Le(e,s,r[o]);t=s,n=r[r.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(A_[this.op],t)}getNodeType(e,t=null){const n=this.op,r=this.aNode,s=this.bNode,o=r.getNodeType(e),a=s?s.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:r,bNode:s}=this,o=this.getNodeType(e,t);let a=null,u=null;o!=="void"?(a=r.getNodeType(e),u=s?s.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=r.build(e,a),c=s?s.build(e,u):null,d=e.getFunctionOperator(n);if(t!=="void"){const h=e.renderer.coordinateSystem===Ji;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 p=`( ${l} ${n} ${c} )`;return!h&&o==="bool"&&e.isVector(a)&&e.isVector(u)&&(p=`all${p}`),e.format(p,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=W(Le,"+").setParameterLength(2,1/0).setName("add"),at=W(Le,"-").setParameterLength(2,1/0).setName("sub"),ae=W(Le,"*").setParameterLength(2,1/0).setName("mul"),Zt=W(Le,"/").setParameterLength(2,1/0).setName("div"),wl=W(Le,"%").setParameterLength(2).setName("mod"),Kf=W(Le,"==").setParameterLength(2).setName("equal"),E_=W(Le,"!=").setParameterLength(2).setName("notEqual"),C_=W(Le,"<").setParameterLength(2).setName("lessThan"),M_=W(Le,">").setParameterLength(2).setName("greaterThan"),P_=W(Le,"<=").setParameterLength(2).setName("lessThanEqual"),B_=W(Le,">=").setParameterLength(2).setName("greaterThanEqual"),D_=W(Le,"&&").setParameterLength(2,1/0).setName("and"),F_=W(Le,"||").setParameterLength(2,1/0).setName("or"),L_=W(Le,"!").setParameterLength(1).setName("not"),U_=W(Le,"^^").setParameterLength(2).setName("xor"),O_=W(Le,"&").setParameterLength(2).setName("bitAnd"),I_=W(Le,"~").setParameterLength(1).setName("bitNot"),k_=W(Le,"|").setParameterLength(2).setName("bitOr"),G_=W(Le,"^").setParameterLength(2).setName("bitXor"),V_=W(Le,"<<").setParameterLength(2).setName("shiftLeft"),$_=W(Le,">>").setParameterLength(2).setName("shiftRight"),z_=P(([i])=>(i.addAssign(1),i)),W_=P(([i])=>(i.subAssign(1),i)),j_=P(([i])=>{const e=Me(i).toConst();return i.addAssign(1),e}),q_=P(([i])=>{const e=Me(i).toConst();return i.subAssign(1),e});w("add",pt);w("sub",at);w("mul",ae);w("div",Zt);w("mod",wl);w("equal",Kf);w("notEqual",E_);w("lessThan",C_);w("greaterThan",M_);w("lessThanEqual",P_);w("greaterThanEqual",B_);w("and",D_);w("or",F_);w("not",L_);w("xor",U_);w("bitAnd",O_);w("bitNot",I_);w("bitOr",k_);w("bitXor",G_);w("shiftLeft",V_);w("shiftRight",$_);w("incrementBefore",z_);w("decrementBefore",W_);w("increment",j_);w("decrement",q_);const H_=(i,e)=>(z('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),wl(Me(i),Me(e)));w("modInt",H_);class x extends qe{static get type(){return"MathNode"}constructor(e,t,n=null,r=null){if(super(),(e===x.MAX||e===x.MIN)&&arguments.length>3){let s=new x(e,t,n);for(let o=2;o<arguments.length-1;o++)s=new x(e,s,arguments[o]);t=s,n=arguments[arguments.length-1],r=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=r,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,r=this.cNode?this.cNode.getNodeType(e):null,s=e.isMatrix(t)?0:e.getTypeLength(t),o=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(r)?0:e.getTypeLength(r);return s>o&&s>a?t:o>a?n:a>s?r:t}getNodeType(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:r}=this;let s=null;if(r===x.ONE_MINUS)s=at(1,t);else if(r===x.RECIPROCAL)s=Zt(1,t);else if(r===x.DIFFERENCE)s=yt(at(t,n));else if(r===x.TRANSFORM_DIRECTION){let o=t,a=n;e.isMatrix(o.getNodeType(e))?a=se(R(a),0):o=se(R(o),0);const u=ae(o,a).xyz;s=Lt(u)}return s!==null?s:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),o=this.getInputType(e),a=this.aNode,u=this.bNode,l=this.cNode,c=e.renderer.coordinateSystem;if(r===x.NEGATE)return e.format("( - "+a.build(e,o)+" )",s,t);{const d=[];return r===x.CROSS?d.push(a.build(e,s),u.build(e,s)):c===Ji&&r===x.STEP?d.push(a.build(e,e.getTypeLength(a.getNodeType(e))===1?"float":o),u.build(e,o)):c===Ji&&(r===x.MIN||r===x.MAX)?d.push(a.build(e,o),u.build(e,e.getTypeLength(u.getNodeType(e))===1?"float":o)):r===x.REFRACT?d.push(a.build(e,o),u.build(e,o),l.build(e,"float")):r===x.MIX?d.push(a.build(e,o),u.build(e,o),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":o)):(c===Gr&&r===x.ATAN&&u!==null&&(r="atan2"),e.shaderStage!=="fragment"&&(r===x.DFDX||r===x.DFDY)&&(z(`TSL: '${r}' is not supported in the ${e.shaderStage} stage.`),r="/*"+r+"*/"),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(r,s)}( ${d.join(", ")} )`,s,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.COS="cos";x.TAN="tan";x.ASIN="asin";x.ACOS="acos";x.ATAN="atan";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 Yf=N(1e-6),X_=N(Math.PI),K_=W(x,x.ALL).setParameterLength(1),Y_=W(x,x.ANY).setParameterLength(1),Q_=W(x,x.RADIANS).setParameterLength(1),Z_=W(x,x.DEGREES).setParameterLength(1),Qf=W(x,x.EXP).setParameterLength(1),Xs=W(x,x.EXP2).setParameterLength(1),Zf=W(x,x.LOG).setParameterLength(1),gn=W(x,x.LOG2).setParameterLength(1),fn=W(x,x.SQRT).setParameterLength(1),J_=W(x,x.INVERSE_SQRT).setParameterLength(1),ar=W(x,x.FLOOR).setParameterLength(1),Al=W(x,x.CEIL).setParameterLength(1),Lt=W(x,x.NORMALIZE).setParameterLength(1),Jt=W(x,x.FRACT).setParameterLength(1),mt=W(x,x.SIN).setParameterLength(1),Ht=W(x,x.COS).setParameterLength(1),ex=W(x,x.TAN).setParameterLength(1),tx=W(x,x.ASIN).setParameterLength(1),Jf=W(x,x.ACOS).setParameterLength(1),ep=W(x,x.ATAN).setParameterLength(1,2),yt=W(x,x.ABS).setParameterLength(1),tp=W(x,x.SIGN).setParameterLength(1),mn=W(x,x.LENGTH).setParameterLength(1),np=W(x,x.NEGATE).setParameterLength(1),nx=W(x,x.ONE_MINUS).setParameterLength(1),rp=W(x,x.DFDX).setParameterLength(1),sp=W(x,x.DFDY).setParameterLength(1),rx=W(x,x.ROUND).setParameterLength(1),sx=W(x,x.RECIPROCAL).setParameterLength(1),ix=W(x,x.TRUNC).setParameterLength(1),ip=W(x,x.FWIDTH).setParameterLength(1),ox=W(x,x.TRANSPOSE).setParameterLength(1),ax=W(x,x.DETERMINANT).setParameterLength(1),ux=W(x,x.INVERSE).setParameterLength(1),lx=(i,e)=>(z('TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),Kf(i,e)),Wr=W(x,x.MIN).setParameterLength(2,1/0),Je=W(x,x.MAX).setParameterLength(2,1/0),op=W(x,x.STEP).setParameterLength(2),cx=W(x,x.REFLECT).setParameterLength(2),dx=W(x,x.DISTANCE).setParameterLength(2),hx=W(x,x.DIFFERENCE).setParameterLength(2),hr=W(x,x.DOT).setParameterLength(2),fr=W(x,x.CROSS).setParameterLength(2),Bo=W(x,x.POW).setParameterLength(2),ap=i=>ae(i,i),fx=i=>ae(i,i,i),up=i=>ae(i,i,i,i),px=W(x,x.TRANSFORM_DIRECTION).setParameterLength(2),gx=i=>ae(tp(i),Bo(yt(i),1/3)),lp=i=>hr(i,i),Ne=W(x,x.MIX).setParameterLength(3),On=(i,e=0,t=1)=>$(new x(x.CLAMP,$(i),$(e),$(t))),El=i=>On(i),cp=W(x,x.REFRACT).setParameterLength(3),yn=W(x,x.SMOOTHSTEP).setParameterLength(3),mx=W(x,x.FACEFORWARD).setParameterLength(3),yx=P(([i])=>{const n=43758.5453,r=hr(i.xy,j(12.9898,78.233)),s=wl(r,X_);return Jt(mt(s).mul(n))}),bx=(i,e,t)=>Ne(e,t,i),_x=(i,e,t)=>yn(e,t,i),xx=(i,e)=>op(e,i),Tx=(i,e)=>(z('TSL: "atan2" is overloaded. Use "atan" instead.'),ep(i,e));w("all",K_);w("any",Y_);w("equals",lx);w("radians",Q_);w("degrees",Z_);w("exp",Qf);w("exp2",Xs);w("log",Zf);w("log2",gn);w("sqrt",fn);w("inverseSqrt",J_);w("floor",ar);w("ceil",Al);w("normalize",Lt);w("fract",Jt);w("sin",mt);w("cos",Ht);w("tan",ex);w("asin",tx);w("acos",Jf);w("atan",ep);w("abs",yt);w("sign",tp);w("length",mn);w("lengthSq",lp);w("negate",np);w("oneMinus",nx);w("dFdx",rp);w("dFdy",sp);w("round",rx);w("reciprocal",sx);w("trunc",ix);w("fwidth",ip);w("atan2",Tx);w("min",Wr);w("max",Je);w("step",xx);w("reflect",cx);w("distance",dx);w("dot",hr);w("cross",fr);w("pow",Bo);w("pow2",ap);w("pow3",fx);w("pow4",up);w("transformDirection",px);w("mix",bx);w("clamp",On);w("refract",cp);w("smoothstep",_x);w("faceForward",mx);w("difference",hx);w("saturate",El);w("cbrt",gx);w("transpose",ox);w("determinant",ax);w("inverse",ux);w("rand",yx);class vx extends H{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const r=t.getNodeType(e);if(n!==null){const s=n.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(r))return s}return r}setup(e){const t=this.condNode,n=this.ifNode.isolate(),r=this.elseNode?this.elseNode.isolate():null,s=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=s,r!==null&&(e.getDataFromNode(r).parentNodeBlock=s);const o=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=o?n:n.context({nodeBlock:n}),a.elseNode=r?o?r:r.context({nodeBlock:r}):null}generate(e,t){const n=this.getNodeType(e),r=e.getDataFromNode(this);if(r.nodeProperty!==void 0)return r.nodeProperty;const{condNode:s,ifNode:o,elseNode:a}=e.getNodeProperties(this),u=e.currentFunctionNode,l=t!=="void",c=l?Un(n).build(e):"";r.nodeProperty=c;const d=s.build(e,"bool");if(e.context.uniformFlow&&a!==null){const f=o.build(e,n),g=a.build(e,n),m=e.getTernary(d,f,g);return e.format(m,n,t)}e.addFlowCode(`
511
+ ${e.tab}if ( ${d} ) {
512
+
513
+ `).addFlowTab();let p=o.build(e,n);if(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."),p="// "+p))),e.removeFlowTab().addFlowCode(e.tab+" "+p+`
514
+
515
+ `+e.tab+"}"),a!==null){e.addFlowCode(` else {
516
+
517
+ `).addFlowTab();let f=a.build(e,n);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."),f="// "+f))),e.removeFlowTab().addFlowCode(e.tab+" "+f+`
518
+
519
+ `+e.tab+`}
520
+
521
+ `)}else e.addFlowCode(`
522
+
523
+ `);return e.format(c,n,t)}}const lt=me(vx).setParameterLength(2,3);w("select",lt);class dp extends H{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(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),r=this.node.build(e,t);return e.setContext(n),r}}const gr=(i=null,e={})=>{let t=i;return(t===null||t.isNode!==!0)&&(e=t||e,t=null),new dp(t,e)},Sx=i=>gr(i,{uniformFlow:!0}),hp=(i,e)=>gr(i,{nodeName:e});function Nx(i,e,t=null){return gr(t,{getShadow:({light:n,shadowColorNode:r})=>e===n?r.mul(i):r})}function Rx(i,e=null){return gr(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.'),hp(i,e)}w("context",gr);w("label",wx);w("uniformFlow",Sx);w("setName",hp);w("builtinShadowContext",(i,e,t)=>Nx(e,t,i));w("builtinAOContext",(i,e)=>Rx(e,i));class Ki extends H{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)}getNodeType(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 r=t.getBaseStack();n?r.addToStackBefore(this):r.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:r}=this,{renderer:s}=e,o=s.backend.isWebGPUBackend===!0;let a=!1,u=!1;r&&(a=e.isDeterministic(t),u=o?r:a);const l=this.getNodeType(e);if(l=="void")return this.isIntent(e)!==!0&&G('TSL: ".toVar()" can not be used with void type.'),t.build(e);const c=e.getVectorType(l),d=t.build(e,c),h=e.getVarFromNode(this,n,c,void 0,u),p=e.getPropertyName(h);let f=p;if(u)if(o)f=a?`const ${p}`:`let ${p}`;else{const g=t.getArrayCount(e);f=`const ${e.getVar(h.type,p,g)}`}return e.addLineFlowCode(`${f} = ${d}`,this),p}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}}const Cl=me(Ki),Ax=(i,e=null)=>Cl(i,e).toStack(),Ex=(i,e=null)=>Cl(i,e,!0).toStack(),Cx=i=>Cl(i).setIntent(!0).toStack();w("toVar",Ax);w("toConst",Ex);w("toVarIntent",Cx);class Mx extends H{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(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 Is=(i,e,t=null)=>$(new Mx($(i),e,t));class Px extends H{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,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)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(n===void 0){const r=this.name,s=this.getNodeType(e),o=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,r,s,o,a),t.node=Is(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation=e.shaderStage==="fragment"),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(gi.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(gi.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),r=this.setupVarying(e);if(n[t]===void 0){const s=this.getNodeType(e),o=e.getPropertyName(r,gi.VERTEX);e.flowNodeFromShaderStage(gi.VERTEX,n.node,s,o),n[t]=o}return e.getPropertyName(r)}}const bn=me(Px).setParameterLength(1,2),Bx=i=>bn(i);w("toVarying",bn);w("toVertexStage",Bx);w("varying",(...i)=>(z("TSL: .varying() has been renamed to .toVarying()."),bn(...i)));w("vertexStage",(...i)=>(z("TSL: .vertexStage() has been renamed to .toVertexStage()."),bn(...i)));const Dx=P(([i])=>{const e=i.mul(.9478672986).add(.0521327014).pow(2.4),t=i.mul(.0773993808),n=i.lessThanEqual(.04045);return Ne(e,t,n)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Fx=P(([i])=>{const e=i.pow(.41666).mul(1.055).sub(.055),t=i.mul(12.92),n=i.lessThanEqual(.0031308);return Ne(e,t,n)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Ml="WorkingColorSpace",Lx="OutputColorSpace";class fp extends qe{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===Ml?Ve.workingColorSpace:t===Lx?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),r=this.resolveColorSpace(e,this.target);let s=t;return Ve.enabled===!1||n===r||!n||!r||(Ve.getTransfer(n)===re&&(s=se(Dx(s.rgb),s.a)),Ve.getPrimaries(n)!==Ve.getPrimaries(r)&&(s=se(nt(Ve._getMatrix(new Js,n,r)).mul(s.rgb),s.a)),Ve.getTransfer(r)===re&&(s=se(Fx(s.rgb),s.a))),s}}const Ux=(i,e)=>$(new fp($(i),Ml,e)),Pl=(i,e)=>$(new fp($(i),e,Ml));w("workingToColorSpace",Ux);w("colorSpaceToWorking",Pl);let Ox=class extends Jr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),r=this.getNodeType();return e.format(t,n,r)}};class pp extends H{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=oe.OBJECT}setGroup(e){return this.group=e,this}element(e){return new Ox(this,$(e))}setNodeType(e){const t=Z(null,e);this.group!==null&&t.setGroup(this.group),this.node=t}getNodeType(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 r=1;r<t.length;r++)n=n[t[r]];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 Ix=(i,e,t)=>new pp(i,e,t);class kx extends pp{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(Q)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const Gx=(i,e,t=null)=>new kx(i,e,t);class Vx extends qe{static get type(){return"ToneMappingNode"}constructor(e,t=zx,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Fs(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===tr)return t;let r=null;const s=e.renderer.library.getToneMappingFunction(n);return s!==null?r=se(s(t.rgb,this.exposureNode),t.a):(G("ToneMappingNode: Unsupported Tone Mapping configuration.",n),r=t),r}}const $x=(i,e,t)=>$(new Vx(i,$(e),$(t))),zx=Gx("toneMappingExposure","float");w("toneMapping",(i,e,t)=>$x(e,t,i));const Uc=new WeakMap;function Oc(i,e){let t=Uc.get(i);return t===void 0&&(t=new my(i,e),Uc.set(i,t)),t}class vn extends yl{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=r,this.usage=hl,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){if(this.bufferStride===0&&this.bufferOffset===0){let t=e.globalCache.getData(this.value);return t===void 0&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(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),r=this.value,s=this.bufferStride||n,o=this.bufferOffset;let a;r.isInterleavedBuffer===!0?a=r:r.isBufferAttribute===!0?a=Oc(r.array,s):a=Oc(r,s);const u=new gy(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),r=e.getPropertyName(n);let s=null;return e.shaderStage==="vertex"||e.shaderStage==="compute"?(this.name=r,s=r):s=bn(this).build(e,t),s}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 Bl(i,e=null,t=0,n=0,r=hl,s=!1){return e==="mat3"||e===null&&i.itemSize===9?nt(new vn(i,"vec3",9,0).setUsage(r).setInstanced(s),new vn(i,"vec3",9,3).setUsage(r).setInstanced(s),new vn(i,"vec3",9,6).setUsage(r).setInstanced(s)):e==="mat4"||e===null&&i.itemSize===16?or(new vn(i,"vec4",16,0).setUsage(r).setInstanced(s),new vn(i,"vec4",16,4).setUsage(r).setInstanced(s),new vn(i,"vec4",16,8).setUsage(r).setInstanced(s),new vn(i,"vec4",16,12).setUsage(r).setInstanced(s)):new vn(i,e,t,n)}const gp=(i,e=null,t=0,n=0)=>Bl(i,e,t,n),Ic=(i,e=null,t=0,n=0)=>Bl(i,e,t,n,hl,!0),kc=(i,e=null,t=0,n=0)=>Bl(i,e,t,n,Mr,!0);w("toAttribute",i=>gp(i.value));class Wx extends H{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=oe.OBJECT,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return z('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){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 r=this.computeNode.build(e,"void");r!==""&&e.addLineFlowCode(r,this)}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const mp=(i,e=[64])=>{(e.length===0||e.length>3)&&G("TSL: compute() workgroupSize must have 1, 2, or 3 elements");for(let t=0;t<e.length;t++){const n=e[t];(typeof n!="number"||n<=0||!Number.isInteger(n))&&G(`TSL: compute() workgroupSize element at index [ ${t} ] must be a positive integer`)}for(;e.length<3;)e.push(1);return $(new Wx($(i),e))},jx=(i,e,t)=>mp(i,t).setCount(e);w("compute",jx);w("computeKernel",mp);class qx extends H{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const r=this.node.getNodeType(e);return e.setCache(t),r}build(e,...t){const n=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.build(e,...t);return e.setCache(n),s}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const ks=i=>new qx($(i));function Hx(i,e=!0){return z('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),ks(i).setParent(e)}w("cache",Hx);w("isolate",ks);class Xx extends H{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(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 Kx=me(Xx).setParameterLength(2);w("bypass",Kx);class yp extends H{static get type(){return"RemapNode"}constructor(e,t,n,r=N(0),s=N(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=r,this.outHighNode=s,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:r,outHighNode:s,doClamp:o}=this;let a=e.sub(t).div(n.sub(t));return o===!0&&(a=a.clamp()),a.mul(s.sub(r)).add(r)}}const Yx=me(yp,null,null,{doClamp:!1}).setParameterLength(3,5),Qx=me(yp).setParameterLength(3,5);w("remap",Yx);w("remapClamp",Qx);class Yi extends H{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),r=this.snippet;if(n==="void")e.addLineFlowCode(r,this);else return e.format(r,n,t)}}const jr=me(Yi).setParameterLength(1,2),Zx=i=>(i?lt(i,jr("discard")):jr("discard")).toStack();w("discard",Zx);class Jx extends qe{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)||tr,r=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||Vr;return n!==tr&&(t=t.toneMapping(n)),r!==Vr&&r!==Ve.workingColorSpace&&(t=t.workingToColorSpace(r)),t}}const eT=(i,e=null,t=null)=>$(new Jx($(i),e,t));w("renderOutput",eT);class tT extends qe{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(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),r="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(r.length);let o="";return o+="// #"+r+`#
524
+ `,o+=e.flow.code.replace(/^\t/mg,"")+`
525
+ `,o+="/* ... */ "+n+` /* ... */
526
+ `,o+="// #"+s+`#
527
+ `,t!==null?t(e,o):yy(o),n}}const nT=(i,e=null)=>$(new tT($(i),e)).toStack();w("debug",nT);class bp{constructor(){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 rT extends H{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=oe.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(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!==bp&&Ge('TSL: ".toInspector()" is only available with WebGPU.'),t}}function sT(i,e="",t=null){return i=$(i),i.before(new rT(i,e,t))}w("toInspector",sT);class _p extends H{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(t===null){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const r=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(r)}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 s=e.geometry.getAttribute(t),o=e.getTypeFromAttribute(s),a=e.getAttribute(t,o);return e.shaderStage==="vertex"?e.format(a.name,o,n):bn(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 In=(i,e=null)=>new _p(i,e),es=(i=0)=>In("uv"+(i>0?i:""),"vec2");class iT extends H{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"),r=this.levelNode===null?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${r} )`,this.getNodeType(e),t)}}const ur=me(iT).setParameterLength(1,2);class oT extends ti{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=oe.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:r,height:s}=n;this.value=Math.log2(Math.max(r,s))}}}const aT=me(oT).setParameterLength(1),xp=new dl;class ts extends ti{static get type(){return"TextureNode"}constructor(e=xp,t=null,n=null,r=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=r,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=oe.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}getNodeType(){return this.value.isDepthTexture===!0?"float":this.value.type===je?"uvec4":this.value.type===st?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return es(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=Z(this.value.matrix)),this._matrixUniform.mul(R(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(this._flipYUniform===null&&(this._flipYUniform=Z(!1)),t=t.toVar(),this.sampler?t=this._flipYUniform.select(t.flipY(),t):t=this._flipYUniform.select(t.setY(Me(ur(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 Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");const r=P(()=>{let o=this.uvNode;return(o===null||e.context.forceUVContext===!0)&&e.context.getUV&&(o=e.context.getUV(this,e)),o||(o=this.getDefaultUV()),this.updateMatrix===!0&&(o=this.getTransformedUV(o)),o=this.setupUV(e,o),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?oe.OBJECT:oe.NONE,o})();let s=this.levelNode;s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),t.uvNode=r,t.levelNode=s,t.biasNode=this.biasNode,t.compareNode=this.compareNode,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,r,s,o,a,u,l){const c=this.value;let d;return s?d=e.generateTextureBias(c,t,n,s,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,r,o,l):r?d=e.generateTextureLevel(c,t,n,r,o,l):d=e.generateTexture(c,t,n,o,l),d}generate(e,t){const n=this.value,r=e.getNodeProperties(this),s=super.generate(e,"property");if(/^sampler/.test(t))return s+"_sampler";if(e.isReference(t))return s;{const o=e.getDataFromNode(this);let a=o.propertyName;if(a===void 0){const{uvNode:c,levelNode:d,biasNode:h,compareNode:p,depthNode:f,gradNode:g,offsetNode:m}=r,y=this.generateUV(e,c),_=d?d.build(e,"float"):null,T=h?h.build(e,"float"):null,A=f?f.build(e,"int"):null,B=p?p.build(e,"float"):null,S=g?[g[0].build(e,"vec2"),g[1].build(e,"vec2")]:null,v=m?this.generateOffset(e,m):null,E=e.getVarFromNode(this);a=e.getPropertyName(E);const D=this.generateSnippet(e,s,y,_,T,A,B,S,v);e.addLineFlowCode(`${a} = ${D}`,this),o.snippet=D,o.propertyName=a}let u=a;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(n)&&(u=Pl(jr(u,l),n.colorSpace).setup(e).build(e,l)),e.format(u,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return z("TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=$(e),t.referenceNode=this.getBase(),$(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=$(e).mul(aT(t)),t.referenceNode=this.getBase();const n=t.value;return t.generateMipmaps===!1&&(n&&n.generateMipmaps===!1||n.minFilter===Bt||n.magFilter===Bt)&&(z("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),$(t)}level(e){const t=this.clone();return t.levelNode=$(e),t.referenceNode=this.getBase(),$(t)}size(e){return ur(this,e)}bias(e){const t=this.clone();return t.biasNode=$(e),t.referenceNode=this.getBase(),$(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=$(e),t.referenceNode=this.getBase(),$(t)}grad(e,t){const n=this.clone();return n.gradNode=[$(e),$(t)],n.referenceNode=this.getBase(),$(n)}depth(e){const t=this.clone();return t.depthNode=$(e),t.referenceNode=this.getBase(),$(t)}offset(e){const t=this.clone();return t.offsetNode=$(e),t.referenceNode=this.getBase(),$(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 uT=me(ts).setParameterLength(1,4).setName("texture"),Pe=(i=xp,e=null,t=null,n=null)=>{let r;return i&&i.isTextureNode===!0?(r=$(i.clone()),r.referenceNode=i.getBase(),e!==null&&(r.uvNode=$(e)),t!==null&&(r.levelNode=$(t)),n!==null&&(r.biasNode=$(n))):r=uT(i,e,t,n),r},Tt=(...i)=>Pe(...i).setSampler(!1);class Dl extends ti{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 Tp=(i,e,t)=>new Dl(i,e,t);class lT extends Jr{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(),r=this.node.getPaddedType();return e.format(t,r,n)}}class cT extends Dl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?ho(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=oe.RENDER,this.isArrayBufferNode=!0}getNodeType(){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 r=0;r<e.length;r++){const s=r*4;t[s]=e[r]}else if(n==="color")for(let r=0;r<e.length;r++){const s=r*4,o=e[r];t[s]=o.r,t[s+1]=o.g,t[s+2]=o.b||0}else if(n==="mat2")for(let r=0;r<e.length;r++){const s=r*4,o=e[r];t[s]=o.elements[0],t[s+1]=o.elements[1],t[s+2]=o.elements[2],t[s+3]=o.elements[3]}else if(n==="mat3")for(let r=0;r<e.length;r++){const s=r*16,o=e[r];t[s]=o.elements[0],t[s+1]=o.elements[1],t[s+2]=o.elements[2],t[s+4]=o.elements[3],t[s+5]=o.elements[4],t[s+6]=o.elements[5],t[s+8]=o.elements[6],t[s+9]=o.elements[7],t[s+10]=o.elements[8],t[s+15]=1}else if(n==="mat4")for(let r=0;r<e.length;r++){const s=r*16,o=e[r];for(let a=0;a<o.elements.length;a++)t[s+a]=o.elements[a]}else for(let r=0;r<e.length;r++){const s=r*4,o=e[r];t[s]=o.x,t[s+1]=o.y,t[s+2]=o.z||0,t[s+3]=o.w||0}}setup(e){const t=this.array.length,n=this.elementType;let r=Float32Array;const s=this.paddedType,o=e.getTypeLength(s);return n.charAt(0)==="i"&&(r=Int32Array),n.charAt(0)==="u"&&(r=Uint32Array),this.value=new r(t*o),this.bufferCount=t,this.bufferType=s,super.setup(e)}element(e){return new lT(this,$(e))}}const Dt=(i,e)=>new cT(i,e);class dT extends H{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const ni=me(dT).setParameterLength(1);let hs,fs;class Ee extends H{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===Ee.DPR?"float":this.scope===Ee.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=oe.NONE;return(this.scope===Ee.SIZE||this.scope===Ee.VIEWPORT||this.scope===Ee.DPR)&&(e=oe.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ee.VIEWPORT?t!==null?fs.copy(t.viewport):(e.getViewport(fs),fs.multiplyScalar(e.getPixelRatio())):this.scope===Ee.DPR?this._output.value=e.getPixelRatio():t!==null?(hs.width=t.width,hs.height=t.height):e.getDrawingBufferSize(hs)}setup(){const e=this.scope;let t=null;return e===Ee.SIZE?t=Z(hs||(hs=new ce)):e===Ee.VIEWPORT?t=Z(fs||(fs=new Oe)):e===Ee.DPR?t=Z(1):t=j(ns.div(Ou)),this._output=t,t}generate(e){if(this.scope===Ee.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Ou).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 hT=U(Ee,Ee.DPR),Ir=U(Ee,Ee.UV),Ou=U(Ee,Ee.SIZE),ns=U(Ee,Ee.COORDINATE),vp=U(Ee,Ee.VIEWPORT),fT=vp.zw;vp.xy;const Fl=Z(0,"uint").setName("u_cameraIndex").setGroup(Rl("cameraIndex")).toVarying("v_cameraIndex"),Qn=Z("float").setName("cameraNear").setGroup(Q).onRenderUpdate(({camera:i})=>i.near),Zn=Z("float").setName("cameraFar").setGroup(Q).onRenderUpdate(({camera:i})=>i.far),Gs=P(({camera:i})=>{let e;if(i.isArrayCamera&&i.cameras.length>0){const t=[];for(const r of i.cameras)t.push(r.projectionMatrix);e=Dt(t).setGroup(Q).setName("cameraProjectionMatrices").element(i.isMultiViewCamera?ni("gl_ViewID_OVR"):Fl).toConst("cameraProjectionMatrix")}else e=Z("mat4").setName("cameraProjectionMatrix").setGroup(Q).onRenderUpdate(({camera:t})=>t.projectionMatrix);return e}).once()(),_n=P(({camera:i})=>{let e;if(i.isArrayCamera&&i.cameras.length>0){const t=[];for(const r of i.cameras)t.push(r.matrixWorldInverse);e=Dt(t).setGroup(Q).setName("cameraViewMatrices").element(i.isMultiViewCamera?ni("gl_ViewID_OVR"):Fl).toConst("cameraViewMatrix")}else e=Z("mat4").setName("cameraViewMatrix").setGroup(Q).onRenderUpdate(({camera:t})=>t.matrixWorldInverse);return e}).once()(),pT=P(({camera:i})=>{let e;if(i.isArrayCamera&&i.cameras.length>0){const t=[];for(let r=0,s=i.cameras.length;r<s;r++)t.push(new I);e=Dt(t).setGroup(Q).setName("cameraPositions").onRenderUpdate(({camera:r},s)=>{const o=r.cameras,a=s.array;for(let u=0,l=o.length;u<l;u++)a[u].setFromMatrixPosition(o[u].matrixWorld)}).element(i.isMultiViewCamera?ni("gl_ViewID_OVR"):Fl).toConst("cameraPosition")}else e=Z(new I).setName("cameraPosition").setGroup(Q).onRenderUpdate(({camera:t},n)=>n.value.setFromMatrixPosition(t.matrixWorld));return e}).once()(),Gc=new uy;class we extends H{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=oe.OBJECT,this.uniformNode=new ti(null)}getNodeType(){const e=this.scope;if(e===we.WORLD_MATRIX)return"mat4";if(e===we.POSITION||e===we.VIEW_POSITION||e===we.DIRECTION||e===we.SCALE)return"vec3";if(e===we.RADIUS)return"float"}update(e){const t=this.object3d,n=this.uniformNode,r=this.scope;if(r===we.WORLD_MATRIX)n.value=t.matrixWorld;else if(r===we.POSITION)n.value=n.value||new I,n.value.setFromMatrixPosition(t.matrixWorld);else if(r===we.SCALE)n.value=n.value||new I,n.value.setFromMatrixScale(t.matrixWorld);else if(r===we.DIRECTION)n.value=n.value||new I,t.getWorldDirection(n.value);else if(r===we.VIEW_POSITION){const s=e.camera;n.value=n.value||new I,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(s.matrixWorldInverse)}else if(r===we.RADIUS){const s=e.object.geometry;s.boundingSphere===null&&s.computeBoundingSphere(),Gc.copy(s.boundingSphere).applyMatrix4(t.matrixWorld),n.value=Gc.radius}}generate(e){const t=this.scope;return t===we.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===we.POSITION||t===we.VIEW_POSITION||t===we.DIRECTION||t===we.SCALE?this.uniformNode.nodeType="vec3":t===we.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}}we.WORLD_MATRIX="worldMatrix";we.POSITION="position";we.SCALE="scale";we.VIEW_POSITION="viewPosition";we.DIRECTION="direction";we.RADIUS="radius";const gT=me(we,we.POSITION).setParameterLength(1);class At extends we{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}At.DIRECTION;const pr=U(At,At.WORLD_MATRIX);At.POSITION;At.SCALE;At.VIEW_POSITION;At.RADIUS;const mT=Z(new Js).onObjectUpdate(({object:i},e)=>e.value.getNormalMatrix(i.matrixWorld)),ri=P(i=>i.context.modelViewMatrix||yT).once()().toVar("modelViewMatrix"),yT=_n.mul(pr),Vc=P(i=>(i.context.isHighPrecisionModelViewMatrix=!0,Z("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),$c=P(i=>{const e=i.context.isHighPrecisionModelViewMatrix;return Z("mat3").onObjectUpdate(({object:t,camera:n})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),Do=In("position","vec3"),Ke=Do.toVarying("positionLocal"),zc=Do.toVarying("positionPrevious"),qr=P(i=>pr.mul(Ke).xyz.toVarying(i.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Sp=P(()=>Ke.transformDirection(pr).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),$e=P(i=>i.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),Ce=P(i=>{let e;return i.camera.isOrthographicCamera?e=R(0,0,1):e=$e.negate().toVarying("v_positionViewDirection").normalize(),e.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class bT extends H{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===ht?"false":e.getFrontFacing()}}const _T=U(bT),Np=N(_T).mul(2).sub(1),si=P(([i],{material:e})=>{const t=e.side;return t===ht?i=i.mul(-1):t===rr&&(i=i.mul(Np)),i}),Rp=In("normal","vec3"),en=P(i=>i.geometry.hasAttribute("normal")===!1?(z('TSL: Vertex attribute "normal" not found on geometry.'),R(0,1,0)):Rp,"vec3").once()().toVar("normalLocal"),xT=$e.dFdx().cross($e.dFdy()).normalize().toVar("normalFlat"),Ks=P(i=>{let e;return i.material.flatShading===!0?e=xT:e=wp(en).toVarying("v_normalViewGeometry").normalize(),e},"vec3").once()().toVar("normalViewGeometry"),TT=P(i=>{let e=Ks.transformDirection(_n);return i.material.flatShading!==!0&&(e=e.toVarying("v_normalWorldGeometry")),e.normalize().toVar("normalWorldGeometry")},"vec3").once()(),pe=P(({subBuildFn:i,material:e,context:t})=>{let n;return i==="NORMAL"||i==="VERTEX"?(n=Ks,e.flatShading!==!0&&(n=si(n))):n=t.setupNormal().context({getUV:null}),n},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),rs=pe.transformDirection(_n).toVar("normalWorld"),Dr=P(({subBuildFn:i,context:e})=>{let t;return i==="NORMAL"||i==="VERTEX"?t=pe:t=e.setupClearcoatNormal().context({getUV:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),vT=P(([i,e=pr])=>{const t=nt(e),n=i.div(R(t[0].dot(t[0]),t[1].dot(t[1]),t[2].dot(t[2])));return t.mul(n).xyz}),wp=P(([i],e)=>{const t=e.context.modelNormalViewMatrix;if(t)return t.transformDirection(i);const n=mT.mul(i);return _n.transformDirection(n)});P(()=>(z('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),pe)).once(["NORMAL","VERTEX"])();P(()=>(z('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),rs)).once(["NORMAL","VERTEX"])();P(()=>(z('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Dr)).once(["NORMAL","VERTEX"])();const Wc=new of,la=new Et,ST=Z(0).onReference(({material:i})=>i).onObjectUpdate(({material:i})=>i.refractionRatio),ca=Z(1).onReference(({material:i})=>i).onObjectUpdate(function({material:i,scene:e}){return i.envMap?i.envMapIntensity:e.environmentIntensity}),Ap=Z(new Et).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?(Wc.copy(t),la.makeRotationFromEuler(Wc)):la.identity(),la}),NT=Ce.negate().reflect(pe),RT=Ce.negate().refract(pe,ST),wT=NT.transformDirection(_n).toVar("reflectVector"),AT=RT.transformDirection(_n).toVar("reflectVector"),ET=new cl;class CT extends ts{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,r=null){super(e,t,n,r),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===uo?wT:e.mapping===lo?AT:(G('CubeTextureNode: Mapping "%s" not supported.',e.mapping),R(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return n.isDepthTexture===!0?e.renderer.coordinateSystem===Gr?R(t.x,t.y.negate(),t.z):t:((e.renderer.coordinateSystem===Gr||!n.isRenderTargetTexture)&&(t=R(t.x.negate(),t.yz)),Ap.mul(t))}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}}const MT=me(CT).setParameterLength(1,4).setName("cubeTexture"),ut=(i=ET,e=null,t=null,n=null)=>{let r;return i&&i.isCubeTextureNode===!0?(r=$(i.clone()),r.referenceNode=i,e!==null&&(r.uvNode=$(e)),t!==null&&(r.levelNode=$(t)),n!==null&&(r.biasNode=$(n))):r=MT(i,e,t,n),r};class PT extends Jr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),r=this.getNodeType();return e.format(t,n,r)}}class Ll extends H{static get type(){return"ReferenceNode"}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=oe.OBJECT}element(e){return new PT(this,$(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=Tp(null,e,this.count):Array.isArray(this.getValueFromReference())?t=Dt(null,e):e==="texture"?t=Pe(null):e==="cubeTexture"?t=ut(null):t=Z(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.setName(this.name),this.node=t}getNodeType(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 r=1;r<t.length;r++)n=n[t[r]];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 Se=(i,e,t)=>new Ll(i,e,t),jc=(i,e,t,n)=>new Ll(i,e,n,t);class BT extends Ll{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 En=(i,e,t=null)=>new BT(i,e,t),Ep=es(),DT=$e.dFdx(),FT=$e.dFdy(),Cp=Ep.dFdx(),Mp=Ep.dFdy(),Pp=pe,Bp=FT.cross(Pp),Dp=Pp.cross(DT),Iu=Bp.mul(Cp.x).add(Dp.mul(Mp.x)),ku=Bp.mul(Cp.y).add(Dp.mul(Mp.y)),qc=Iu.dot(Iu).max(ku.dot(ku)),Fp=qc.equal(0).select(0,qc.inverseSqrt()),LT=Iu.mul(Fp).toVar("tangentViewFrame"),UT=ku.mul(Fp).toVar("bitangentViewFrame"),Lp=In("tangent","vec4"),Ul=Lp.xyz.toVar("tangentLocal"),Up=P(({subBuildFn:i,geometry:e,material:t})=>{let n;return i==="VERTEX"||e.hasAttribute("tangent")?n=ri.mul(se(Ul,0)).xyz.toVarying("v_tangentView").normalize():n=LT,t.flatShading!==!0&&(n=si(n)),n},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),OT=P(([i,e],{subBuildFn:t,material:n})=>{let r=i.mul(Lp.w).xyz;return t==="NORMAL"&&n.flatShading!==!0&&(r=r.toVarying(e)),r}).once(["NORMAL"]),IT=P(({subBuildFn:i,geometry:e,material:t})=>{let n;return i==="VERTEX"||e.hasAttribute("tangent")?n=OT(pe.cross(Up),"v_bitangentView").normalize():n=UT,t.flatShading!==!0&&(n=si(n)),n},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),As=nt(Up,IT,pe).toVar("TBNViewMatrix"),kT=P(()=>{let i=Or.cross(Ce);return i=i.cross(Or).normalize(),i=Ne(i,pe,Xn.mul(cn.oneMinus()).oneMinus().pow2().pow2()).normalize(),i}).once()(),GT=i=>$(i).mul(.5).add(.5),Hc=i=>R(i,fn(El(N(1).sub(hr(i,i)))));class VT extends qe{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=Wo,this.unpackNormalMode=jo}setup({material:e}){const{normalMapType:t,scaleNode:n,unpackNormalMode:r}=this;let s=this.node.mul(2).sub(1);if(t===Wo?r===sf?s=Hc(s.xy):r===ly?s=Hc(s.yw):r!==jo&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${r}`):r!==jo&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${r}'`),n!==null){let a=n;e.flatShading===!0&&(a=si(a)),s=R(s.xy.mul(a),s.z)}let o=null;return t===cy?o=wp(s):t===Wo?o=As.mul(s).normalize():(G(`NodeMaterial: Unsupported normal map type: ${t}`),o=pe),o}}const Xc=me(VT).setParameterLength(1,2),$T=P(({textureNode:i,bumpScale:e})=>{const t=r=>i.isolate().context({getUV:s=>r(s.uvNode||es()),forceUVContext:!0}),n=N(t(r=>r));return j(N(t(r=>r.add(r.dFdx()))).sub(n),N(t(r=>r.add(r.dFdy()))).sub(n)).mul(e)}),zT=P(i=>{const{surf_pos:e,surf_norm:t,dHdxy:n}=i,r=e.dFdx().normalize(),s=e.dFdy().normalize(),o=t,a=s.cross(o),u=o.cross(r),l=r.dot(a).mul(Np),c=l.sign().mul(n.x.mul(a).add(n.y.mul(u)));return l.abs().mul(t).sub(c).normalize()});class WT extends qe{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=$T({textureNode:this.textureNode,bumpScale:e});return zT({surf_pos:$e,surf_norm:pe,dHdxy:t})}}const jT=me(WT).setParameterLength(1,2),Kc=new Map;class C extends H{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=Kc.get(e);return n===void 0&&(n=En(e,t),Kc.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 r=null;if(n===C.COLOR){const s=t.color!==void 0?this.getColor(n):R();t.map&&t.map.isTexture===!0?r=s.mul(this.getTexture("map")):r=s}else if(n===C.OPACITY){const s=this.getFloat(n);t.alphaMap&&t.alphaMap.isTexture===!0?r=s.mul(this.getTexture("alpha")):r=s}else if(n===C.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?r=this.getTexture("specular").r:r=N(1);else if(n===C.SPECULAR_INTENSITY){const s=this.getFloat(n);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?r=s.mul(this.getTexture(n).a):r=s}else if(n===C.SPECULAR_COLOR){const s=this.getColor(n);t.specularColorMap&&t.specularColorMap.isTexture===!0?r=s.mul(this.getTexture(n).rgb):r=s}else if(n===C.ROUGHNESS){const s=this.getFloat(n);t.roughnessMap&&t.roughnessMap.isTexture===!0?r=s.mul(this.getTexture(n).g):r=s}else if(n===C.METALNESS){const s=this.getFloat(n);t.metalnessMap&&t.metalnessMap.isTexture===!0?r=s.mul(this.getTexture(n).b):r=s}else if(n===C.EMISSIVE){const s=this.getFloat("emissiveIntensity"),o=this.getColor(n).mul(s);t.emissiveMap&&t.emissiveMap.isTexture===!0?r=o.mul(this.getTexture(n)):r=o}else if(n===C.NORMAL)t.normalMap?(r=Xc(this.getTexture("normal"),this.getCache("normalScale","vec2")),r.normalMapType=t.normalMapType,(t.normalMap.format==hn||t.normalMap.format==io||t.normalMap.format==so)&&(r.unpackNormalMode=sf)):t.bumpMap?r=jT(this.getTexture("bump").r,this.getFloat("bumpScale")):r=pe;else if(n===C.CLEARCOAT){const s=this.getFloat(n);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?r=s.mul(this.getTexture(n).r):r=s}else if(n===C.CLEARCOAT_ROUGHNESS){const s=this.getFloat(n);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?r=s.mul(this.getTexture(n).r):r=s}else if(n===C.CLEARCOAT_NORMAL)t.clearcoatNormalMap?r=Xc(this.getTexture(n),this.getCache(n+"Scale","vec2")):r=pe;else if(n===C.SHEEN){const s=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?r=s.mul(this.getTexture("sheenColor").rgb):r=s}else if(n===C.SHEEN_ROUGHNESS){const s=this.getFloat(n);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?r=s.mul(this.getTexture(n).a):r=s,r=r.clamp(1e-4,1)}else if(n===C.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const s=this.getTexture(n);r=Sl(ps.x,ps.y,ps.y.negate(),ps.x).mul(s.rg.mul(2).sub(j(1)).normalize().mul(s.b))}else r=ps;else if(n===C.IRIDESCENCE_THICKNESS){const s=Se("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const o=Se("0","float",t.iridescenceThicknessRange);r=s.sub(o).mul(this.getTexture(n).g).add(o)}else r=s}else if(n===C.TRANSMISSION){const s=this.getFloat(n);t.transmissionMap?r=s.mul(this.getTexture(n).r):r=s}else if(n===C.THICKNESS){const s=this.getFloat(n);t.thicknessMap?r=s.mul(this.getTexture(n).g):r=s}else if(n===C.IOR)r=this.getFloat(n);else if(n===C.LIGHT_MAP)r=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===C.AO)r=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===C.LINE_DASH_OFFSET)r=t.dashOffset?this.getFloat(n):N(0);else{const s=this.getNodeType(e);r=this.getCache(n,s)}return r}}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 qT=U(C,C.ALPHA_TEST),HT=U(C,C.COLOR),XT=U(C,C.SHININESS),KT=U(C,C.EMISSIVE),Op=U(C,C.OPACITY),YT=U(C,C.SPECULAR),Yc=U(C,C.SPECULAR_INTENSITY),QT=U(C,C.SPECULAR_COLOR),Qi=U(C,C.SPECULAR_STRENGTH),da=U(C,C.REFLECTIVITY),ZT=U(C,C.ROUGHNESS),JT=U(C,C.METALNESS),ev=U(C,C.NORMAL),tv=U(C,C.CLEARCOAT),nv=U(C,C.CLEARCOAT_ROUGHNESS),rv=U(C,C.CLEARCOAT_NORMAL),sv=U(C,C.ROTATION),iv=U(C,C.SHEEN),ov=U(C,C.SHEEN_ROUGHNESS),av=U(C,C.ANISOTROPY),uv=U(C,C.IRIDESCENCE),lv=U(C,C.IRIDESCENCE_IOR),cv=U(C,C.IRIDESCENCE_THICKNESS),dv=U(C,C.TRANSMISSION),hv=U(C,C.THICKNESS),fv=U(C,C.IOR),pv=U(C,C.ATTENUATION_DISTANCE),gv=U(C,C.ATTENUATION_COLOR),mv=U(C,C.LINE_SCALE),yv=U(C,C.LINE_DASH_SIZE),bv=U(C,C.LINE_GAP_SIZE);C.LINE_WIDTH;const _v=U(C,C.LINE_DASH_OFFSET),xv=U(C,C.POINT_SIZE),Tv=U(C,C.DISPERSION),Ip=U(C,C.LIGHT_MAP),vv=U(C,C.AO),ps=Z(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))}),Sv=P(i=>i.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Nv extends Jr{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 r=e.context.assign;if(e.isAvailable("storageBuffer")===!1?this.node.isPBO===!0&&r!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!=="compute")?n=e.generatePBO(this):n=this.node.build(e):n=super.generate(e),r!==!0){const s=this.getNodeType(e);n=e.format(n,s,t)}return n}}const Rv=me(Nv).setParameterLength(2);class wv extends Dl{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let r,s=null;t&&t.isStruct?(r="struct",s=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(r=Pf(e.itemSize),n=e.count):r=t,super(e,r,n),this.isStorageBufferNode=!0,this.structTypeNode=s,this.access=Nt.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){if(this.bufferCount===0){let t=e.globalCache.getData(this.value);return t===void 0&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Rv(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Nt.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=gp(this.value),this._varying=bn(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(this.structTypeNode!==null)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(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(),r=n.build(e);return e.registerTransform(r,t),r}}const Qc=(i,e=null,t=0)=>new wv(i,e,t);class De extends H{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 r;if(n===De.VERTEX)r=e.getVertexIndex();else if(n===De.INSTANCE)r=e.getInstanceIndex();else if(n===De.DRAW)r=e.getDrawIndex();else if(n===De.INVOCATION_LOCAL)r=e.getInvocationLocalIndex();else if(n===De.INVOCATION_SUBGROUP)r=e.getInvocationSubgroupIndex();else if(n===De.SUBGROUP)r=e.getSubgroupIndex();else throw new Error("THREE.IndexNode: Unknown scope: "+n);let s;return e.shaderStage==="vertex"||e.shaderStage==="compute"?s=r:s=bn(this).build(e,t),s}}De.VERTEX="vertex";De.INSTANCE="instance";De.SUBGROUP="subgroup";De.INVOCATION_LOCAL="invocationLocal";De.INVOCATION_SUBGROUP="invocationSubgroup";De.DRAW="draw";const Av=U(De,De.VERTEX),Vs=U(De,De.INSTANCE);De.SUBGROUP;De.INVOCATION_SUBGROUP;De.INVOCATION_LOCAL;const Ev=U(De,De.DRAW);class Cv extends H{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=oe.FRAME,this.buffer=null,this.bufferColor=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){const{instanceMatrix:t,instanceColor:n,isStorageMatrix:r,isStorageColor:s}=this,{count:o}=t;let{instanceMatrixNode:a,instanceColorNode:u}=this;if(a===null){if(r)a=Qc(t,"mat4",Math.max(o,1)).element(Vs);else if(o<=1e3)a=Tp(t.array,"mat4",Math.max(o,1)).element(Vs);else{const c=new dy(t.array,16,1);this.buffer=c;const d=t.usage===Mr?kc:Ic,h=[d(c,"vec4",16,0),d(c,"vec4",16,4),d(c,"vec4",16,8),d(c,"vec4",16,12)];a=or(...h)}this.instanceMatrixNode=a}if(n&&u===null){if(s)u=Qc(n,"vec3",Math.max(n.count,1)).element(Vs);else{const c=new hy(n.array,3),d=n.usage===Mr?kc:Ic;this.bufferColor=c,u=R(d(c,"vec3",3,0))}this.instanceColorNode=u}const l=a.mul(Ke).xyz;if(Ke.assign(l),e.hasGeometryAttribute("normal")){const c=vT(en,a);en.assign(c)}this.instanceColorNode!==null&&po("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.buffer!==null&&this.isStorageMatrix!==!0&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.usage!==Mr&&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.usage!==Mr&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version))}}class Mv extends Cv{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:r}=e;super(t,n,r),this.instancedMesh=e}}const Pv=me(Mv).setParameterLength(1);class Bv extends H{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=Vs:this.batchingIdNode=Ev);const n=P(([f])=>{const g=Me(ur(Tt(this.batchMesh._indirectTexture),0).x).toConst(),m=Me(f).mod(g).toConst(),y=Me(f).div(g).toConst();return Tt(this.batchMesh._indirectTexture,qt(m,y)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(Me(this.batchingIdNode)),r=this.batchMesh._matricesTexture,s=Me(ur(Tt(r),0).x).toConst(),o=N(n).mul(4).toInt().toConst(),a=o.mod(s).toConst(),u=o.div(s).toConst(),l=or(Tt(r,qt(a,u)),Tt(r,qt(a.add(1),u)),Tt(r,qt(a.add(2),u)),Tt(r,qt(a.add(3),u))),c=this.batchMesh._colorsTexture;if(c!==null){const g=P(([m])=>{const y=Me(ur(Tt(c),0).x).toConst(),_=m,T=_.mod(y).toConst(),A=_.div(y).toConst();return Tt(c,qt(T,A)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(n);po("vec3","vBatchColor").assign(g)}const d=nt(l);Ke.assign(l.mul(Ke));const h=en.div(R(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),p=d.mul(h).xyz;en.assign(p),e.hasGeometryAttribute("tangent")&&Ul.mulAssign(d)}}const Dv=me(Bv).setParameterLength(1),Zc=new WeakMap;class Fv extends H{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=oe.OBJECT,this.skinIndexNode=In("skinIndex","uvec4"),this.skinWeightNode=In("skinWeight","vec4"),this.bindMatrixNode=Se("bindMatrix","mat4"),this.bindMatrixInverseNode=Se("bindMatrixInverse","mat4"),this.boneMatricesNode=jc("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Ke,this.toPositionNode=Ke,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:n,skinWeightNode:r,bindMatrixNode:s,bindMatrixInverseNode:o}=this,a=e.element(n.x),u=e.element(n.y),l=e.element(n.z),c=e.element(n.w),d=s.mul(t),h=pt(a.mul(r.x).mul(d),u.mul(r.y).mul(d),l.mul(r.z).mul(d),c.mul(r.w).mul(d));return o.mul(h).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=en){const{skinIndexNode:n,skinWeightNode:r,bindMatrixNode:s,bindMatrixInverseNode:o}=this,a=e.element(n.x),u=e.element(n.y),l=e.element(n.z),c=e.element(n.w);let d=pt(r.x.mul(a),r.y.mul(u),r.z.mul(l),r.w.mul(c));return d=o.mul(d).mul(s),d.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return this.previousBoneMatricesNode===null&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=jc("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,zc)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||Bf(e.object).useVelocity===!0}setup(e){this.needsPreviousBoneMatrices(e)&&zc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const n=this.getSkinnedNormal();en.assign(n),e.hasGeometryAttribute("tangent")&&Ul.assign(n)}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;Zc.get(t)!==e.frameId&&(Zc.set(t,e.frameId),this.previousBoneMatricesNode!==null&&(t.previousBoneMatrices===null&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const Lv=i=>new Fv(i);class Uv extends H{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]=jr(c,d)}const r=e.addStack(),s=this.params[this.params.length-1](n);t.returnsNode=s.context({nodeLoop:s}),t.stackNode=r;const o=this.params[0];if(o.isNode!==!0&&typeof o.update=="function"){const a=P(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,r=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,p=null,f=null,g=null;u.isNode?u.getNodeType(e)==="bool"?(l=!0,p="bool",d=u.build(e,p)):(p="int",h=this.getVarName(o),c="0",d=u.build(e,p),f="<"):(p=u.type||"int",h=u.name||this.getVarName(o),c=u.start,d=u.end,f=u.condition,g=u.update,typeof c=="number"?c=e.generateConst(p,c):c&&c.isNode&&(c=c.build(e,p)),typeof d=="number"?d=e.generateConst(p,d):d&&d.isNode&&(d=d.build(e,p)),c!==void 0&&d===void 0?(c=c+" - 1",d="0",f=">="):d!==void 0&&c===void 0&&(c="0",f="<"),f===void 0&&(Number(c)>Number(d)?f=">=":f="<"));let m;if(l)m=`while ( ${d} )`;else{const y={start:c,end:d},_=y.start,T=y.end;let A;const B=()=>f.includes("<")?"+=":"-=";if(g!=null)switch(typeof g){case"function":A=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":A=h+" "+B()+" "+e.generateConst(p,g);break;case"string":A=h+" "+g;break;default:g.isNode?A=h+" "+B()+" "+g.build(e):(G("TSL: 'Loop( { update: ... } )' is not a function, string or number."),A="break /* invalid update */")}else p==="int"||p==="uint"?g=f.includes("<")?"++":"--":g=B()+" 1.",A=h+" "+g;const S=e.getVar(p,h)+" = "+_,v=h+" "+f+" "+T;m=`for ( ${S}; ${v}; ${A} )`}e.addFlowCode((o===0?`
528
+ `:"")+e.tab+m+` {
529
+
530
+ `).addFlowTab()}const s=r.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode(`
531
+ `+e.tab+s);for(let o=0,a=this.params.length-1;o<a;o++)e.addFlowCode((o===0?"":e.tab)+`}
532
+
533
+ `).removeFlowTab();e.addFlowTab()}}const St=(...i)=>new Uv(Ur(i,"int")).toStack(),Ov=()=>jr("break").toStack(),ha=new WeakMap,gt=new Oe,Jc=P(({bufferMap:i,influence:e,stride:t,width:n,depth:r,offset:s})=>{const o=Me(Av).mul(t).add(s),a=o.div(n),u=o.sub(a.mul(n));return Tt(i,qt(u,a)).depth(r).xyz.mul(e)});function Iv(i){const e=i.morphAttributes.position!==void 0,t=i.morphAttributes.normal!==void 0,n=i.morphAttributes.color!==void 0,r=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,s=r!==void 0?r.length:0;let o=ha.get(i);if(o===void 0||o.count!==s){let y=function(){g.dispose(),ha.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 p=4096;d>p&&(h=Math.ceil(d/p),d=p);const f=new Float32Array(d*h*4*s),g=new fy(f,d,h,s);g.type=vt,g.needsUpdate=!0;const m=c*4;for(let _=0;_<s;_++){const T=a[_],A=u[_],B=l[_],S=d*h*4*_;for(let v=0;v<T.count;v++){const E=v*m;e===!0&&(gt.fromBufferAttribute(T,v),f[S+E+0]=gt.x,f[S+E+1]=gt.y,f[S+E+2]=gt.z,f[S+E+3]=0),t===!0&&(gt.fromBufferAttribute(A,v),f[S+E+4]=gt.x,f[S+E+5]=gt.y,f[S+E+6]=gt.z,f[S+E+7]=0),n===!0&&(gt.fromBufferAttribute(B,v),f[S+E+8]=gt.x,f[S+E+9]=gt.y,f[S+E+10]=gt.z,f[S+E+11]=B.itemSize===4?gt.w:1)}}o={count:s,texture:g,stride:c,size:new ce(d,h)},ha.set(i,o),i.addEventListener("dispose",y)}return o}class kv extends H{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Z(1),this.updateType=oe.OBJECT}setup(e){const{geometry:t}=e,n=t.morphAttributes.position!==void 0,r=t.hasAttribute("normal")&&t.morphAttributes.normal!==void 0,s=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,o=s!==void 0?s.length:0,{texture:a,stride:u,size:l}=Iv(t);n===!0&&Ke.mulAssign(this.morphBaseInfluence),r===!0&&en.mulAssign(this.morphBaseInfluence);const c=Me(l.width);St(o,({i:d})=>{const h=N(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?h.assign(Tt(this.mesh.morphTexture,qt(Me(d).add(1),Me(Vs))).r):h.assign(Se("morphTargetInfluences","float").element(d).toVar()),Re(h.notEqual(0),()=>{n===!0&&Ke.addAssign(Jc({bufferMap:a,influence:h,stride:u,width:c,depth:d,offset:Me(0)})),r===!0&&en.addAssign(Jc({bufferMap:a,influence:h,stride:u,width:c,depth:d,offset:Me(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 Gv=me(kv).setParameterLength(1);class ss extends H{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Vv extends ss{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class $v extends dp{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,r=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=r,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n=R().toVar("directDiffuse"),r=R().toVar("directSpecular"),s=R().toVar("indirectDiffuse"),o=R().toVar("indirectSpecular"),a={directDiffuse:n,directSpecular:r,indirectDiffuse:s,indirectSpecular:o};return{radiance:R().toVar("radiance"),irradiance:R().toVar("irradiance"),iblIrradiance:R().toVar("iblIrradiance"),ambientOcclusion:N(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 zv=me($v);class Wv extends ss{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const vr=new ce;class kp extends ts{static get type(){return"ViewportTextureNode"}constructor(e=Ir,t=null,n=null){let r=null;n===null?(r=new Rh,r.minFilter=sr,n=r):r=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=r,this.isOutputTextureNode=!0,this.updateBeforeType=oe.FRAME,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 r=t.clone();n.set(e,r)}return n.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget();n===null?t.getDrawingBufferSize(vr):vr.set(n.width,n.height);const r=this.getTextureForReference(n);(r.image.width!==vr.width||r.image.height!==vr.height)&&(r.image.width=vr.width,r.image.height=vr.height,r.needsUpdate=!0);const s=r.generateMipmaps;r.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(r),r.generateMipmaps=s}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Gp=me(kp,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let bi=null;class jv extends kp{static get type(){return"ViewportDepthTextureNode"}constructor(e=Ir,t=null){bi===null&&(bi=new Qt),super(e,t,bi)}getTextureForReference(){return bi}}const qv=me(jv).setParameterLength(0,2);class ct extends H{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===ct.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let r=null;if(t===ct.DEPTH_BASE)n!==null&&(r=zp().assign(n));else if(t===ct.DEPTH)e.isPerspectiveCamera?r=Hv($e.z,Qn,Zn):r=$s($e.z,Qn,Zn);else if(t===ct.LINEAR_DEPTH)if(n!==null)if(e.isPerspectiveCamera){const s=Vp(n,Qn,Zn);r=$s(s,Qn,Zn)}else r=n;else r=$s($e.z,Qn,Zn);return r}}ct.DEPTH_BASE="depthBase";ct.DEPTH="depth";ct.LINEAR_DEPTH="linearDepth";const $s=(i,e,t)=>i.add(e).div(e.sub(t)),Hv=(i,e,t)=>e.add(i).mul(t).div(t.sub(e).mul(i)),Vp=(i,e,t)=>e.mul(t).div(t.sub(e).mul(i).sub(t)),$p=(i,e,t)=>{e=e.max(1e-6).toVar();const n=gn(i.negate().div(e)),r=gn(t.div(e));return n.div(r)},zp=me(ct,ct.DEPTH_BASE),Wp=U(ct,ct.DEPTH),Xv=me(ct,ct.LINEAR_DEPTH).setParameterLength(0,1);qv();Wp.assign=i=>zp(i);class wt extends H{static get type(){return"ClippingNode"}constructor(e=wt.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:r}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===wt.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,r):this.scope===wt.HARDWARE?this.setupHardwareClipping(r,e):this.setupDefault(n,r)}setupAlphaToCoverage(e,t){return P(()=>{const n=N().toVar("distanceToPlane"),r=N().toVar("distanceToGradient"),s=N(1).toVar("clipOpacity"),o=t.length;if(this.hardwareClipping===!1&&o>0){const u=Dt(t).setGroup(Q);St(o,({i:l})=>{const c=u.element(l);n.assign($e.dot(c.xyz).negate().add(c.w)),r.assign(n.fwidth().div(2)),s.mulAssign(yn(r.negate(),r,n))})}const a=e.length;if(a>0){const u=Dt(e).setGroup(Q),l=N(1).toVar("intersectionClipOpacity");St(a,({i:c})=>{const d=u.element(c);n.assign($e.dot(d.xyz).negate().add(d.w)),r.assign(n.fwidth().div(2)),l.mulAssign(yn(r.negate(),r,n).oneMinus())}),s.mulAssign(l.oneMinus())}ve.a.mulAssign(s),ve.a.equal(0).discard()})()}setupDefault(e,t){return P(()=>{const n=t.length;if(this.hardwareClipping===!1&&n>0){const s=Dt(t).setGroup(Q);St(n,({i:o})=>{const a=s.element(o);$e.dot(a.xyz).greaterThan(a.w).discard()})}const r=e.length;if(r>0){const s=Dt(e).setGroup(Q),o=vl(!0).toVar("clipped");St(r,({i:a})=>{const u=s.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),P(()=>{const r=Dt(e).setGroup(Q),s=ni(t.getClipDistance());St(n,({i:o})=>{const a=r.element(o),u=$e.dot(a.xyz).sub(a.w).negate();s.element(o).assign(u)})})()}}wt.ALPHA_TO_COVERAGE="alphaToCoverage";wt.DEFAULT="default";wt.HARDWARE="hardware";const Kv=()=>new wt,Yv=()=>new wt(wt.ALPHA_TO_COVERAGE),Qv=()=>new wt(wt.HARDWARE),Zv=.05,ed=P(([i])=>Jt(ae(1e4,mt(ae(17,i.x).add(ae(.1,i.y)))).mul(pt(.1,yt(mt(ae(13,i.y).add(i.x))))))),td=P(([i])=>ed(j(ed(i.xy),i.z))),Jv=P(([i])=>{const e=Je(mn(rp(i.xyz)),mn(sp(i.xyz))),t=N(1).div(N(Zv).mul(e)).toVar("pixScale"),n=j(Xs(ar(gn(t))),Xs(Al(gn(t)))),r=j(td(ar(n.x.mul(i.xyz))),td(ar(n.y.mul(i.xyz)))),s=Jt(gn(t)),o=pt(ae(s.oneMinus(),r.x),ae(s,r.y)),a=Wr(s,s.oneMinus()),u=R(o.mul(o).div(ae(2,a).mul(at(1,a))),o.sub(ae(.5,a)).div(at(1,a)),at(1,at(1,o).mul(at(1,o)).div(ae(2,a).mul(at(1,a))))),l=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(u.x,u.y),u.z);return On(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class e0 extends _p{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 r;return n===!0?r=super.generate(e):r=e.generateConst(this.nodeType,new Oe(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const t0=(i=0)=>new e0(i),n0=P(([i])=>se(i.rgb.mul(i.a),i.a),{color:"vec4",return:"vec4"});class ze extends Hl{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.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,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{z('NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}_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(Co(t.slice(0,-4)),n.getCacheKey());return this.type+ei(e)}build(e){this.setup(e)}setupObserver(e){return new Gb(e)}setup(e){e.context.setupNormal=()=>Is(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();t.contextNode.isContextNode===!0?e.context={...e.context,...t.contextNode.getFlowContextData()}:G('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),this.contextNode!==null&&(this.contextNode.isContextNode===!0?e.context={...e.context,...this.contextNode.getFlowContextData()}:G('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const r=Is(this.setupVertex(e),"VERTEX"),s=this.vertexNode||r;e.stack.outputNode=s,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=se(u,ve.a).max(0);o=this.setupOutput(e,l),Os.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&&Os.assign(o),o=d,h!==null&&(o=d.merge(h))):h!==null&&(o=h)}}else{let u=this.fragmentNode;u.isOutputStructNode!==!0&&(u=se(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 r=null;if(t.length>0||n.length>0){const s=e.renderer.currentSamples;this.alphaToCoverage&&s>1?r=Yv():e.stack.addToStack(Kv())}return r}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(Qv()),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let r=this.depthNode;if(r===null){const s=t.getMRT();s&&s.has("depth")?r=s.get("depth"):t.logarithmicDepthBuffer===!0&&(n.isPerspectiveCamera?r=$p($e.z,Qn,Zn):r=$s($e.z,Qn,Zn))}r!==null&&Wp.assign(r).toStack()}setupPositionView(){return ri.mul(Ke).xyz}setupModelViewProjection(){return Gs.mul($e)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Sv}setupPosition(e){const{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&Gv(t).toStack(),t.isSkinnedMesh===!0&&Lv(t).toStack(),this.displacementMap){const r=En("displacementMap","texture"),s=En("displacementScale","float"),o=En("displacementBias","float");Ke.addAssign(en.normalize().mul(r.x.mul(s).add(o)))}return t.isBatchedMesh&&Dv(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&Pv(t).toStack(),this.positionNode!==null&&Ke.assign(Is(this.positionNode,"POSITION","vec3")),Ke}setupDiffuseColor(e){const{object:t,geometry:n}=e;this.maskNode!==null&&vl(this.maskNode).not().discard();let r=this.colorNode?se(this.colorNode):HT;this.vertexColors===!0&&n.hasAttribute("color")&&(r=r.mul(t0())),t.instanceColor&&(r=po("vec3","vInstanceColor").mul(r)),t.isBatchedMesh&&t._colorsTexture&&(r=po("vec3","vBatchColor").mul(r)),ve.assign(r);const s=this.opacityNode?N(this.opacityNode):Op;ve.a.assign(ve.a.mul(s));let o=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(o=this.alphaTestNode!==null?N(this.alphaTestNode):qT,this.alphaToCoverage===!0?(ve.a=yn(o,o.add(ip(ve.a)),ve.a),ve.a.lessThanEqual(0).discard()):ve.a.lessThanEqual(o).discard()),this.alphaHash===!0&&ve.a.lessThan(Jv(Ke)).discard(),e.isOpaque()&&ve.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?R(0):ve.rgb}setupNormal(){return this.normalNode?R(this.normalNode):ev}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?En("envMap","cubeTexture"):En("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Wv(Ip)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const r=this.setupLightMap(e);r&&r.isLightingNode&&t.push(r);let s=this.aoNode;s===null&&e.material.aoMap&&(s=vv),e.context.getAO&&(s=e.context.getAO(s,e)),s&&t.push(new Vv(s));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:r,emissiveNode:s}=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=zv(a,l,n,r)}else n!==null&&(u=R(r!==null?Ne(u,n,r):n));return(s&&s.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(Dc.assign(R(s||KT)),u=u.add(Dc)),u}setupFog(e,t){const n=e.fogNode;return n&&(Os.assign(t),t=se(n.toVar())),t}setupPremultipliedAlpha(e,t){return n0(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 r=e[n];this[n]===void 0&&(this[n]=r,r&&r.clone&&(this[n]=r.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=Hl.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:s,childNode:o}of this._getNodeChildren())n.inputNodes[s]=o.toJSON(e).uuid;function r(s){const o=[];for(const a in s){const u=s[a];delete u.metadata,o.push(u)}return o}if(t){const s=r(e.textures),o=r(e.images),a=r(e.nodes);s.length>0&&(n.textures=s),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.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 r0=new vh;class s0 extends ze{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(r0),this.setValues(e)}}const i0=new Am;class o0 extends ze{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(i0),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?N(this.offsetNode):_v,t=this.dashScaleNode?N(this.dashScaleNode):mv,n=this.dashSizeNode?N(this.dashSizeNode):yv,r=this.gapSizeNode?N(this.gapSizeNode):bv;ua.assign(n),Fc.assign(r);const s=bn(In("lineDistance").mul(t));(e?s.add(e):s).mod(ua.add(Fc)).greaterThan(ua).discard()}}const a0=new Rm;class u0 extends ze{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(a0),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?N(this.opacityNode):Op;ve.assign(Pl(se(GT(pe),e),Ju))}}const jp=P(([i=Sp])=>{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 j(e,t)});class qp extends sy{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,r=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 s=new uf(5,5,5),o=jp(Sp),a=new ze;a.colorNode=Pe(t,o,0),a.side=ht,a.blending=$r;const u=new Ut(s,a),l=new So;l.add(u),t.minFilter===sr&&(t.minFilter=Ot);const c=new iy(1,10,this),d=e.getMRT();return e.setMRT(null),c.update(e,l),e.setMRT(d),t.minFilter=n,t.currentGenerateMipmaps=r,u.geometry.dispose(),u.material.dispose(),this}}const zs=new WeakMap;class l0 extends qe{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=ut(null);const t=new cl;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=oe.RENDER}updateBefore(e){const{renderer:t,material:n}=e,r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const s=r.isTextureNode?r.value:n[r.property];if(s&&s.isTexture){const o=s.mapping;if(o===rl||o===sl){if(zs.has(s)){const a=zs.get(s);nd(a,s.mapping),this._cubeTexture=a}else{const a=s.image;if(c0(a)){const u=new qp(a.height);u.fromEquirectangularTexture(t,s),nd(u.texture,s.mapping),this._cubeTexture=u.texture,zs.set(s,u.texture),s.addEventListener("dispose",Hp)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function c0(i){return i==null?!1:i.height>0}function Hp(i){const e=i.target;e.removeEventListener("dispose",Hp);const t=zs.get(e);t!==void 0&&(zs.delete(e),t.dispose())}function nd(i,e){e===rl?i.mapping=uo:e===sl&&(i.mapping=lo)}const Xp=me(l0).setParameterLength(1);class Ol extends ss{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Xp(this.envNode)}}class d0 extends ss{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=N(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Fo{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Kp extends Fo{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,r=e.irradianceLightMap;n.indirectDiffuse.assign(se(0)),r?n.indirectDiffuse.addAssign(r):n.indirectDiffuse.addAssign(se(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(ve.rgb)}finish(e){const{material:t,context:n}=e,r=n.outgoingLight,s=e.context.environment;if(s)switch(t.combine){case ny:r.rgb.assign(Ne(r.rgb,r.rgb.mul(s.rgb),Qi.mul(da)));break;case ty:r.rgb.assign(Ne(r.rgb,s.rgb,Qi.mul(da)));break;case ey:r.rgb.addAssign(s.rgb.mul(Qi.mul(da)));break;default:z("BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const h0=new An;class f0 extends ze{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(h0),this.setValues(e)}setupNormal(){return si(Ks)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Ol(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new d0(Ip)),t}setupOutgoingLight(){return ve.rgb}setupLightingModel(){return new Kp}}const Ys=P(({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))}),Hr=P(i=>i.diffuseColor.mul(1/Math.PI)),p0=()=>N(.25),g0=P(({dotNH:i})=>Lu.mul(N(.5)).add(1).mul(N(1/Math.PI)).mul(i.pow(Lu))),m0=P(({lightDirection:i})=>{const e=i.add(Ce).normalize(),t=pe.dot(e).clamp(),n=Ce.dot(e).clamp(),r=Ys({f0:dr,f90:1,dotVH:n}),s=p0(),o=g0({dotNH:t});return r.mul(s).mul(o)});class Yp extends Kp{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const s=pe.dot(e).clamp().mul(t);n.directDiffuse.addAssign(s.mul(Hr({diffuseColor:ve.rgb}))),this.specular===!0&&n.directSpecular.addAssign(s.mul(m0({lightDirection:e})).mul(Qi))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(Hr({diffuseColor:ve}))),r.indirectDiffuse.mulAssign(t)}}const y0=new bh;class b0 extends ze{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(y0),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Ol(t):null}setupLightingModel(){return new Yp(!1)}}const _0=new Tm;class x0 extends ze{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(_0),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Ol(t):null}setupLightingModel(){return new Yp}setupVariants(){const e=(this.shininessNode?N(this.shininessNode):XT).max(1e-4);Lu.assign(e);const t=this.specularNode||YT;dr.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const T0=P(i=>{if(i.geometry.hasAttribute("normal")===!1)return N(0);const e=Ks.dFdx().abs().max(Ks.dFdy().abs());return e.x.max(e.y).max(e.z)}),Qp=P(i=>{const{roughness:e}=i,t=T0();let n=e.max(.0525);return n=n.add(t),n=n.min(1),n}),v0=P(({alpha:i,dotNL:e,dotNV:t})=>{const n=i.pow2(),r=e.mul(n.add(n.oneMinus().mul(t.pow2())).sqrt()),s=t.mul(n.add(n.oneMinus().mul(e.pow2())).sqrt());return Zt(.5,r.add(s).max(Yf))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),S0=P(({alphaT:i,alphaB:e,dotTV:t,dotBV:n,dotTL:r,dotBL:s,dotNV:o,dotNL:a})=>{const u=a.mul(R(i.mul(t),e.mul(n),o).length()),l=o.mul(R(i.mul(r),e.mul(s),a).length());return Zt(.5,u.add(l))}).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"}]}),N0=P(({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"}]}),R0=N(1/Math.PI),w0=P(({alphaT:i,alphaB:e,dotNH:t,dotTH:n,dotBH:r})=>{const s=i.mul(e),o=R(e.mul(n),i.mul(r),s.mul(t)),a=o.dot(o),u=s.div(a);return R0.mul(s.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"}]}),Zp=P(({lightDirection:i,f0:e,f90:t,roughness:n,f:r,normalView:s=pe,USE_IRIDESCENCE:o,USE_ANISOTROPY:a})=>{const u=n.pow2(),l=i.add(Ce).normalize(),c=s.dot(i).clamp(),d=s.dot(Ce).clamp(),h=s.dot(l).clamp(),p=Ce.dot(l).clamp();let f=Ys({f0:e,f90:t,dotVH:p}),g,m;if(Bc(o)&&(f=Nl.mix(f,r)),Bc(a)){const y=Hi.dot(i),_=Hi.dot(Ce),T=Hi.dot(l),A=Or.dot(i),B=Or.dot(Ce),S=Or.dot(l);g=S0({alphaT:Fu,alphaB:u,dotTV:_,dotBV:B,dotTL:y,dotBL:A,dotNV:d,dotNL:c}),m=w0({alphaT:Fu,alphaB:u,dotNH:h,dotTH:T,dotBH:S})}else g=v0({alpha:u,dotNL:c,dotNV:d}),m=N0({alpha:u,dotNH:h});return f.mul(g).mul(m)}),A0=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 zt=null;const mo=P(({roughness:i,dotNV:e})=>{zt===null&&(zt=new nf(A0,16,16,hn,it),zt.name="DFG_LUT",zt.minFilter=Ot,zt.magFilter=Ot,zt.wrapS=js,zt.wrapT=js,zt.generateMipmaps=!1,zt.needsUpdate=!0);const t=j(i,e);return Pe(zt,t).rg}),E0=P(({lightDirection:i,f0:e,f90:t,roughness:n,f:r,USE_IRIDESCENCE:s,USE_ANISOTROPY:o})=>{const a=Zp({lightDirection:i,f0:e,f90:t,roughness:n,f:r,USE_IRIDESCENCE:s,USE_ANISOTROPY:o}),u=pe.dot(i).clamp(),l=pe.dot(Ce).clamp(),c=mo({roughness:n,dotNV:l}),d=mo({roughness:n,dotNV:u}),h=e.mul(c.x).add(t.mul(c.y)),p=e.mul(d.x).add(t.mul(d.y)),f=c.x.add(c.y),g=d.x.add(d.y),m=N(1).sub(f),y=N(1).sub(g),_=e.add(e.oneMinus().mul(.047619)),T=h.mul(p).mul(_).div(N(1).sub(m.mul(y).mul(_).mul(_)).add(Yf)),A=m.mul(y),B=T.mul(A);return a.add(B)}),Jp=P(i=>{const{dotNV:e,specularColor:t,specularF90:n,roughness:r}=i,s=mo({dotNV:e,roughness:r});return t.mul(s.x).add(n.mul(s.y))}),rd=P(({f:i,f90:e,dotVH:t})=>{const n=t.oneMinus().saturate(),r=n.mul(n),s=n.mul(r,r).clamp(0,.9999);return i.sub(R(e).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),C0=P(({roughness:i,dotNH:e})=>{const t=i.pow2(),n=N(1).div(t),s=e.pow2().oneMinus().max(.0078125);return N(2).add(n).mul(s.pow(n.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),M0=P(({dotNV:i,dotNL:e})=>N(1).div(N(4).mul(e.add(i).sub(e.mul(i))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),P0=P(({lightDirection:i})=>{const e=i.add(Ce).normalize(),t=pe.dot(i).clamp(),n=pe.dot(Ce).clamp(),r=pe.dot(e).clamp(),s=C0({roughness:Yn,dotNH:r}),o=M0({dotNV:n,dotNL:t});return xt.mul(s).mul(o)}),B0=P(({N:i,V:e,roughness:t})=>{const s=.0078125,o=i.dot(e).saturate(),a=j(t,o.oneMinus().sqrt());return a.assign(a.mul(.984375).add(s)),a}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),D0=P(({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"}]}),_i=P(({v1:i,v2:e})=>{const t=i.dot(e),n=t.abs().toVar(),r=n.mul(.0145206).add(.4965155).mul(n).add(.8543985).toVar(),s=n.add(4.1616724).mul(n).add(3.417594).toVar(),o=r.div(s),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"}]}),sd=P(({N:i,V:e,P:t,mInv:n,p0:r,p1:s,p2:o,p3:a})=>{const u=s.sub(r).toVar(),l=a.sub(r).toVar(),c=u.cross(l),d=R().toVar();return Re(c.dot(t.sub(r)).greaterThanEqual(0),()=>{const h=e.sub(i.mul(e.dot(i))).normalize(),p=i.cross(h).negate(),f=n.mul(nt(h,p,i).transpose()).toVar(),g=f.mul(r.sub(t)).normalize().toVar(),m=f.mul(s.sub(t)).normalize().toVar(),y=f.mul(o.sub(t)).normalize().toVar(),_=f.mul(a.sub(t)).normalize().toVar(),T=R(0).toVar();T.addAssign(_i({v1:g,v2:m})),T.addAssign(_i({v1:m,v2:y})),T.addAssign(_i({v1:y,v2:_})),T.addAssign(_i({v1:_,v2:g})),d.assign(R(D0({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"}]}),Lo=1/6,eg=i=>ae(Lo,ae(i,ae(i,i.negate().add(3)).sub(3)).add(1)),Gu=i=>ae(Lo,ae(i,ae(i,ae(3,i).sub(6))).add(4)),tg=i=>ae(Lo,ae(i,ae(i,ae(-3,i).add(3)).add(3)).add(1)),Vu=i=>ae(Lo,Bo(i,3)),id=i=>eg(i).add(Gu(i)),od=i=>tg(i).add(Vu(i)),ad=i=>pt(-1,Gu(i).div(eg(i).add(Gu(i)))),ud=i=>pt(1,Vu(i).div(tg(i).add(Vu(i)))),ld=(i,e,t)=>{const n=i.uvNode,r=ae(n,e.zw).add(.5),s=ar(r),o=Jt(r),a=id(o.x),u=od(o.x),l=ad(o.x),c=ud(o.x),d=ad(o.y),h=ud(o.y),p=j(s.x.add(l),s.y.add(d)).sub(.5).mul(e.xy),f=j(s.x.add(c),s.y.add(d)).sub(.5).mul(e.xy),g=j(s.x.add(l),s.y.add(h)).sub(.5).mul(e.xy),m=j(s.x.add(c),s.y.add(h)).sub(.5).mul(e.xy),y=id(o.y).mul(pt(a.mul(i.sample(p).level(t)),u.mul(i.sample(f).level(t)))),_=od(o.y).mul(pt(a.mul(i.sample(g).level(t)),u.mul(i.sample(m).level(t))));return y.add(_)},F0=P(([i,e])=>{const t=j(i.size(Me(e))),n=j(i.size(Me(e.add(1)))),r=Zt(1,t),s=Zt(1,n),o=ld(i,se(r,t),ar(e)),a=ld(i,se(s,n),Al(e));return Jt(e).mix(o,a)}),cd=P(([i,e,t,n,r])=>{const s=R(cp(e.negate(),Lt(i),Zt(1,n))),o=R(mn(r[0].xyz),mn(r[1].xyz),mn(r[2].xyz));return Lt(s).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"}]}),L0=P(([i,e])=>i.mul(On(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),U0=Gp(),O0=Gp(),dd=P(([i,e,t],{material:n})=>{const s=(n.side===ht?U0:O0).sample(i),o=gn(Ou.x).mul(L0(e,t));return F0(s,o)}),hd=P(([i,e,t])=>(Re(t.notEqual(0),()=>{const n=Zf(e).negate().div(t);return Qf(n.negate().mul(i))}),R(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),I0=P(([i,e,t,n,r,s,o,a,u,l,c,d,h,p,f])=>{let g,m;if(f){g=se().toVar(),m=R().toVar();const B=c.sub(1).mul(f.mul(.025)),S=R(c.sub(B),c,c.add(B));St({start:0,end:3},({i:v})=>{const E=S.element(v),D=cd(i,e,d,E,a),O=o.add(D),Y=l.mul(u.mul(se(O,1))),ee=j(Y.xy.div(Y.w)).toVar();ee.addAssign(1),ee.divAssign(2),ee.assign(j(ee.x,ee.y.oneMinus()));const te=dd(ee,t,E);g.element(v).assign(te.element(v)),g.a.addAssign(te.a),m.element(v).assign(n.element(v).mul(hd(mn(D),h,p).element(v)))}),g.a.divAssign(3)}else{const B=cd(i,e,d,c,a),S=o.add(B),v=l.mul(u.mul(se(S,1))),E=j(v.xy.div(v.w)).toVar();E.addAssign(1),E.divAssign(2),E.assign(j(E.x,E.y.oneMinus())),g=dd(E,t,c),m=n.mul(hd(mn(B),h,p))}const y=m.rgb.mul(g.rgb),_=i.dot(e).clamp(),T=R(Jp({dotNV:_,specularColor:r,specularF90:s,roughness:t})),A=m.r.add(m.g,m.b).div(3);return se(T.oneMinus().mul(y),g.a.oneMinus().mul(A).oneMinus())}),k0=nt(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),G0=i=>{const e=i.sqrt();return R(1).add(e).div(R(1).sub(e))},fd=(i,e)=>i.sub(e).div(i.add(e)).pow2(),V0=(i,e)=>{const t=i.mul(2*Math.PI*1e-9),n=R(54856e-17,44201e-17,52481e-17),r=R(1681e3,1795300,2208400),s=R(43278e5,93046e5,66121e5),o=N(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(s.mul(2*Math.PI).sqrt()).mul(r.mul(t).add(e).cos()).mul(t.pow2().negate().mul(s).exp());return a=R(a.x.add(o),a.y,a.z).div(10685e-11),k0.mul(a)},pd=P(({outsideIOR:i,eta2:e,cosTheta1:t,thinFilmThickness:n,baseF0:r})=>{const s=Ne(i,e,yn(0,.03,n)),a=i.div(s).pow2().mul(t.pow2().oneMinus()).oneMinus();Re(a.lessThan(0),()=>R(1));const u=a.sqrt(),l=fd(s,i),c=Ys({f0:l,f90:1,dotVH:t}),d=c.oneMinus(),h=s.lessThan(i).select(Math.PI,0),p=N(Math.PI).sub(h),f=G0(r.clamp(0,.9999)),g=fd(f,s.toVec3()),m=Ys({f0:g,f90:1,dotVH:u}),y=R(f.x.lessThan(s).select(Math.PI,0),f.y.lessThan(s).select(Math.PI,0),f.z.lessThan(s).select(Math.PI,0)),_=s.mul(n,u,2),T=R(p).add(y),A=c.mul(m).clamp(1e-5,.9999),B=A.sqrt(),S=d.pow2().mul(m).div(R(1).sub(A)),E=c.add(S).toVar(),D=S.sub(d).toVar();return St({start:1,end:2,condition:"<=",name:"m"},({m:O})=>{D.mulAssign(B);const Y=V0(N(O).mul(_),N(O).mul(T)).mul(2);E.addAssign(D.mul(Y))}),E.max(R(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"}]}),gs=P(({normal:i,viewDir:e,roughness:t})=>{const n=i.dot(e).saturate(),r=t.mul(t),s=t.add(.1).reciprocal(),o=N(-1.9362).add(t.mul(1.0678)).add(r.mul(.4573)).sub(s.mul(.8469)),a=N(-.6014).add(t.mul(.5538)).sub(r.mul(.467)).sub(s.mul(.1255));return o.mul(n).add(a).exp().saturate()}),fa=R(.04),pa=N(1);class ng extends Fo{constructor(e=!1,t=!1,n=!1,r=!1,s=!1,o=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=r,this.transmission=s,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=R().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=R().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=R().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=R().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=R().toVar("sheenSpecularIndirect")),this.iridescence===!0){const t=pe.dot(Ce).clamp(),n=pd({outsideIOR:N(1),eta2:Bu,cosTheta1:t,thinFilmThickness:Du,baseF0:dr}),r=pd({outsideIOR:N(1),eta2:Bu,cosTheta1:t,thinFilmThickness:Du,baseF0:ve.rgb});this.iridescenceFresnel=Ne(n,r,Mn),this.iridescenceF0Dielectric=rd({f:n,f90:1,dotVH:t}),this.iridescenceF0Metallic=rd({f:r,f90:1,dotVH:t}),this.iridescenceF0=Ne(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Mn)}if(this.transmission===!0){const t=qr,n=pT.sub(qr).normalize(),r=rs,s=e.context;s.backdrop=I0(r,n,cn,Cr,Br,Us,t,pr,_n,Gs,Xi,zf,jf,Wf,this.dispersion?qf:null),s.backdropAlpha=Uu,ve.a.mulAssign(Ne(1,s.backdrop.a,Uu))}super.start(e)}computeMultiscattering(e,t,n,r,s=null){const o=pe.dot(Ce).clamp(),a=mo({roughness:cn,dotNV:o}),u=s?Nl.mix(r,s):r,l=u.mul(a.x).add(n.mul(a.y)),d=a.x.add(a.y).oneMinus(),h=u.add(u.oneMinus().mul(.047619)),p=l.mul(h).div(d.mul(h).oneMinus());e.addAssign(l),t.addAssign(p.mul(d))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const s=pe.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(s.mul(P0({lightDirection:e})));const o=gs({normal:pe,viewDir:Ce,roughness:Yn}),a=gs({normal:pe,viewDir:e,roughness:Yn}),u=xt.r.max(xt.g).max(xt.b).mul(o.max(a)).oneMinus();s.mulAssign(u)}if(this.clearcoat===!0){const a=Dr.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(a.mul(Zp({lightDirection:e,f0:fa,f90:pa,roughness:go,normalView:Dr})))}n.directDiffuse.addAssign(s.mul(Hr({diffuseColor:Cr}))),n.directSpecular.addAssign(s.mul(E0({lightDirection:e,f0:Br,f90:1,roughness:cn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:r,reflectedLight:s,ltc_1:o,ltc_2:a}){const u=t.add(n).sub(r),l=t.sub(n).sub(r),c=t.sub(n).add(r),d=t.add(n).add(r),h=pe,p=Ce,f=$e.toVar(),g=B0({N:h,V:p,roughness:cn}),m=o.sample(g).toVar(),y=a.sample(g).toVar(),_=nt(R(m.x,0,m.y),R(0,1,0),R(m.z,0,m.w)).toVar(),T=Br.mul(y.x).add(Br.oneMinus().mul(y.y)).toVar();s.directSpecular.addAssign(e.mul(T).mul(sd({N:h,V:p,P:f,mInv:_,p0:u,p1:l,p2:c,p3:d}))),s.directDiffuse.addAssign(e.mul(Cr).mul(sd({N:h,V:p,P:f,mInv:nt(1,0,0,0,1,0,0,0,1),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,r=t.mul(Hr({diffuseColor:Cr})).toVar();if(this.sheen===!0){const s=gs({normal:pe,viewDir:Ce,roughness:Yn}),o=xt.r.max(xt.g).max(xt.b).mul(s).oneMinus();r.mulAssign(o)}n.indirectDiffuse.addAssign(r)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:r}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(n.mul(xt,gs({normal:pe,viewDir:Ce,roughness:Yn}))),this.clearcoat===!0){const m=Dr.dot(Ce).clamp(),y=Jp({dotNV:m,specularColor:fa,specularF90:pa,roughness:go});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(y))}const s=R().toVar("singleScatteringDielectric"),o=R().toVar("multiScatteringDielectric"),a=R().toVar("singleScatteringMetallic"),u=R().toVar("multiScatteringMetallic");this.computeMultiscattering(s,o,Us,dr,this.iridescenceF0Dielectric),this.computeMultiscattering(a,u,Us,ve.rgb,this.iridescenceF0Metallic);const l=Ne(s,a,Mn),c=Ne(o,u,Mn),d=s.add(o),h=Cr.mul(d.oneMinus()),p=n.mul(1/Math.PI),f=t.mul(l).add(c.mul(p)).toVar(),g=h.mul(p).toVar();if(this.sheen===!0){const m=gs({normal:pe,viewDir:Ce,roughness:Yn}),y=xt.r.max(xt.g).max(xt.b).mul(m).oneMinus();f.mulAssign(y),g.mulAssign(y)}r.indirectSpecular.addAssign(f),r.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,s=pe.dot(Ce).clamp().add(t),o=cn.mul(-16).oneMinus().negate().exp2(),a=t.sub(s.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=Dr.dot(Ce).clamp(),r=Ys({dotVH:n,f0:fa,f90:pa}),s=t.mul(Pu.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Pu));t.assign(s)}if(this.sheen===!0){const n=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(n)}}}const gd=N(1),$u=N(-2),xi=N(.8),ga=N(-1),Ti=N(.4),ma=N(2),vi=N(.305),ya=N(3),md=N(.21),$0=N(4),yd=N(4),z0=N(16),W0=P(([i])=>{const e=R(yt(i)).toVar(),t=N(-1).toVar();return Re(e.x.greaterThan(e.z),()=>{Re(e.x.greaterThan(e.y),()=>{t.assign(lt(i.x.greaterThan(0),0,3))}).Else(()=>{t.assign(lt(i.y.greaterThan(0),1,4))})}).Else(()=>{Re(e.z.greaterThan(e.y),()=>{t.assign(lt(i.z.greaterThan(0),2,5))}).Else(()=>{t.assign(lt(i.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),j0=P(([i,e])=>{const t=j().toVar();return Re(e.equal(0),()=>{t.assign(j(i.z,i.y).div(yt(i.x)))}).ElseIf(e.equal(1),()=>{t.assign(j(i.x.negate(),i.z.negate()).div(yt(i.y)))}).ElseIf(e.equal(2),()=>{t.assign(j(i.x.negate(),i.y).div(yt(i.z)))}).ElseIf(e.equal(3),()=>{t.assign(j(i.z.negate(),i.y).div(yt(i.x)))}).ElseIf(e.equal(4),()=>{t.assign(j(i.x.negate(),i.z).div(yt(i.y)))}).Else(()=>{t.assign(j(i.x,i.y).div(yt(i.z)))}),ae(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),q0=P(([i])=>{const e=N(0).toVar();return Re(i.greaterThanEqual(xi),()=>{e.assign(gd.sub(i).mul(ga.sub($u)).div(gd.sub(xi)).add($u))}).ElseIf(i.greaterThanEqual(Ti),()=>{e.assign(xi.sub(i).mul(ma.sub(ga)).div(xi.sub(Ti)).add(ga))}).ElseIf(i.greaterThanEqual(vi),()=>{e.assign(Ti.sub(i).mul(ya.sub(ma)).div(Ti.sub(vi)).add(ma))}).ElseIf(i.greaterThanEqual(md),()=>{e.assign(vi.sub(i).mul($0.sub(ya)).div(vi.sub(md)).add(ya))}).Else(()=>{e.assign(N(-2).mul(gn(ae(1.16,i))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),H0=P(([i,e])=>{const t=i.toVar();t.assign(ae(2,t).sub(1));const n=R(t,1).toVar();return Re(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"}]}),X0=P(([i,e,t,n,r,s])=>{const o=N(t),a=R(e),u=On(q0(o),$u,s),l=Jt(u),c=ar(u),d=R(Qs(i,a,c,n,r,s)).toVar();return Re(l.notEqual(0),()=>{const h=R(Qs(i,a,c.add(1),n,r,s)).toVar();d.assign(Ne(d,h,l))}),d}),Qs=P(([i,e,t,n,r,s])=>{const o=N(t).toVar(),a=R(e),u=N(W0(a)).toVar(),l=N(Je(yd.sub(o),0)).toVar();o.assign(Je(o,yd));const c=N(Xs(o)).toVar(),d=j(j0(a,u).mul(c.sub(2)).add(1)).toVar();return Re(u.greaterThan(2),()=>{d.y.addAssign(c),u.subAssign(3)}),d.x.addAssign(u.mul(c)),d.x.addAssign(l.mul(ae(3,z0))),d.y.addAssign(ae(4,Xs(s).sub(c))),d.x.mulAssign(n),d.y.mulAssign(r),i.sample(d).grad(j(),j())}),ba=P(({envMap:i,mipInt:e,outputDirection:t,theta:n,axis:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const u=Ht(n),l=t.mul(u).add(r.cross(t).mul(mt(n))).add(r.mul(r.dot(t).mul(u.oneMinus())));return Qs(i,l,e,s,o,a)}),K0=P(({n:i,latitudinal:e,poleAxis:t,outputDirection:n,weights:r,samples:s,dTheta:o,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d})=>{const h=R(lt(e,t,fr(t,n))).toVar();Re(h.equal(R(0)),()=>{h.assign(R(n.z,0,n.x.negate()))}),h.assign(Lt(h));const p=R().toVar();return p.addAssign(r.element(0).mul(ba({theta:0,axis:h,outputDirection:n,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d}))),St({start:Me(1),end:i},({i:f})=>{Re(f.greaterThanEqual(s),()=>{Ov()});const g=N(o.mul(N(f))).toVar();p.addAssign(r.element(f).mul(ba({theta:g.mul(-1),axis:h,outputDirection:n,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d}))),p.addAssign(r.element(f).mul(ba({theta:g,axis:h,outputDirection:n,mipInt:a,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:d})))}),se(p,1)}),Y0=P(([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)))),N(e).mul(23283064365386963e-26)}),Q0=P(([i,e])=>j(N(i).div(N(e)),Y0(i))),Z0=P(([i,e,t])=>{const n=R(e).toVar(),r=N(t),s=r.mul(r).toVar(),o=Lt(R(s.mul(n.x),s.mul(n.y),n.z)).toVar(),a=o.x.mul(o.x).add(o.y.mul(o.y)),u=lt(a.greaterThan(0),R(o.y.negate(),o.x,0).div(fn(a)),R(1,0,0)).toVar(),l=fr(o,u).toVar(),c=fn(i.x),d=ae(2,3.14159265359).mul(i.y),h=c.mul(Ht(d)).toVar(),p=c.mul(mt(d)).toVar(),f=ae(.5,o.z.add(1));p.assign(f.oneMinus().mul(fn(h.mul(h).oneMinus())).add(f.mul(p)));const g=u.mul(h).add(l.mul(p)).add(o.mul(fn(Je(0,h.mul(h).add(p.mul(p)).oneMinus()))));return Lt(R(s.mul(g.x),s.mul(g.y),Je(0,g.z)))}),J0=P(({roughness:i,mipInt:e,envMap:t,N_immutable:n,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const u=R(n).toVar(),l=R(0).toVar(),c=N(0).toVar();return Re(i.lessThan(.001),()=>{l.assign(Qs(t,u,e,s,o,a))}).Else(()=>{const d=lt(yt(u.z).lessThan(.999),R(0,0,1),R(1,0,0)),h=Lt(fr(d,u)).toVar(),p=fr(u,h).toVar();St({start:de(0),end:r},({i:f})=>{const g=Q0(f,r),m=Z0(g,R(0,0,1),i),y=Lt(h.mul(m.x).add(p.mul(m.y)).add(u.mul(m.z))),_=Lt(y.mul(hr(u,y).mul(2)).sub(u)),T=Je(hr(u,_),0);Re(T.greaterThan(0),()=>{const A=Qs(t,_,e,s,o,a);l.addAssign(A.mul(T)),c.addAssign(T)})}),Re(c.greaterThan(0),()=>{l.assign(l.div(c))})}),se(l,1)}),Pn=4,bd=[.125,.215,.35,.446,.526,.582],Jn=20,eS=512,ms=new nl(-1,1,1,-1,0,1),tS=new Ws(90,1),_d=new Ct;let _a=null,xa=0,Ta=0;const nS=new I,yo=new WeakMap,rS=[3,1,5,0,4,2],va=H0(es(),In("faceIndex")).normalize(),Uo=R(va.x,va.y,va.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,r=100,s={}){const{size:o=256,position:a=nS,renderTarget:u=null}=s;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 s.renderTarget=c,this.fromSceneAsync(e,t,n,r,s),c}_a=this._renderer.getRenderTarget(),xa=this._renderer.getActiveCubeFace(),Ta=this._renderer.getActiveMipmapLevel();const l=u||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,n,r,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,r=100,s={}){return Ge('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,r,s)}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 Ge('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 Ge('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Td(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=vd(),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===uo||e.mapping===lo?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(_a,xa,Ta),e.scissorTest=!1,Sr(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),_a=this._renderer.getRenderTarget(),xa=this._renderer.getActiveCubeFace(),Ta=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 xd(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=xd(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=iS(t)),this._blurMaterial=oS(t,e.width,e.height),this._ggxMaterial=aS(t,e.width,e.height)}}async _compileMaterial(e){const t=new Ut(new Zs,e);await this._renderer.compile(t,ms)}_sceneToCubeUV(e,t,n,r,s){const o=tS;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(_d),l.autoClear=!1,this._backgroundBox===null&&(this._backgroundBox=new Ut(new uf,new An({name:"PMREM.Background",side:ht,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,h=d.material;let p=!1;const f=e.background;f?f.isColor&&(h.color.copy(f),e.background=null,p=!0):(h.color.copy(_d),p=!0),l.setRenderTarget(r),l.clear(),p&&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(s.x,s.y,s.z),o.lookAt(s.x+u[g],s.y,s.z)):m===1?(o.up.set(0,0,a[g]),o.position.set(s.x,s.y,s.z),o.lookAt(s.x,s.y+u[g],s.z)):(o.up.set(0,a[g],0),o.position.set(s.x,s.y,s.z),o.lookAt(s.x,s.y,s.z+u[g]));const y=this._cubeSize;Sr(r,m*y,g>2?y:0,y,y),l.render(e,o)}l.autoClear=c,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===uo||e.mapping===lo;r?this._cubemapMaterial===null&&(this._cubemapMaterial=Td(e)):this._equirectMaterial===null&&(this._equirectMaterial=vd(e));const s=r?this._cubemapMaterial:this._equirectMaterial;s.fragmentNode.value=e;const o=this._lodMeshes[0];o.material=s;const a=this._cubeSize;Sr(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(o,ms)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodMeshes.length;for(let s=1;s<r;s++)this._applyGGXFilter(e,s-1,s);t.autoClear=n}_applyGGXFilter(e,t,n){const r=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const u=yo.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,p=d*h,{_lodMax:f}=this,g=this._sizeLods[n],m=3*g*(n>f-Pn?n-f+Pn:0),y=4*(this._cubeSize-g);e.texture.frame=(e.texture.frame||0)+1,u.envMap.value=e.texture,u.roughness.value=p,u.mipInt.value=f-t,Sr(s,m,y,3*g,2*g),r.setRenderTarget(s),r.render(a,ms),s.texture.frame=(s.texture.frame||0)+1,u.envMap.value=s.texture,u.roughness.value=0,u.mipInt.value=f-n,Sr(e,m,y,3*g,2*g),r.setRenderTarget(e),r.render(a,ms)}_blur(e,t,n,r,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,r,"latitudinal",s),this._halfBlur(o,e,n,n,r,"longitudinal",s)}_halfBlur(e,t,n,r,s,o,a){const u=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&G("blur direction must be either latitudinal or longitudinal!");const c=3,d=this._lodMeshes[r];d.material=l;const h=yo.get(l),p=this._sizeLods[n]-1,f=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*Jn-1),g=s/f,m=isFinite(s)?1+Math.floor(c*g):Jn;m>Jn&&z(`sigmaRadians, ${s}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Jn}`);const y=[];let _=0;for(let v=0;v<Jn;++v){const E=v/g,D=Math.exp(-E*E/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=f,h.mipInt.value=T-n;const A=this._sizeLods[r],B=3*A*(r>T-Pn?r-T+Pn:0),S=4*(this._cubeSize-A);Sr(t,B,S,3*A,2*A),u.setRenderTarget(t),u.render(d,ms)}}function iS(i){const e=[],t=[],n=[];let r=i;const s=i-Pn+1+bd.length;for(let o=0;o<s;o++){const a=Math.pow(2,r);e.push(a);let u=1/a;o>i-Pn?u=bd[o-i+Pn-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],p=6,f=6,g=3,m=2,y=1,_=new Float32Array(g*f*p),T=new Float32Array(m*f*p),A=new Float32Array(y*f*p);for(let S=0;S<p;S++){const v=S%3*2/3-1,E=S>2?0:-1,D=[v,E,0,v+2/3,E,0,v+2/3,E+1,0,v,E,0,v+2/3,E+1,0,v,E+1,0],O=rS[S];_.set(D,g*f*O),T.set(h,m*f*O);const Y=[O,O,O,O,O,O];A.set(Y,y*f*O)}const B=new Zs;B.setAttribute("position",new Gi(_,g)),B.setAttribute("uv",new Gi(T,m)),B.setAttribute("faceIndex",new Gi(A,y)),n.push(new Ut(B,null)),r>Pn&&r--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function xd(i,e){const t={magFilter:Ot,minFilter:Ot,generateMipmaps:!1,type:it,format:Ft,colorSpace:py},n=new Yr(i,e,t);return n.texture.mapping=Ya,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function Sr(i,e,t,n,r){i.viewport.set(e,t,n,r),i.scissor.set(e,t,n,r)}function Oo(i){const e=new ze;return e.depthTest=!1,e.depthWrite=!1,e.blending=$r,e.name=`PMREM_${i}`,e}function oS(i,e,t){const n=Dt(new Array(Jn).fill(0)),r=Z(new I(0,1,0)),s=Z(0),o=N(Jn),a=Z(0),u=Z(1),l=Pe(),c=Z(0),d=N(1/e),h=N(1/t),p=N(i),f={n:o,latitudinal:a,weights:n,poleAxis:r,outputDirection:Uo,dTheta:s,samples:u,envMap:l,mipInt:c,CUBEUV_TEXEL_WIDTH:d,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:p},g=Oo("blur");return g.fragmentNode=K0({...f,latitudinal:a.equal(1)}),yo.set(g,f),g}function aS(i,e,t){const n=Pe(),r=Z(0),s=Z(0),o=N(1/e),a=N(1/t),u=N(i),l={envMap:n,roughness:r,mipInt:s,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:u},c=Oo("ggx");return c.fragmentNode=J0({...l,N_immutable:Uo,GGX_SAMPLES:de(eS)}),yo.set(c,l),c}function Td(i){const e=Oo("cubemap");return e.fragmentNode=ut(i,Uo),e}function vd(i){const e=Oo("equirect");return e.fragmentNode=Pe(i,jp(Uo),0),e}const Sd=new WeakMap;function uS(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 lS(i,e,t){const n=cS(e);let r=n.get(i);if((r!==void 0?r.pmremVersion:-1)!==i.pmremVersion){const o=i.image;if(i.isCubeTexture)if(hS(o))r=t.fromCubemap(i,r);else return null;else if(fS(o))r=t.fromEquirectangular(i,r);else return null;r.pmremVersion=i.pmremVersion,n.set(i,r)}return r.texture}function cS(i){let e=Sd.get(i);return e===void 0&&(e=new WeakMap,Sd.set(i,e)),e}class dS extends qe{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 r=new dl;r.isRenderTargetTexture=!0,this._texture=Pe(r),this._width=Z(0),this._height=Z(0),this._maxMip=Z(0),this.updateBeforeType=oe.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=uS(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,r=this._value;n!==r.pmremVersion&&(r.isPMREMTexture===!0?t=r:t=lS(r,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=Ap.mul(R(t.x,t.y.negate(),t.z));let n=this.levelNode;return n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),X0(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function hS(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 fS(i){return i==null?!1:i.height>0}const rg=me(dS).setParameterLength(1,3),Nd=new WeakMap;class pS extends ss{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];let h=Nd.get(d);h===void 0&&(h=rg(d),Nd.set(d,h)),n=h}const s=t.useAnisotropy===!0||t.anisotropy>0?kT:pe,o=n.context(Rd(cn,s)).mul(ca),a=n.context(gS(rs)).mul(Math.PI).mul(ca),u=ks(o),l=ks(a);e.context.radiance.addAssign(u),e.context.iblIrradiance.addAssign(l);const c=e.context.lightingModel.clearcoatRadiance;if(c){const d=n.context(Rd(go,Dr)).mul(ca),h=ks(d);c.addAssign(h)}}}const Rd=(i,e)=>{let t=null;return{getUV:()=>(t===null&&(t=Ce.negate().reflect(e),t=up(i).mix(t,e).normalize(),t=t.transformDirection(_n)),t),getTextureLevel:()=>i}},gS=i=>({getUV:()=>i,getTextureLevel:()=>N(1)}),mS=new vm;class sg extends ze{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(mS),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new pS(t):null}setupLightingModel(){return new ng}setupSpecular(){const e=Ne(R(.04),ve.rgb,Mn);dr.assign(R(.04)),Br.assign(e),Us.assign(1)}setupVariants(){const e=this.metalnessNode?N(this.metalnessNode):JT;Mn.assign(e);let t=this.roughnessNode?N(this.roughnessNode):ZT;t=Qp({roughness:t}),cn.assign(t),this.setupSpecular(),Cr.assign(ve.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const yS=new Sm;class bS extends sg{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(yS),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?N(this.iorNode):fv;Xi.assign(e),dr.assign(Wr(ap(Xi.sub(1).div(Xi.add(1))).mul(QT),R(1)).mul(Yc)),Br.assign(Ne(dr,ve.rgb,Mn)),Us.assign(Ne(Yc,1,Mn))}setupLightingModel(){return new ng(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?N(this.clearcoatNode):tv,n=this.clearcoatRoughnessNode?N(this.clearcoatRoughnessNode):nv;Pu.assign(t),go.assign(Qp({roughness:n}))}if(this.useSheen){const t=this.sheenNode?R(this.sheenNode):iv,n=this.sheenRoughnessNode?N(this.sheenRoughnessNode):ov;xt.assign(t),Yn.assign(n)}if(this.useIridescence){const t=this.iridescenceNode?N(this.iridescenceNode):uv,n=this.iridescenceIORNode?N(this.iridescenceIORNode):lv,r=this.iridescenceThicknessNode?N(this.iridescenceThicknessNode):cv;Nl.assign(t),Bu.assign(n),Du.assign(r)}if(this.useAnisotropy){const t=(this.anisotropyNode?j(this.anisotropyNode):av).toVar();Xn.assign(t.length()),Re(Xn.equal(0),()=>{t.assign(j(1,0))}).Else(()=>{t.divAssign(j(Xn)),Xn.assign(Xn.saturate())}),Fu.assign(Xn.pow2().mix(cn.pow2(),1)),Hi.assign(As[0].mul(t.x).add(As[1].mul(t.y))),Or.assign(As[1].mul(t.x).sub(As[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?N(this.transmissionNode):dv,n=this.thicknessNode?N(this.thicknessNode):hv,r=this.attenuationDistanceNode?N(this.attenuationDistanceNode):pv,s=this.attenuationColorNode?R(this.attenuationColorNode):gv;if(Uu.assign(t),zf.assign(n),Wf.assign(r),jf.assign(s),this.useDispersion){const o=this.dispersionNode?N(this.dispersionNode):Tv;qf.assign(o)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?R(this.clearcoatNormalNode):rv}setup(e){e.context.setupClearcoatNormal=()=>Is(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.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 _S=P(({normal:i,lightDirection:e,builder:t})=>{const n=i.dot(e),r=j(n.mul(.5).add(.5),0);if(t.material.gradientMap){const s=En("gradientMap","texture").context({getUV:()=>r});return R(s.r)}else{const s=r.fwidth().mul(.5);return Ne(R(.7),R(1),yn(N(.7).sub(s.x),N(.7).add(s.x),r.x))}});class xS extends Fo{direct({lightDirection:e,lightColor:t,reflectedLight:n},r){const s=_S({normal:Rp,lightDirection:e,builder:r}).mul(t);n.directDiffuse.addAssign(s.mul(Hr({diffuseColor:ve.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(Hr({diffuseColor:ve}))),r.indirectDiffuse.mulAssign(t)}}const TS=new Nm;class vS extends ze{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(TS),this.setValues(e)}setupLightingModel(){return new xS}}const SS=P(()=>{const i=R(Ce.z,0,Ce.x.negate()).normalize(),e=Ce.cross(i);return j(i.dot(pe),e.dot(pe)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),NS=new wm;class RS extends ze{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(NS),this.setValues(e)}setupVariants(e){const t=SS;let n;e.material.matcap?n=En("matcap","texture").context({getUV:()=>t}):n=R(Ne(.2,.8,t.y)),ve.rgb.mulAssign(n.rgb)}}class wS extends qe{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if(this.getNodeType(e)==="vec2"){const s=t.cos(),o=t.sin();return Sl(s,o,o.negate(),s).mul(n)}else{const s=t,o=or(se(1,0,0,0),se(0,Ht(s.x),mt(s.x).negate(),0),se(0,mt(s.x),Ht(s.x),0),se(0,0,0,1)),a=or(se(Ht(s.y),0,mt(s.y),0),se(0,1,0,0),se(mt(s.y).negate(),0,Ht(s.y),0),se(0,0,0,1)),u=or(se(Ht(s.z),mt(s.z).negate(),0,0),se(mt(s.z),Ht(s.z),0,0),se(0,0,1,0),se(0,0,0,1));return o.mul(a).mul(u).mul(se(n,1)).xyz}}}const ig=me(wS).setParameterLength(2),AS=new Cm;class og extends ze{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(AS),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:r,rotationNode:s,scaleNode:o,sizeAttenuation:a}=this,u=ri.mul(R(r||0));let l=j(pr[0].xyz.length(),pr[1].xyz.length());o!==null&&(l=l.mul(j(o))),n.isPerspectiveCamera&&a===!1&&(l=l.mul(u.z.negate()));let c=Do.xy;if(t.center&&t.center.isVector2===!0){const p=Ix("center","vec2",t);c=c.sub(p.sub(.5))}c=c.mul(l);const d=N(s||sv),h=ig(c,d);return se(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 ES=new Em,CS=new ce;class MS extends og{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(ES),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return ri.mul(R(e||Ke)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:r,scaleNode:s,sizeNode:o,sizeAttenuation:a}=this;let u=super.setupVertex(e);if(t.isNodeMaterial!==!0)return u;let l=o!==null?j(o):xv;l=l.mul(hT),n.isPerspectiveCamera&&a===!0&&(l=l.mul(PS.div($e.z.negate()))),s&&s.isNode&&(l=l.mul(j(s)));let c=Do.xy;if(r&&r.isNode){const d=N(r);c=ig(c,d)}return c=c.mul(l),c=c.div(fT.div(2)),c=c.mul(u.w),u=u.add(se(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 PS=Z(1).onFrameUpdate(function({renderer:i}){const e=i.getSize(CS);this.value=.5*e.y});class BS extends Fo{constructor(){super(),this.shadowNode=N(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){ve.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(ve.rgb)}}const DS=new Mm;class FS extends ze{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(DS),this.setValues(e)}setupLightingModel(){return new BS}}Un("vec3");Un("vec3");Un("vec3");class LS{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.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 It{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 r=0;r<e.length-1;r++){const s=e[r];n.has(s)===!1&&n.set(s,new WeakMap),n=n.get(s)}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 US=0;function OS(i){const e=Object.keys(i);let t=Object.getPrototypeOf(i);for(;t;){const n=Object.getOwnPropertyDescriptors(t);for(const r in n)if(n[r]!==void 0){const s=n[r];s&&typeof s.get=="function"&&e.push(r)}t=Object.getPrototypeOf(t)}return e}class IS{constructor(e,t,n,r,s,o,a,u,l,c){this.id=US++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=r,this.material=s,this.scene=o,this.camera=a,this.lightsNode=u,this.context=l,this.geometry=r.geometry,this.version=s.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=[],r=new Set,s={};for(const o of e){let a;if(o.node&&o.node.attribute?a=o.node.attribute:(a=t.getAttribute(o.name),s[o.name]=a.version),a===void 0)continue;n.push(a);const u=a.isInterleavedBufferAttribute?a.data:a;r.add(u)}return this.attributes=n,this.attributesId=s,this.vertexBuffers=Array.from(r.values()),n}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:r,drawRange:s}=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=s.start*c,h=(s.start+s.count)*c;r!==null&&(d=Math.max(d,r.start*c),h=Math.min(h,(r.start+r.count)*c));const p=n.attributes.position;let f=1/0;u?f=a.count:p!=null&&(f=p.count),d=Math.max(d,0),h=Math.min(h,f);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 r=e.attributes[n];t+=n+",",r.data&&(t+=r.data.stride+","),r.offset&&(t+=r.offset+","),r.itemSize&&(t+=r.itemSize+","),r.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const r=e.morphAttributes[n];t+="morph-"+n+",";for(let s=0,o=r.length;s<o;s++){const a=r[s];t+=a.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:n}=this;let r=t.customProgramCacheKey();for(const s of OS(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(s))continue;const o=t[s];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);r+=a+","}return r+=this.clippingContextCacheKey+",",e.geometry&&(r+=this.getGeometryCacheKey()),e.skeleton&&(r+=e.skeleton.bones.length+","),e.isBatchedMesh&&(r+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(r+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(r+=e.uuid+","),r+=this.context.id+",",r+=e.receiveShadow+",",Co(r)}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=Fs(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Fs(e,1)),e=Fs(e,this.camera.id,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 Wn=[];class kS{constructor(e,t,n,r,s,o){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=r,this.bindings=s,this.info=o,this.chainMaps={}}get(e,t,n,r,s,o,a,u){const l=this.getChainMap(u);Wn[0]=e,Wn[1]=t,Wn[2]=o,Wn[3]=s;let c=l.get(Wn);return c===void 0?(c=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,r,s,o,a,u),l.set(Wn,c)):(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,r,s,o,a,u)):c.version=t.version)),Wn.length=0,c}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new It)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,r,s,o,a,u,l,c,d){const h=this.getChainMap(d),p=new IS(e,t,n,r,s,o,a,u,l,c);return p.onDispose=()=>{this.pipelines.delete(p),this.bindings.deleteForRender(p),this.nodes.delete(p),h.delete(p.getChainArray())},p}}class kn{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 Rt={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},Cn=16,GS=211,VS=212;class $S extends kn{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return t!==null&&this.backend.destroyAttribute(e),t}update(e,t){const n=this.get(e);if(n.version===void 0)t===Rt.VERTEX?this.backend.createAttribute(e):t===Rt.INDEX?this.backend.createIndexAttribute(e):t===Rt.STORAGE?this.backend.createStorageAttribute(e):t===Rt.INDIRECT&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const r=this._getBufferAttribute(e);(n.version<r.version||r.usage===Mr)&&(this.backend.updateAttribute(e),n.version=r.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function ag(i){return i.index!==null?i.index.version:i.attributes.position.version}function wd(i){const e=[],t=i.index,n=i.attributes.position;if(t!==null){const s=t.array;for(let o=0,a=s.length;o<a;o+=3){const u=s[o+0],l=s[o+1],c=s[o+2];e.push(u,l,l,c,c,u)}}else{const s=n.array;for(let o=0,a=s.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 r=new(Fm(e)?Bm:Dm)(e,1);return r.version=ag(i),r}class zS extends kn{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 r=()=>{this.info.memory.geometries--;const s=t.index,o=e.getAttributes();s!==null&&this.attributes.delete(s);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",r),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){const t=e.getAttributes();for(const s of t)s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute?this.updateAttribute(s,Rt.STORAGE):this.updateAttribute(s,Rt.VERTEX);const n=this.getIndex(e);n!==null&&this.updateAttribute(n,Rt.INDEX);const r=e.geometry.indirect;r!==null&&this.updateAttribute(r,Rt.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 r=t.index;if(n.wireframe===!0){const s=this.wireframes;let o=s.get(t);o===void 0?(o=wd(t),s.set(t,o)):o.version!==ag(t)&&(this.attributes.delete(o),o=wd(t),s.set(t,o)),r=o}return r}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class WS{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}}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):G("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,this.memory.geometries=0,this.memory.textures=0}}class ug{constructor(e){this.cacheKey=e,this.usedTimes=0}}class jS extends ug{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class qS extends ug{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let HS=0;class Sa{constructor(e,t,n,r=null,s=null){this.id=HS++,this.code=e,this.stage=t,this.name=n,this.transforms=r,this.attributes=s,this.usedTimes=0}}class XS extends kn{constructor(e,t){super(),this.backend=e,this.nodes=t,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,r=this.get(e);if(this._needsComputeUpdate(e)){const s=r.pipeline;s&&(s.usedTimes--,s.computeProgram.usedTimes--);const o=this.nodes.getForCompute(e);let a=this.programs.compute.get(o.computeShader);a===void 0&&(s&&s.computeProgram.usedTimes===0&&this._releaseProgram(s.computeProgram),a=new Sa(o.computeShader,"compute",e.name,o.transforms,o.nodeAttributes),this.programs.compute.set(o.computeShader,a),n.createProgram(a));const u=this._getComputeCacheKey(e,a);let l=this.caches.get(u);l===void 0&&(s&&s.usedTimes===0&&this._releasePipeline(s),l=this._getComputePipeline(e,a,u,t)),l.usedTimes++,a.usedTimes++,r.version=e.version,r.pipeline=l}return r.pipeline}getForRender(e,t=null){const{backend:n}=this,r=this.get(e);if(this._needsRenderUpdate(e)){const s=r.pipeline;s&&(s.usedTimes--,s.vertexProgram.usedTimes--,s.fragmentProgram.usedTimes--);const o=e.getNodeBuilderState(),a=e.material?e.material.name:"";let u=this.programs.vertex.get(o.vertexShader);u===void 0&&(s&&s.vertexProgram.usedTimes===0&&this._releaseProgram(s.vertexProgram),u=new Sa(o.vertexShader,"vertex",a),this.programs.vertex.set(o.vertexShader,u),n.createProgram(u));let l=this.programs.fragment.get(o.fragmentShader);l===void 0&&(s&&s.fragmentProgram.usedTimes===0&&this._releaseProgram(s.fragmentProgram),l=new Sa(o.fragmentShader,"fragment",a),this.programs.fragment.set(o.fragmentShader,l),n.createProgram(l));const c=this._getRenderCacheKey(e,u,l);let d=this.caches.get(c);d===void 0?(s&&s.usedTimes===0&&this._releasePipeline(s),d=this._getRenderPipeline(e,u,l,c,t)):e.pipeline=d,d.usedTimes++,u.usedTimes++,l.usedTimes++,r.pipeline=d}return r.pipeline}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,r){n=n||this._getComputeCacheKey(e,t);let s=this.caches.get(n);return s===void 0&&(s=new qS(n,t),this.caches.set(n,s),this.backend.createComputePipeline(s,r)),s}_getRenderPipeline(e,t,n,r,s){r=r||this._getRenderCacheKey(e,t,n);let o=this.caches.get(r);return o===void 0&&(o=new jS(r,t,n),this.caches.set(r,o),e.pipeline=o,this.backend.createRenderPipeline(e,s)),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)}_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 KS extends kn{constructor(e,t,n,r,s,o){super(),this.backend=e,this.textures=n,this.pipelines=s,this.attributes=r,this.nodes=t,this.info=o,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const n of t){const r=this.get(n);r.bindGroup===void 0&&(this._init(n),this.backend.createBindings(n,t,0),r.bindGroup=n)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const n of t){const r=this.get(n);r.bindGroup===void 0&&(this._init(n),this.backend.createBindings(n,t,0),r.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,r=n.isIndirectStorageBufferAttribute?Rt.INDIRECT:Rt.STORAGE;this.attributes.update(n,r)}}_update(e,t){const{backend:n}=this;let r=!1,s=!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?Rt.INDIRECT:Rt.STORAGE;this.attributes.update(c,d)}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,r=!0,s=!1)),n.get(d).externalTexture!==void 0||h.isDefaultTexture?s=!1:(o=o*10+d.id,a+=d.version),d.isStorageTexture===!0&&d.mipmapsAutoUpdate===!0){const f=this.get(d);u.store===!0?f.needsMipmap=!0:this.textures.needsMipmaps(d)&&f.needsMipmap===!0&&(this.backend.generateMipmaps(d),f.needsMipmap=!1)}}else if(u.isSampler&&u.update()){const d=this.textures.updateSampler(u.texture);u.samplerKey!==d&&(u.samplerKey=d,r=!0,s=!1)}}r===!0&&this.backend.updateBindings(e,t,s?o:0,a)}}function YS(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 Ad(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 Ed(i){return(i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode)&&i.side===rr&&i.forceSinglePass===!1}class QS{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,r,s,o,a){let u=this.renderItems[this.renderItemsIndex];return u===void 0?(u={id:e.id,object:e,geometry:t,material:n,groupOrder:r,renderOrder:e.renderOrder,z:s,group:o,clippingContext:a},this.renderItems[this.renderItemsIndex]=u):(u.id=e.id,u.object=e,u.geometry=t,u.material=n,u.groupOrder=r,u.renderOrder=e.renderOrder,u.z=s,u.group=o,u.clippingContext=a),this.renderItemsIndex++,u}push(e,t,n,r,s,o,a){const u=this.getNextRenderItem(e,t,n,r,s,o,a);e.occlusionTest===!0&&this.occlusionQueryCount++,n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Ed(n)&&this.transparentDoublePass.push(u),this.transparent.push(u)):this.opaque.push(u)}unshift(e,t,n,r,s,o,a){const u=this.getNextRenderItem(e,t,n,r,s,o,a);n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Ed(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||YS),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Ad),this.transparent.length>1&&this.transparent.sort(t||Ad)}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 ys=[];class ZS{constructor(e){this.lighting=e,this.lists=new It}get(e,t){const n=this.lists;ys[0]=e,ys[1]=t;let r=n.get(ys);return r===void 0&&(r=new QS(this.lighting,e,t),n.set(ys,r)),ys.length=0,r}dispose(){this.lists=new It}}let JS=0;class eN{constructor(){this.id=JS++,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 Oe,this.scissor=!1,this.scissorValue=new Oe,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.isRenderContext=!0}getCacheKey(){return lg(this)}}function lg(i){const{textures:e,activeCubeFace:t,activeMipmapLevel:n}=i,r=[t,n];for(const s of e)r.push(s.id);return ei(r)}const Nr=[],tN=new So,nN=new hm;class rN{constructor(){this.chainMaps={}}get(e,t,n=null,r=null){Nr[0]=e,Nr[1]=t,r!==null&&(Nr[2]=r);let s;if(n===null)s="default";else{const u=n.texture.format;s=`${n.textures.length}:${u}:${n.samples}:${n.depthBuffer}:${n.stencilBuffer}`}const o=this._getChainMap(s);let a=o.get(Nr);return a===void 0&&(a=new eN,o.set(Nr,a)),Nr.length=0,n!==null&&(a.sampleCount=n.samples===0?1:n.samples),a}getForClear(e=null){return this.get(tN,nN,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new It)}dispose(){this.chainMaps={}}}const sN=new I;class iN extends kn{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n}updateRenderTarget(e,t=0){const n=this.get(e),r=e.samples===0?1:e.samples,s=n.depthTextureMips||(n.depthTextureMips={}),o=e.textures,a=this.getSize(o[0]),u=a.width>>t,l=a.height>>t;let c=e.depthTexture||s[t];const d=e.depthBuffer===!0||e.stencilBuffer===!0;let h=!1;c===void 0&&d&&(c=new Qt,c.format=e.stencilBuffer?Dn:Fn,c.type=e.stencilBuffer?Bn:je,c.image.width=u,c.image.height=l,c.image.depth=a.depth,c.renderTarget=e,c.isArrayTexture=e.multiview===!0&&a.depth>1,s[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!==r&&(h=!0,c&&(c.needsUpdate=!0),n.sampleCount=r);const p={sampleCount:r};if(e.isXRRenderTarget!==!0){for(let f=0;f<o.length;f++){const g=o[f];h&&(g.needsUpdate=!0),this.updateTexture(g,p)}c&&this.updateTexture(c,p)}n.initialized!==!0&&(n.initialized=!0,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 r=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,s=this.backend;if(r&&n.initialized===!0&&s.destroyTexture(e),e.isFramebufferTexture){const l=this.renderer.getRenderTarget();l?e.type=l.texture.type:e.type=bt}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++,r||e.isStorageTexture===!0||e.isExternalTexture===!0)s.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)&&(s.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),e.source.dataReady===!0&&s.updateTexture(e,t);const c=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!c&&s.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else s.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;n.initialized!==!0&&(n.initialized=!0,n.generation=e.version,this.info.memory.textures++,e.isVideoTexture&&Ve.enabled===!0&&Ve.getTransfer(e.colorSpace)!==re&&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=sN){let n=e.images?e.images[0]:e.image;return n?(n.image!==void 0&&(n=n.image),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 r;return e.mipmaps.length>0?r=e.mipmaps.length:e.isCompressedTexture===!0?r=1:r=Math.floor(Math.log2(Math.max(t,n)))+1,r}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,r=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let s=0;s<n.length;s++)this._destroyTexture(n[s]);r&&this._destroyTexture(r),this.delete(e),this.backend.delete(e)}}_destroyTexture(e){if(this.has(e)===!0){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const n=t.isDefaultTexture;this.backend.destroyTexture(e,n),this.delete(e),this.info.memory.textures--}}}class Il extends Ct{constructor(e,t,n,r=1){super(e,t,n),this.a=r}set(e,t,n,r=1){return this.a=r,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 oN extends _e{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const n=this.getNodeType(e),r=e.getStructTypeNode(n);let s;return r!==null?s=r.getMemberType(e,t):(G(`TSL: Member "${t}" not found in struct "${n}".`),s="float"),s}getHash(){return this.uuid}generate(){return this.name}}class aN extends H{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?this.outputNode.getElementType(e):"void"}getNodeType(e){return this.hasOutput?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return e.isNode!==!0?(G("TSL: Invalid node added to stack."),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 ws(t);return this._currentCond=lt(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){const n=new ws(t),r=lt(e,n);return this._currentCond.elseNode=r,this._currentCond=r,this}Else(e){return this._currentCond.elseNode=new ws(e),this}Switch(e){return this._expressionNode=$(e),this}Case(...e){const t=[];if(e.length>=2)for(let a=0;a<e.length-1;a++)t.push(this._expressionNode.equal($(e[a])));else G("TSL: Invalid parameter length. Case() requires at least two parameters.");const n=e[e.length-1],r=new ws(n);let s=t[0];for(let a=1;a<t.length;a++)s=s.or(t[a]);const o=lt(s,r);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 r of this.getChildren())r.isVarNode&&r.isIntent(e)&&r.isAssign(e)!==!0||(t["node"+n++]=r);return t.outputNode||null}get hasOutput(){return this.outputNode&&this.outputNode.isNode}build(e,...t){const n=Uf(),r=e.buildStage;fo(this),e.setActiveStack(this);const s=l=>{if(this._currentNode=l,!(l.isVarNode&&l.isIntent(e)&&l.isAssign(e)!==!0)){if(r==="setup")l.build(e);else if(r==="analyze")l.build(e,this);else if(r==="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)s(l);this._currentNode=null;const a=this.nodes.filter(l=>o.indexOf(l)===-1);for(const l of a)s(l);let u;return this.hasOutput?u=this.outputNode.build(e,...t):u=super.build(e,...t),fo(n),e.removeActiveStack(this),u}}const Na=me(aN).setParameterLength(0,1);class cg extends qe{static get type(){return"BitcastNode"}constructor(e,t,n=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=n,this.isBitcastNode=!0}getNodeType(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 r=this.valueNode.getNodeType(e);n=e.getTypeLength(r)===1?this.inputType:e.changeComponentType(r,this.inputType)}else n=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,n)}( ${this.valueNode.build(e,n)} )`}}const uN=W(cg).setParameterLength(2),lN=i=>new cg(i,"uint","float"),Si={};class lr extends x{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){n==="int"?t.assign(uN(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return de;case"int":return Me;case"uvec2":return If;case"uvec3":return Gf;case"uvec4":return $f;case"ivec2":return qt;case"ivec3":return kf;case"ivec4":return Vf}}_createTrailingZerosBaseLayout(e,t){const n=this._returnDataNode(t);return P(([s])=>{const o=de(0);this._resolveElementType(s,o,t);const a=N(o.bitAnd(np(o))),l=lN(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 P(([s])=>{Re(s.equal(de(0)),()=>de(32));const o=de(0),a=de(0);return this._resolveElementType(s,o,t),Re(o.shiftRight(16).equal(0),()=>{a.addAssign(16),o.shiftLeftAssign(16)}),Re(o.shiftRight(24).equal(0),()=>{a.addAssign(8),o.shiftLeftAssign(8)}),Re(o.shiftRight(28).equal(0),()=>{a.addAssign(4),o.shiftLeftAssign(4)}),Re(o.shiftRight(30).equal(0),()=>{a.addAssign(2),o.shiftLeftAssign(2)}),Re(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 P(([s])=>{const o=de(0);this._resolveElementType(s,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,r){const s=this._returnDataNode(t);return P(([a])=>{if(n===1)return s(r(a));{const u=s(0),l=["x","y","z","w"];for(let c=0;c<n;c++){const d=l[c];u[d].assign(r(a[d]))}return u}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){const{method:t,aNode:n}=this,{renderer:r}=e;if(r.backend.isWebGPUBackend)return super.setup(e);const s=this.getInputType(e),o=e.getElementType(s),a=e.getTypeLength(s),u=`${t}_base_${o}`,l=`${t}_${s}`;let c=Si[u];if(c===void 0){switch(t){case lr.COUNT_LEADING_ZEROS:{c=this._createLeadingZerosBaseLayout(u,o);break}case lr.COUNT_TRAILING_ZEROS:{c=this._createTrailingZerosBaseLayout(u,o);break}case lr.COUNT_ONE_BITS:{c=this._createOneBitsBaseLayout(u,o);break}}Si[u]=c}let d=Si[l];return d===void 0&&(d=this._createMainLayout(l,s,a,c),Si[l]=d),P(()=>d(n))()}}lr.COUNT_TRAILING_ZEROS="countTrailingZeros";lr.COUNT_LEADING_ZEROS="countLeadingZeros";lr.COUNT_ONE_BITS="countOneBits";new vo;new I;new I;new I;new Et;new I(0,0,-1);new Oe;new I;new I;new Oe;new ce;const cN=new Yr;Ir.flipX();cN.depthTexture=new Qt(1,1);const Ra=new nl(-1,1,1,-1,0,1);class dN extends Zs{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new oo([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new oo(t,2))}}const hN=new dN;class kl extends Ut{constructor(e=null){super(hN,e),this.camera=Ra,this.isQuadMesh=!0}async renderAsync(e){Ge('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,Ra)}render(e){e.render(this,Ra)}}const dg=P(([i])=>Jt(N(52.9829189).mul(Jt(hr(i,j(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),Xt=P(([i,e,t])=>{const n=N(2.399963229728653),r=fn(N(i).add(.5).div(N(e))),s=N(i).mul(n).add(t);return j(Ht(s),mt(s)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class pn extends H{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===pn.OBJECT?this.updateType=oe.OBJECT:e===pn.MATERIAL?this.updateType=oe.RENDER:e===pn.BEFORE_OBJECT?this.updateBeforeType=oe.OBJECT:e===pn.BEFORE_MATERIAL&&(this.updateBeforeType=oe.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}pn.OBJECT="object";pn.MATERIAL="material";pn.BEFORE_OBJECT="beforeObject";pn.BEFORE_MATERIAL="beforeMaterial";const bs=new of,wa=new Et;class dt extends H{static get type(){return"SceneNode"}constructor(e=dt.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,n=this.scene!==null?this.scene:e.scene;let r;return t===dt.BACKGROUND_BLURRINESS?r=Se("backgroundBlurriness","float",n):t===dt.BACKGROUND_INTENSITY?r=Se("backgroundIntensity","float",n):t===dt.BACKGROUND_ROTATION?r=Z("mat4").setName("backgroundRotation").setGroup(Q).onRenderUpdate(()=>{const s=n.background;return s!==null&&s.isTexture&&s.mapping!==ry?(bs.copy(n.backgroundRotation),bs.x*=-1,bs.y*=-1,bs.z*=-1,wa.makeRotationFromEuler(bs)):wa.identity(),wa}):G("SceneNode: Unknown scope:",t),r}}dt.BACKGROUND_BLURRINESS="backgroundBlurriness";dt.BACKGROUND_INTENSITY="backgroundIntensity";dt.BACKGROUND_ROTATION="backgroundRotation";const fN=U(dt,dt.BACKGROUND_BLURRINESS),Cd=U(dt,dt.BACKGROUND_INTENSITY),pN=U(dt,dt.BACKGROUND_ROTATION),gN=P(({texture:i,uv:e})=>{const n=R().toVar();return Re(e.x.lessThan(1e-4),()=>{n.assign(R(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{n.assign(R(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{n.assign(R(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{n.assign(R(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{n.assign(R(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{n.assign(R(0,0,-1))}).Else(()=>{const s=i.sample(e.add(R(-.01,0,0))).r.sub(i.sample(e.add(R(.01,0,0))).r),o=i.sample(e.add(R(0,-.01,0))).r.sub(i.sample(e.add(R(0,.01,0))).r),a=i.sample(e.add(R(0,0,-.01))).r.sub(i.sample(e.add(R(0,0,.01))).r);n.assign(R(s,o,a))}),n.normalize()});class mN extends ts{static get type(){return"Texture3DNode"}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return R(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return e.isFlipY()&&(n.isRenderTargetTexture===!0||n.isFramebufferTexture===!0)&&(this.sampler?t=t.flipY():t=t.setY(Me(ur(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return gN({texture:this,uv:e})}}const yN=me(mN).setParameterLength(1,3),Ni=new ce;class bN extends ts{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Md extends bN{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n}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 Io extends qe{static get type(){return"PassNode"}constructor(e,t,n,r={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=r,this._pixelRatio=1,this._width=1,this._height=1;const s=new Qt;s.isRenderTargetTexture=!0,s.name="depth";const o=new Yr(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:it,...r});o.texture.name="output",o.depthTexture=s,this.renderTarget=o,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:o.texture,depth:s},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Z(0),this._cameraFar=Z(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=oe.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],r=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[r]=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 Md(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 Md(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,r=this._cameraFar;this._viewZNodes[e]=t=Vp(this.getTextureNode(e),n,r)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(t===void 0){const n=this._cameraNear,r=this._cameraFar,s=this.getViewZNode(e);this._linearDepthNodes[e]=t=$s(s,n,r)}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(),this.scope===Io.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let r,s;const o=t.getOutputRenderTarget();o&&o.isXRRenderTarget===!0?(s=1,r=t.xr.getCamera(),t.xr.updateCamera(r),Ni.set(o.width,o.height)):(r=this.camera,s=t.getPixelRatio(),t.getSize(Ni)),this._pixelRatio=s,this.setSize(Ni.width,Ni.height);const a=t.getRenderTarget(),u=t.getMRT(),l=t.autoClear,c=t.transparent,d=t.opaque,h=r.layers.mask,p=t.contextNode,f=n.overrideMaterial;this._cameraNear.value=r.near,this._cameraFar.value=r.far,this._layers!==null&&(r.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:gr({...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,r),n.name=g,n.overrideMaterial=f,t.setRenderTarget(a),t.setMRT(u),t.autoClear=l,t.transparent=c,t.opaque=d,t.contextNode=p,r.layers.mask=h}setSize(e,t){this._width=e,this._height=t;const n=Math.floor(this._width*this._pixelRatio*this._resolutionScale),r=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(n,r),this._scissor!==null&&this.renderTarget.scissor.copy(this._scissor),this._viewport!==null&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,n,r){e===null?this._scissor=null:(this._scissor===null&&(this._scissor=new Oe),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,r),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,n,r){e===null?this._viewport=null:(this._viewport===null&&(this._viewport=new Oe),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,r),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Io.COLOR="color";Io.DEPTH="depth";const _N=P(([i,e])=>i.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),xN=P(([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"}]}),TN=P(([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"}]}),vN=P(([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)}),SN=P(([i,e])=>{const t=nt(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),n=nt(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return i=i.mul(e).div(.6),i=t.mul(i),i=vN(i),i=n.mul(i),i.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),NN=nt(R(1.6605,-.1246,-.0182),R(-.5876,1.1329,-.1006),R(-.0728,-.0083,1.1187)),RN=nt(R(.6274,.0691,.0164),R(.3293,.9195,.088),R(.0433,.0113,.8956)),wN=P(([i])=>{const e=R(i).toVar(),t=R(e.mul(e)).toVar(),n=R(t.mul(t)).toVar();return N(15.5).mul(n.mul(t)).sub(ae(40.14,n.mul(e))).add(ae(31.96,n).sub(ae(6.868,t.mul(e))).add(ae(.4298,t).add(ae(.1191,e).sub(.00232))))}),AN=P(([i,e])=>{const t=R(i).toVar(),n=nt(R(.856627153315983,.137318972929847,.11189821299995),R(.0951212405381588,.761241990602591,.0767994186031903),R(.0482516061458583,.101439036467562,.811302368396859)),r=nt(R(1.1271005818144368,-.1413297634984383,-.14132976349843826),R(-.11060664309660323,1.157823702216272,-.11060664309660294),R(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=N(-12.47393),o=N(4.026069);return t.mulAssign(e),t.assign(RN.mul(t)),t.assign(n.mul(t)),t.assign(Je(t,1e-10)),t.assign(gn(t)),t.assign(t.sub(s).div(o.sub(s))),t.assign(On(t,0,1)),t.assign(wN(t)),t.assign(r.mul(t)),t.assign(Bo(Je(R(0),t),R(2.2))),t.assign(NN.mul(t)),t.assign(On(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),EN=P(([i,e])=>{const t=N(.76),n=N(.15);i=i.mul(e);const r=Wr(i.r,Wr(i.g,i.b)),s=lt(r.lessThan(.08),r.sub(ae(6.25,r.mul(r))),.04);i.subAssign(s);const o=Je(i.r,Je(i.g,i.b));Re(o.lessThan(t),()=>i);const a=at(1,t),u=at(1,a.mul(a).div(o.add(a.sub(t))));i.mulAssign(u.div(o));const l=at(1,Zt(1,n.mul(o.sub(u)).add(1)));return Ne(i,R(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Qe extends H{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 r of t)r.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 CN extends Qe{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(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),r=n.name,s=n.type,o=e.getCodeFromNode(this,s);r!==""&&(o.name=r);const a=e.getPropertyName(o),u=this.getNodeFunction(e).getCode(a);return o.code=u+`
534
+ `,t==="property"?a:e.format(`${a}()`,s,t)}}function hg(i){let e;const t=i.context.getViewZ;return t!==void 0&&(e=t(this)),(e||$e.z).negate()}const MN=P(([i,e],t)=>{const n=hg(t);return yn(i,e,n)}),PN=P(([i],e)=>{const t=hg(e);return i.mul(i,t,t).negate().exp().oneMinus()}),Pd=P(([i,e])=>se(e.toFloat().mix(Os.rgb,i.toVec3()),Os.a));class BN extends H{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:n}=e;n.backend.isWebGLBackend===!0?e.addFlowCode(` // ${t}Barrier
535
+ `):e.addLineFlowCode(`${t}Barrier()`,this)}}me(BN);class nn extends H{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)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),n=t.parents,r=this.method,s=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(r,s)}( ${l.join(", ")} )`;if(n?n.length===1&&n[0].isStackNode===!0:!1)e.addLineFlowCode(c,this);else return t.constNode===void 0&&(t.constNode=jr(c,s).toConst()),t.constNode.build(e)}}nn.ATOMIC_LOAD="atomicLoad";nn.ATOMIC_STORE="atomicStore";nn.ATOMIC_ADD="atomicAdd";nn.ATOMIC_SUB="atomicSub";nn.ATOMIC_MAX="atomicMax";nn.ATOMIC_MIN="atomicMin";nn.ATOMIC_AND="atomicAnd";nn.ATOMIC_OR="atomicOr";nn.ATOMIC_XOR="atomicXor";me(nn);class ge extends qe{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,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n);return r>s?t:n}getNodeType(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,r=this.getNodeType(e),s=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,r),a.build(e,c==="float"?"int":r))}else n===ge.SUBGROUP_SHUFFLE_XOR||n===ge.SUBGROUP_SHUFFLE_DOWN||n===ge.SUBGROUP_SHUFFLE_UP?u.push(o.build(e,r),a.build(e,"uint")):(o!==null&&u.push(o.build(e,s)),a!==null&&u.push(a.build(e,s)));const l=u.length===0?"()":`( ${u.join(", ")} )`;return e.format(`${e.getMethod(n,r)}${l}`,r,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 Ri;function ko(i){Ri=Ri||new WeakMap;let e=Ri.get(i);return e===void 0&&Ri.set(i,e={}),e}function Gl(i){const e=ko(i);return e.shadowMatrix||(e.shadowMatrix=Z("mat4").setGroup(Q).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 DN(i,e=qr){const t=Gl(i).mul(e);return t.xyz.div(t.w)}function fg(i){const e=ko(i);return e.position||(e.position=Z(new I).setGroup(Q).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(i.matrixWorld)))}function FN(i){const e=ko(i);return e.targetPosition||(e.targetPosition=Z(new I).setGroup(Q).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(i.target.matrixWorld)))}function pg(i){const e=ko(i);return e.viewPosition||(e.viewPosition=Z(new I).setGroup(Q).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new I,n.value.setFromMatrixPosition(i.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}const gg=i=>_n.transformDirection(fg(i).sub(FN(i))),LN=i=>i.sort((e,t)=>e.id-t.id),UN=(i,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===i)return t;return null},Aa=new WeakMap,_s=[];class mg extends H{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Un("vec3","totalDiffuse"),this.totalSpecularNode=Un("vec3","totalSpecular"),this.outgoingLightNode=Un("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 r=e[n];if(_s.push(r.id),_s.push(r.castShadow?1:0),r.isSpotLight===!0){const s=r.map!==null?r.map.id:-1,o=r.colorNode?r.colorNode.getCacheKey():-1;_s.push(s,o)}}const t=ei(_s);return _s.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,r=LN(this._lights),s=e.renderer.library;for(const o of r)if(o.isNode)t.push($(o));else{let a=null;if(n!==null&&(a=UN(o.id,n)),a===null){const u=s.getLightNodeClass(o.constructor);if(u===null){z(`LightsNode.setupNodeLights: Light node not found for ${o.constructor.name}`);continue}let l=null;Aa.has(o)?l=Aa.get(o):(l=new u(o),Aa.set(o,l)),t.push(l)}}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:r,reflectedLight:s}=e.context;r.direct({...n,lightNode:t,reflectedLight:s},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:r,reflectedLight:s}=e.context;r.directRectArea({...n,lightNode:t,reflectedLight:s},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 r=e.context,s=r.lightingModel,o=e.getNodeProperties(this);if(s){const{totalDiffuseNode:a,totalSpecularNode:u}=this;r.outgoingLight=n;const l=e.addStack();o.nodes=l.nodes,s.start(e);const{backdrop:c,backdropAlpha:d}=r,{directDiffuse:h,directSpecular:p,indirectDiffuse:f,indirectSpecular:g}=r.reflectedLight;let m=h.add(f);c!==null&&(d!==null?m=R(d.mix(m,c)):m=R(c)),a.assign(m),u.assign(p.add(g)),n.assign(a.add(u)),s.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 ON extends H{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=oe.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){yg.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||qr)}}const yg=Un("vec3","shadowPositionWorld");function IN(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 Ct),e.clearAlpha=i.getClearAlpha(),e.autoClear=i.autoClear,e.scissorTest=i.getScissorTest(),e}function kN(i,e){return e=IN(i,e),i.setMRT(null),i.setRenderObjectFunction(null),i.setClearColor(0,1),i.autoClear=!0,e}function GN(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 VN(i,e={}){return e.background=i.background,e.backgroundNode=i.backgroundNode,e.overrideMaterial=i.overrideMaterial,e}function $N(i,e){return e=VN(i,e),i.background=null,i.backgroundNode=null,i.overrideMaterial=null,e}function zN(i,e){i.background=e.background,i.backgroundNode=e.backgroundNode,i.overrideMaterial=e.overrideMaterial}function WN(i,e,t){return t=kN(i,t),t=$N(e,t),t}function jN(i,e,t){GN(i,t),zN(e,t)}const bo=new WeakMap,qN=P(({depthTexture:i,shadowCoord:e,depthLayer:t})=>{let n=Pe(i,e.xy).setName("t_basic");return i.isArrayTexture&&(n=n.depth(t)),n.compare(e.z)}),HN=P(({depthTexture:i,shadowCoord:e,shadow:t,depthLayer:n})=>{const r=(c,d)=>{let h=Pe(i,c);return i.isArrayTexture&&(h=h.depth(n)),h.compare(d)},s=Se("mapSize","vec2",t).setGroup(Q),o=Se("radius","float",t).setGroup(Q),a=j(1).div(s),u=o.mul(a.x),l=dg(ns.xy).mul(6.28318530718);return pt(r(e.xy.add(Xt(0,5,l).mul(u)),e.z),r(e.xy.add(Xt(1,5,l).mul(u)),e.z),r(e.xy.add(Xt(2,5,l).mul(u)),e.z),r(e.xy.add(Xt(3,5,l).mul(u)),e.z),r(e.xy.add(Xt(4,5,l).mul(u)),e.z)).mul(1/5)}),XN=P(({depthTexture:i,shadowCoord:e,shadow:t,depthLayer:n})=>{const r=(d,h)=>{let p=Pe(i,d);return i.isArrayTexture&&(p=p.depth(n)),p.compare(h)},s=Se("mapSize","vec2",t).setGroup(Q),o=j(1).div(s),a=o.x,u=o.y,l=e.xy,c=Jt(l.mul(s).add(.5));return l.subAssign(c.mul(o)),pt(r(l,e.z),r(l.add(j(a,0)),e.z),r(l.add(j(0,u)),e.z),r(l.add(o),e.z),Ne(r(l.add(j(a.negate(),0)),e.z),r(l.add(j(a.mul(2),0)),e.z),c.x),Ne(r(l.add(j(a.negate(),u)),e.z),r(l.add(j(a.mul(2),u)),e.z),c.x),Ne(r(l.add(j(0,u.negate())),e.z),r(l.add(j(0,u.mul(2))),e.z),c.y),Ne(r(l.add(j(a,u.negate())),e.z),r(l.add(j(a,u.mul(2))),e.z),c.y),Ne(Ne(r(l.add(j(a.negate(),u.negate())),e.z),r(l.add(j(a.mul(2),u.negate())),e.z),c.x),Ne(r(l.add(j(a.negate(),u.mul(2))),e.z),r(l.add(j(a.mul(2),u.mul(2))),e.z),c.x),c.y)).mul(1/9)}),KN=P(({depthTexture:i,shadowCoord:e,depthLayer:t})=>{let n=Pe(i).sample(e.xy);i.isArrayTexture&&(n=n.depth(t)),n=n.rg;const r=n.x,s=Je(1e-7,n.y.mul(n.y)),o=op(e.z,r);Re(o.equal(1),()=>N(1));const a=e.z.sub(r);let u=s.div(s.add(a.mul(a)));return u=On(at(u,.3).div(.65)),Je(o,u)}),YN=P(([i,e,t])=>{let n=qr.sub(i).length();return n=n.sub(e).div(t.sub(e)),n=n.saturate(),n}),QN=i=>{const e=i.shadow.camera,t=Se("near","float",e).setGroup(Q),n=Se("far","float",e).setGroup(Q),r=gT(i);return YN(r,t,n)},ZN=i=>{let e=bo.get(i);if(e===void 0){const t=i.isPointLight?QN(i):null;e=new ze,e.colorNode=se(0,0,0,1),e.depthNode=t,e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.fog=!1,bo.set(i,e)}return e},JN=i=>{const e=bo.get(i);e!==void 0&&(e.dispose(),bo.delete(i))},Bd=new It,Rr=[],eR=(i,e,t,n)=>{Rr[0]=i,Rr[1]=e;let r=Bd.get(Rr);return(r===void 0||r.shadowType!==t||r.useVelocity!==n)&&(r=(s,o,a,u,l,c,...d)=>{(s.castShadow===!0||s.receiveShadow&&t===ji)&&(n&&(Bf(s).useVelocity=!0),s.onBeforeShadow(i,s,a,e.camera,u,o.overrideMaterial,c),i.renderObject(s,o,a,u,l,c,...d),s.onAfterShadow(i,s,a,e.camera,u,o.overrideMaterial,c))},r.shadowType=t,r.useVelocity=n,Bd.set(Rr,r)),Rr[0]=null,Rr[1]=null,r},tR=P(({samples:i,radius:e,size:t,shadowPass:n,depthLayer:r})=>{const s=N(0).toVar("meanVertical"),o=N(0).toVar("squareMeanVertical"),a=i.lessThanEqual(N(1)).select(N(0),N(2).div(i.sub(1))),u=i.lessThanEqual(N(1)).select(N(0),N(-1));St({start:Me(0),end:Me(i),type:"int",condition:"<"},({i:c})=>{const d=u.add(N(c).mul(a));let h=n.sample(pt(ns.xy,j(0,d).mul(e)).div(t));n.value.isArrayTexture&&(h=h.depth(r)),h=h.x,s.addAssign(h),o.addAssign(h.mul(h))}),s.divAssign(i),o.divAssign(i);const l=fn(o.sub(s.mul(s)).max(0));return j(s,l)}),nR=P(({samples:i,radius:e,size:t,shadowPass:n,depthLayer:r})=>{const s=N(0).toVar("meanHorizontal"),o=N(0).toVar("squareMeanHorizontal"),a=i.lessThanEqual(N(1)).select(N(0),N(2).div(i.sub(1))),u=i.lessThanEqual(N(1)).select(N(0),N(-1));St({start:Me(0),end:Me(i),type:"int",condition:"<"},({i:c})=>{const d=u.add(N(c).mul(a));let h=n.sample(pt(ns.xy,j(d,0).mul(e)).div(t));n.value.isArrayTexture&&(h=h.depth(r)),s.addAssign(h.x),o.addAssign(pt(h.y.mul(h.y),h.x.mul(h.x)))}),s.divAssign(i),o.divAssign(i);const l=fn(o.sub(s.mul(s)).max(0));return j(s,l)}),rR=[qN,HN,XN,KN];let Ea;const wi=new kl;class bg extends ON{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:r,shadow:s,depthLayer:o}){const a=r.x.greaterThanEqual(0).and(r.x.lessThanEqual(1)).and(r.y.greaterThanEqual(0)).and(r.y.lessThanEqual(1)).and(r.z.lessThanEqual(1)),u=t({depthTexture:n,shadowCoord:r,shadow:s,depthLayer:o});return a.select(u,N(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:r}=e,s=Se("bias","float",n).setGroup(Q);let o=t,a;if(n.camera.isOrthographicCamera||r.logarithmicDepthBuffer!==!0)o=o.xyz.div(o.w),a=o.z,r.coordinateSystem===Gr&&(a=a.mul(2).sub(1));else{const u=o.w;o=o.xy.div(u);const l=Se("near","float",n.camera).setGroup(Q),c=Se("far","float",n.camera).setGroup(Q);a=$p(u.negate(),l,c)}return o=R(o.x,o.y.oneMinus(),a.add(s)),o}getShadowFilterFn(e){return rR[e]}setupRenderTarget(e,t){const n=new Qt(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=Ao;const r=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return r.texture.name="ShadowMap",r.texture.type=e.mapType,r.depthTexture=n,{shadowMap:r,depthTexture:n}}setupShadow(e){const{renderer:t,camera:n}=e,{light:r,shadow:s}=this,o=t.shadowMap.type,{depthTexture:a,shadowMap:u}=this.setupRenderTarget(s,e);if(s.camera.coordinateSystem=n.coordinateSystem,s.camera.updateProjectionMatrix(),o===ji&&s.isPointLightShadow!==!0){a.compareFunction=null,u.depth>1?(u._vsmShadowMapVertical||(u._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:hn,type:it,depth:u.depth,depthBuffer:!1}),u._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=u._vsmShadowMapVertical,u._vsmShadowMapHorizontal||(u._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:hn,type:it,depth:u.depth,depthBuffer:!1}),u._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=u._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:hn,type:it,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:hn,type:it,depthBuffer:!1}));let T=Pe(a);a.isArrayTexture&&(T=T.depth(this.depthLayer));let A=Pe(this.vsmShadowMapVertical.texture);a.isArrayTexture&&(A=A.depth(this.depthLayer));const B=Se("blurSamples","float",s).setGroup(Q),S=Se("radius","float",s).setGroup(Q),v=Se("mapSize","vec2",s).setGroup(Q);let E=this.vsmMaterialVertical||(this.vsmMaterialVertical=new ze);E.fragmentNode=tR({samples:B,radius:S,size:v,shadowPass:T,depthLayer:this.depthLayer}).context(e.getSharedContext()),E.name="VSMVertical",E=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new ze),E.fragmentNode=nR({samples:B,radius:S,size:v,shadowPass:A,depthLayer:this.depthLayer}).context(e.getSharedContext()),E.name="VSMHorizontal"}const l=Se("intensity","float",s).setGroup(Q),c=Se("normalBias","float",s).setGroup(Q),d=Gl(r).mul(yg.add(rs.mul(c))),h=this.setupShadowCoord(e,d),p=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(p===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=o===ji&&s.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:a,g=this.setupShadowFilter(e,{filterFn:p,shadowTexture:u.texture,depthTexture:f,shadowCoord:h,shadow:s,depthLayer:this.depthLayer});let m;u.texture.isCubeTexture?m=ut(u.texture,h.xyz):(m=Pe(u.texture,h),a.isArrayTexture&&(m=m.depth(this.depthLayer)));const y=Ne(1,g.rgb.mix(m,1),l.mul(m.a)).toVar();this.shadowMap=u,this.shadow.map=u;const _=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return y.toInspector(`${_} / Color`,()=>this.shadowMap.texture.isCubeTexture?ut(this.shadowMap.texture):Pe(this.shadowMap.texture)).toInspector(`${_} / Depth`,()=>this.shadowMap.texture.isCubeTexture?ut(this.shadowMap.texture).r.oneMinus():Tt(this.shadowMap.depthTexture,es().mul(ur(Pe(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(e.renderer.shadowMap.enabled!==!1)return P(()=>{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.shadowNode&&z('NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){const{shadow:t,shadowMap:n,light:r}=this,{renderer:s,scene:o}=e;t.updateMatrices(r),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);const a=o.name;o.name=`Shadow Map [ ${r.name||"ID: "+r.id} ]`,s.render(o,t.camera),o.name=a}updateShadow(e){const{shadowMap:t,light:n,shadow:r}=this,{renderer:s,scene:o,camera:a}=e,u=s.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const c=r.camera.layers.mask;(r.camera.layers.mask&4294967294)===0&&(r.camera.layers.mask=a.layers.mask);const d=s.getRenderObjectFunction(),h=s.getMRT(),p=h?h.has("velocity"):!1;Ea=WN(s,o,Ea),o.overrideMaterial=ZN(n),s.setRenderObjectFunction(eR(s,r,u,p)),s.setClearColor(0,0),s.setRenderTarget(t),this.renderShadow(e),s.setRenderObjectFunction(d),u===ji&&r.isPointLightShadow!==!0&&this.vsmPass(s),r.camera.layers.mask=c,jN(s,o,Ea)}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),wi.material=this.vsmMaterialVertical,wi.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),wi.material=this.vsmMaterialHorizontal,wi.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,JN(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 sR=(i,e)=>new bg(i,e),iR=new Ct,Dd=new Et,xs=new I,Ca=new I,oR=[new I(1,0,0),new I(-1,0,0),new I(0,-1,0),new I(0,1,0),new I(0,0,1),new I(0,0,-1)],aR=[new I(0,-1,0),new I(0,-1,0),new I(0,0,-1),new I(0,0,1),new I(0,-1,0),new I(0,-1,0)],uR=[new I(1,0,0),new I(-1,0,0),new I(0,1,0),new I(0,-1,0),new I(0,0,1),new I(0,0,-1)],lR=[new I(0,-1,0),new I(0,-1,0),new I(0,0,1),new I(0,0,-1),new I(0,-1,0),new I(0,-1,0)],cR=P(({depthTexture:i,bd3D:e,dp:t})=>ut(i,e).compare(t)),dR=P(({depthTexture:i,bd3D:e,dp:t,shadow:n})=>{const r=Se("radius","float",n).setGroup(Q),s=Se("mapSize","vec2",n).setGroup(Q),o=r.div(s.x),a=yt(e),u=Lt(fr(e,a.x.greaterThan(a.z).select(R(0,1,0),R(1,0,0)))),l=fr(e,u),c=dg(ns.xy).mul(6.28318530718),d=Xt(0,5,c),h=Xt(1,5,c),p=Xt(2,5,c),f=Xt(3,5,c),g=Xt(4,5,c);return ut(i,e.add(u.mul(d.x).add(l.mul(d.y)).mul(o))).compare(t).add(ut(i,e.add(u.mul(h.x).add(l.mul(h.y)).mul(o))).compare(t)).add(ut(i,e.add(u.mul(p.x).add(l.mul(p.y)).mul(o))).compare(t)).add(ut(i,e.add(u.mul(f.x).add(l.mul(f.y)).mul(o))).compare(t)).add(ut(i,e.add(u.mul(g.x).add(l.mul(g.y)).mul(o))).compare(t)).mul(1/5)}),hR=P(({filterFn:i,depthTexture:e,shadowCoord:t,shadow:n})=>{const r=t.xyz.toVar(),s=r.length(),o=Z("float").setGroup(Q).onRenderUpdate(()=>n.camera.near),a=Z("float").setGroup(Q).onRenderUpdate(()=>n.camera.far),u=Se("bias","float",n).setGroup(Q),l=N(1).toVar();return Re(s.sub(a).lessThanEqual(0).and(s.sub(o).greaterThanEqual(0)),()=>{const c=s.sub(o).div(a.sub(o)).toVar();c.addAssign(u);const d=r.normalize();l.assign(i({depthTexture:e,bd3D:d,dp:c,shadow:n}))}),l});class fR extends bg{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===oy?cR:dR}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:s}){return hR({filterFn:t,depthTexture:n,shadowCoord:r,shadow:s})}setupRenderTarget(e,t){const n=new ay(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=Ao;const r=t.createCubeRenderTarget(e.mapSize.width);return r.texture.name="PointShadowMap",r.depthTexture=n,{shadowMap:r,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:r}=this,{renderer:s,scene:o}=e,a=t.camera,u=t.matrix,l=s.coordinateSystem===Gr,c=l?oR:uR,d=l?aR:lR;n.setSize(t.mapSize.width,t.mapSize.width);const h=s.autoClear,p=s.getClearColor(iR),f=s.getClearAlpha();s.autoClear=!1,s.setClearColor(t.clearColor,t.clearAlpha);for(let g=0;g<6;g++){s.setRenderTarget(n,g),s.clear();const m=r.distance||a.far;m!==a.far&&(a.far=m,a.updateProjectionMatrix()),xs.setFromMatrixPosition(r.matrixWorld),a.position.copy(xs),Ca.copy(a.position),Ca.add(c[g]),a.up.copy(d[g]),a.lookAt(Ca),a.updateMatrixWorld(),u.makeTranslation(-xs.x,-xs.y,-xs.z),Dd.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(Dd,a.coordinateSystem,a.reversedDepth);const y=o.name;o.name=`Point Light Shadow [ ${r.name||"ID: "+r.id} ] - Face ${g+1}`,s.render(o,a),o.name=y}s.autoClear=h,s.setClearColor(p,f)}}const pR=(i,e)=>new fR(i,e);class mr extends ss{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Ct,this.colorNode=e&&e.colorNode||Z(this.color).setGroup(Q),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=oe.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 pg(this.light).sub(e.context.positionView||$e)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return sR(this.light)}setupShadow(e){const{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let n=this.shadowColorNode;if(n===null){const r=this.light.shadow.shadowNode;let s;r!==void 0?s=$(r):s=this.setupShadowNode(),this.shadowNode=s,this.shadowColorNode=n=this.colorNode.mul(s),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 _g=P(({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)}),gR=({color:i,lightVector:e,cutoffDistance:t,decayExponent:n})=>{const r=e.normalize(),s=e.length(),o=_g({lightDistance:s,cutoffDistance:t,decayExponent:n}),a=i.mul(o);return{lightDirection:r,lightColor:a}};class mR extends mr{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Z(0).setGroup(Q),this.decayExponentNode=Z(2).setGroup(Q)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return pR(this.light)}setupDirect(e){return gR({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}P(([i=es()],{renderer:e,material:t})=>{const n=lp(i.mul(2).sub(1));let r;if(t.alphaToCoverage&&e.currentSamples>0){const s=N(n.fwidth()).toVar();r=yn(s.oneMinus(),s.add(1),n).oneMinus()}else r=lt(n.greaterThan(1),0,1);return r});const yR=P(([i,e])=>{const t=i.x,n=i.y,r=i.z;let s=e.element(0).mul(.886227);return s=s.add(e.element(1).mul(2*.511664).mul(n)),s=s.add(e.element(2).mul(2*.511664).mul(r)),s=s.add(e.element(3).mul(2*.511664).mul(t)),s=s.add(e.element(4).mul(2*.429043).mul(t).mul(n)),s=s.add(e.element(5).mul(2*.429043).mul(n).mul(r)),s=s.add(e.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),s=s.add(e.element(7).mul(2*.429043).mul(t).mul(r)),s=s.add(e.element(8).mul(.429043).mul(ae(t,t).sub(ae(n,n)))),s}),Mt=new Il;class bR extends kn{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const r=this.renderer,s=this.nodes.getBackgroundNode(e)||e.background;let o=!1;if(s===null)r._clearColor.getRGB(Mt),Mt.a=r._clearColor.a;else if(s.isColor===!0)s.getRGB(Mt),Mt.a=1,o=!0;else if(s.isNode===!0){const u=this.get(e),l=s;Mt.copy(r._clearColor);let c=u.backgroundMesh;if(c===void 0){let _=function(){s.removeEventListener("dispose",_),c.material.dispose(),c.geometry.dispose()};const h=se(l).mul(Cd).context({getUV:()=>pN.mul(TT),getTextureLevel:()=>fN}),p=Gs.element(3).element(3).equal(1),f=Zt(1,Gs.element(1).element(1)).mul(3),g=p.select(Ke.mul(f),Ke);let m=Gs.mul(ri.mul(se(g,0)));m=m.setZ(m.w);const y=new ze;y.name="Background.material",y.side=ht,y.depthTest=!1,y.depthWrite=!1,y.allowOverride=!1,y.fog=!1,y.lights=!1,y.vertexNode=m,y.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=c=new Ut(new Zu(1,32,32),y),c.frustumCulled=!1,c.name="Background.mesh",s.addEventListener("dispose",_)}const d=l.getCacheKey();u.backgroundCacheKey!==d&&(u.backgroundMeshNode.node=se(l).mul(Cd),u.backgroundMeshNode.needsUpdate=!0,c.material.needsUpdate=!0,u.backgroundCacheKey=d),t.unshift(c,c.geometry,c.material,0,0,null,null)}else G("Renderer: Unsupported background configuration.",s);const a=r.xr.getEnvironmentBlendMode();if(a==="additive"?Mt.set(0,0,0,1):a==="alpha-blend"&&Mt.set(0,0,0,0),r.autoClear===!0||o===!0){const u=n.clearColorValue;u.r=Mt.r,u.g=Mt.g,u.b=Mt.b,u.a=Mt.a,(r.backend.isWebGLBackend===!0||r.alpha===!0)&&(u.r*=u.a,u.g*=u.a,u.b*=u.a),n.depthClearValue=r._clearDepth,n.stencilClearValue=r._clearStencil,n.clearColor=r.autoClearColor===!0,n.clearDepth=r.autoClearDepth===!0,n.clearStencil=r.autoClearStencil===!0}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let _R=0;class zu{constructor(e="",t=[],n=0,r=[]){this.name=e,this.bindings=t,this.index=n,this.bindingsReference=r,this.id=_R++}}class xR{constructor(e,t,n,r,s,o,a,u,l,c=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=c,this.nodeAttributes=r,this.bindings=s,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 r=new zu(t.name,[],t.index,t.bindingsReference);e.push(r);for(const s of t.bindings)r.bindings.push(s.clone())}else e.push(t);return e}}class Fd{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class TR{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 xg{constructor(e,t,n=!1,r=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=r}}class vR extends xg{constructor(e,t,n=null,r=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=r}}class SR{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let NR=0;class Ma{constructor(e=null){this.id=NR++,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 RR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class Gn{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class wR extends Gn{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class AR extends Gn{constructor(e,t=new ce){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class ER extends Gn{constructor(e,t=new I){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class CR extends Gn{constructor(e,t=new Oe){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class MR extends Gn{constructor(e,t=new Ct){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class PR extends Gn{constructor(e,t=new af){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class BR extends Gn{constructor(e,t=new Js){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class DR extends Gn{constructor(e,t=new Et){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class FR extends wR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class LR extends AR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class UR extends ER{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class OR extends CR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class IR extends MR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kR extends PR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class GR extends BR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class VR extends DR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let $R=0;const zR=new WeakMap,Ld=new WeakMap,WR=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Ai=i=>/e/g.test(i)?String(i).replace(/\+/g,""):(i=Number(i),i+(i%1?"":".0"));class Tg{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=Na(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Ma,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:$R++})}isOpaque(){const e=this.material;return e.transparent===!1&&e.blending===ir&&e.alphaToCoverage===!1}getBindGroupsCache(){let e=Ld.get(this.renderer);return e===void 0&&(e=new It,Ld.set(this.renderer,e)),e}createRenderTarget(e,t,n){return new Yr(e,t,n)}createCubeRenderTarget(e,t){return new qp(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=this.getBindGroupsCache(),r=[];let s=!0;for(const a of t)r.push(a),s=s&&a.groupNode.shared!==!0;let o;return s?(o=n.get(r),o===void 0&&(o=new zu(e,r,this.bindingsIndexes[e].group,r),n.set(r,o))):o=new zu(e,r,this.bindingsIndexes[e].group,r),o}getBindGroupArray(e,t){const n=this.bindings[t];let r=n[e];return r===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=r=[]),r}getBindings(){let e=this.bindGroups;if(e===null){const t={},n=this.bindings;for(const r of Ac)for(const s in n[r]){const o=n[r][s];(t[s]||(t[s]=[])).push(...o)}e=[];for(const r in t){const s=t[r],o=this._getBindGroup(r,s);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,n.index=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){this.sequentialNodes.includes(e)===!1&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes)e.getUpdateType()!==oe.NONE&&this.updateNodes.push(e);for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t!==oe.NONE&&this.updateBeforeNodes.push(e),n!==oe.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===Ot||e.magFilter===Qa||e.magFilter===qs||e.magFilter===sr||e.minFilter===Ot||e.minFilter===Qa||e.minFilter===qs||e.minFilter===sr}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 Ma(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 r=this.generateArrayDeclaration(e,t)+"( ";for(let s=0;s<t;s++){const o=n?n[s]:null;o!==null?r+=o.build(this,e):r+=this.generateConst(e),s<t-1&&(r+=", ")}return r+=" )",r}generateStruct(e,t,n=null){const r=[];for(const s of t){const{name:o,type:a}=s;n&&n[o]&&n[o].isNode?r.push(n[o].build(this,a)):r.push(this.generateConst(a))}return e+"( "+r.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new Ct:e==="vec2"||e==="uvec2"||e==="ivec2"?t=new ce:e==="vec3"||e==="uvec3"||e==="ivec3"?t=new I:(e==="vec4"||e==="uvec4"||e==="ivec4")&&(t=new Oe)),e==="float")return Ai(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")}( ${Ai(t.r)}, ${Ai(t.g)}, ${Ai(t.b)} )`;const n=this.getTypeLength(e),r=this.getComponentType(e),s=o=>this.generateConst(r,o);if(n===2)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)} )`;if(n===3)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)} )`;if(n===4&&e!=="mat2")return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)}, ${s(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(s).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 s of n)if(s.name===e)return s;const r=new Fd(e,t);return this.registerDeclaration(r),n.push(r),r}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===je)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=Pf(e);const r=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(n=n.replace("vec","mat")),r+n}getTypeFromArray(e){return WR.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,r=e.itemSize,s=e.normalized;let o;return!(e instanceof rf)&&s!==!0&&(o=this.getTypeFromArray(n)),this.getTypeFromLength(r,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=Na(this.stack);const e=Uf();return this.stacks.push(e),fo(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,fo(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){n=n===null?e.isGlobal(this)?this.globalCache:this.cache:n;let r=n.getData(e);r===void 0&&(r={},n.setData(e,r)),r[t]===void 0&&(r[t]={});let s=r[t];const o=r.any?r.any.subBuilds:null,a=this.getClosestSubBuild(o);return a&&(s.subBuildsCache===void 0&&(s.subBuildsCache={}),s=s.subBuildsCache[a]||(s.subBuildsCache[a]={}),s.subBuilds=o),s}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 r=n.bufferAttribute;if(r===void 0){const s=this.uniforms.index++;r=new Fd("nodeAttribute"+s,t,e),this.bufferAttributes.push(r),n.bufferAttribute=r}return r}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,r=this.shaderStage){const s=this.getDataFromNode(e,r,this.globalCache);let o=s.structType;if(o===void 0){const a=this.structs.index++;n===null&&(n="StructType"+a),o=new RR(n,t),this.structs[r].push(o),this.types[r][n]=e,s.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,r=null){const s=this.getDataFromNode(e,n,this.globalCache);let o=s.uniform;if(o===void 0){const a=this.uniforms.index++;o=new TR(r||"nodeUniform"+a,t,e),this.uniforms[n].push(o),this.registerDeclaration(o),s.uniform=o}return o}getVarFromNode(e,t=null,n=e.getNodeType(this),r=this.shaderStage,s=!1){const o=this.getDataFromNode(e,r),a=this.getSubBuildProperty("variable",o.subBuilds);let u=o[a];if(u===void 0){const l=s?"_const":"_var",c=this.vars[r]||(this.vars[r]=[]),d=this.vars[l]||(this.vars[l]=0);t===null&&(t=(s?"nodeConst":"nodeVar")+d,this.vars[l]++),a!=="variable"&&(t=this.getSubBuildProperty(t,o.subBuilds));const h=e.getArrayCount(this);u=new xg(t,n,s,h),s||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),r=null,s=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 vR(t,n,r,s),l.push(u),this.registerDeclaration(u),o[a]=u}return u}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),r=this.getPropertyName(e);let s=1,o=r;for(;n[o]!==void 0;)o=r+"_"+s++;s>1&&(e.name=o,z(`TSL: Declaration name '${r}' of '${e.type}' already in use. Renamed to '${o}'.`)),n[o]=e}getCodeFromNode(e,t,n=this.shaderStage){const r=this.getDataFromNode(e);let s=r.code;if(s===void 0){const o=this.codes[n]||(this.codes[n]=[]),a=o.length;s=new SR("nodeCode"+a,t),o.push(s),r.code=s}return s}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:r}=this.getDataFromNode(e);let s=!0,o=t;for(;o;){if(r.get(o)===!0){s=!1;break}o=this.getDataFromNode(o).parentNodeBlock}if(s)for(const a of n)this.addLineFlowCode(a)}addLineFlowCodeBlock(e,t,n){const r=this.getDataFromNode(e),s=r.flowCodes||(r.flowCodes=[]),o=r.flowCodeBlock||(r.flowCodeBlock=new WeakMap);s.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+`;
536
+ `),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 CN,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 oN(o.type,o.name);e.layout=null;const r=e.call(n),s=this.flowStagesNode(r,t.type);return e.layout=t,s}flowBuildStage(e,t,n=null){const r=this.getBuildStage();this.setBuildStage(t);const s=e.build(this,n);return this.setBuildStage(r),s}flowStagesNode(e,t=null){const n=this.flow,r=this.vars,s=this.declarations,o=this.cache,a=this.buildStage,u=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new Ma,this.stack=Na();for(const c of wc)this.setBuildStage(c),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=r,this.declarations=s,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,r={code:""};return this.flow=r,r.result=e.build(this,t),this.flow=n,r}flowNodeFromShaderStage(e,t,n=null,r=null){const s=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);r!==null&&(d.code+=`${this.tab+r} = ${d.result};
537
+ `),this.flowCode[e]=this.flowCode[e]+d.code,c=d}else c=t.build(this);return this.setShaderStage(a),this.cache=o,this.tab=s,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){let t="";const n=this.vars[e];if(n!==void 0)for(const r of n)t+=`${this.getVar(r.type,r.name)}; `;return t}getUniforms(){z("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(t!==void 0)for(const r of t)n+=r.code+`
538
+ `;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 r=t.length-1;r>=0;r--){const s=t[r];if(n.includes(s))return s}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 r;return n?r=e?n+"_"+e:n:r=e,r}build(){const{object:e,material:t,renderer:n}=this;if(t!==null){let r=n.library.fromMaterial(t);r===null&&(G(`NodeMaterial: Material "${t.type}" is not compatible.`),r=new ze),r.build(this)}else this.addFlow("compute",e);for(const r of wc){this.setBuildStage(r),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const s of Ac){this.setShaderStage(s);const o=this.flowNodes[s];for(const a of o)r==="generate"?this.flowNode(a):a.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=zR.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let r=n.cache;if(r===void 0){if(t==="float"||t==="int"||t==="uint")r=new FR(e);else if(t==="vec2"||t==="ivec2"||t==="uvec2")r=new LR(e);else if(t==="vec3"||t==="ivec3"||t==="uvec3")r=new UR(e);else if(t==="vec4"||t==="ivec4"||t==="uvec4")r=new OR(e);else if(t==="color")r=new IR(e);else if(t==="mat2")r=new kR(e);else if(t==="mat3")r=new GR(e);else if(t==="mat4")r=new VR(e);else throw new Error(`Uniform "${t}" not implemented.`);n.cache=r}return r}format(e,t,n){if(t=this.getVectorType(t),n=this.getVectorType(n),t===n||n===null||this.isReference(n))return e;const r=this.getTypeLength(t),s=this.getTypeLength(n);return r===16&&s===9?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:r===9&&s===4?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:r>4||s>4||s===0?e:r===s?`${this.getType(n)}( ${e} )`:r>s?(e=n==="bool"?`all( ${e} )`:`${e}.${"xyz".slice(0,s)}`,this.format(e,this.getTypeFromLength(s,this.getComponentType(t)),n)):s===4&&r>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:r===2?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(r===1&&s>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${No} - Node System
539
+ `}}class Ud{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===oe.FRAME){const r=this._getMaps(this.updateBeforeMap,n);if(r.frameId!==this.frameId){const s=r.frameId;r.frameId=this.frameId,e.updateBefore(this)===!1&&(r.frameId=s)}}else if(t===oe.RENDER){const r=this._getMaps(this.updateBeforeMap,n);if(r.renderId!==this.renderId){const s=r.renderId;r.renderId=this.renderId,e.updateBefore(this)===!1&&(r.renderId=s)}}else t===oe.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===oe.FRAME){const r=this._getMaps(this.updateAfterMap,n);r.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(r.frameId=this.frameId)}else if(t===oe.RENDER){const r=this._getMaps(this.updateAfterMap,n);r.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(r.renderId=this.renderId)}else t===oe.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===oe.FRAME){const r=this._getMaps(this.updateMap,n);r.frameId!==this.frameId&&e.update(this)!==!1&&(r.frameId=this.frameId)}else if(t===oe.RENDER){const r=this._getMaps(this.updateMap,n);r.renderId!==this.renderId&&e.update(this)!==!1&&(r.renderId=this.renderId)}else t===oe.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 Vl{constructor(e,t,n=null,r="",s=!1){this.type=e,this.name=t,this.count=n,this.qualifier=r,this.isConst=s}}Vl.isNodeFunctionInput=!0;class jR extends mr{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:gg(this.light),lightColor:e}}}const Pa=new Et,Ei=new Et;let Ts=null;class qR extends mr{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Z(new I).setGroup(Q),this.halfWidth=Z(new I).setGroup(Q),this.updateType=oe.RENDER}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;Ei.identity(),Pa.copy(t.matrixWorld),Pa.premultiply(n),Ei.extractRotation(Pa),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(Ei),this.halfHeight.value.applyMatrix4(Ei)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=Pe(Ts.LTC_FLOAT_1),n=Pe(Ts.LTC_FLOAT_2)):(t=Pe(Ts.LTC_HALF_1),n=Pe(Ts.LTC_HALF_2));const{colorNode:r,light:s}=this,o=pg(s);return{lightColor:r,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){Ts=e}}class $l extends mr{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Z(0).setGroup(Q),this.penumbraCosNode=Z(0).setGroup(Q),this.cutoffDistanceNode=Z(0).setGroup(Q),this.decayExponentNode=Z(0).setGroup(Q),this.colorNode=Z(this.color).setGroup(Q)}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:r}=this;return yn(n,r,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return n===void 0&&(n=DN(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:r,light:s}=this,o=this.getLightVector(e),a=o.normalize(),u=a.dot(gg(s)),l=this.getSpotAttenuation(e,u),c=o.length(),d=_g({lightDistance:c,cutoffDistance:n,decayExponent:r});let h=t.mul(l).mul(d),p,f;return s.colorNode?(f=this.getLightCoord(e),p=s.colorNode(f)):s.map&&(f=this.getLightCoord(e),p=Pe(s.map,f.xy).onRenderUpdate(()=>s.map)),p&&(h=f.mul(2).sub(1).abs().lessThan(1).all().select(h.mul(p),h)),{lightColor:h,lightDirection:a}}}class HR extends $l{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const n=this.light.iesMap;let r=null;if(n&&n.isTexture===!0){const s=t.acos().mul(1/Math.PI);r=Pe(n,j(s,0),0).r}else r=super.getSpotAttenuation(t);return r}}const XR=P(([i,e])=>{const t=i.abs().sub(e);return mn(Je(t,0)).add(Wr(Je(t.x,t.y),0))});class KR extends $l{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=N(0),n=this.penumbraCosNode,r=Gl(this.light).mul(e.context.positionWorld||qr);return Re(r.w.greaterThan(0),()=>{const s=r.xyz.div(r.w),o=XR(s.xy.sub(j(.5)),j(.5)),a=Zt(-1,at(1,Jf(n)).sub(1));t.assign(El(o.mul(-2).mul(a)))}),t}}class YR extends mr{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class QR extends mr{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=fg(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Z(new Ct).setGroup(Q)}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:r}=this,o=rs.dot(r).mul(.5).add(.5),a=Ne(n,t,o);e.context.irradiance.addAssign(a)}}class ZR extends mr{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let n=0;n<9;n++)t.push(new I);this.lightProbe=Dt(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=yR(rs,this.lightProbe);e.context.irradiance.addAssign(t)}}class vg{parseFunction(){z("Abstract function.")}}class zl{constructor(e,t,n="",r=""){this.type=e,this.inputs=t,this.name=n,this.precision=r}getCode(){z("Abstract function.")}}zl.isNodeFunction=!0;const JR=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,ew=/[a-z_0-9]+/ig,Od="#pragma main",tw=i=>{i=i.trim();const e=i.indexOf(Od),t=e!==-1?i.slice(e+Od.length):i,n=t.match(JR);if(n!==null&&n.length===5){const r=n[4],s=[];let o=null;for(;(o=ew.exec(r))!==null;)s.push(o);const a=[];let u=0;for(;u<s.length;){const f=s[u][0]==="const";f===!0&&u++;let g=s[u][0];g==="in"||g==="out"||g==="inout"?u++:g="";const m=s[u++][0];let y=Number.parseInt(s[u][0]);Number.isNaN(y)===!1?u++:y=null;const _=s[u++][0];a.push(new Vl(m,_,y,g,f))}const l=t.substring(n[0].length),c=n[3]!==void 0?n[3]:"",d=n[2],h=n[1]!==void 0?n[1]:"",p=e!==-1?i.slice(0,e):"";return{type:d,inputs:a,name:c,precision:h,inputsCode:r,blockCode:l,headerCode:p}}else throw new Error("FunctionNode: Function is not a GLSL code.")};class nw extends zl{constructor(e){const{type:t,inputs:n,name:r,precision:s,inputsCode:o,blockCode:a,headerCode:u}=tw(e);super(t,n,r,s),this.inputsCode=o,this.blockCode=a,this.headerCode=u}getCode(e=this.name){let t;const n=this.blockCode;if(n!==""){const{type:r,inputsCode:s,headerCode:o,precision:a}=this;let u=`${r} ${e} ( ${s.trim()} )`;a!==""&&(u=`${a} ${u}`),t=o+u+n}else t="";return t}}class rw extends vg{parseFunction(e){return new nw(e)}}const Id=new WeakMap,Wt=[],Sn=[];class sw extends kn{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new Ud,this.nodeBuilderCache=new Map,this.callHashCache=new It,this.groupsData=new It,this.cacheLib={}}updateGroup(e){const t=e.groupNode,n=t.name;if(n===Xf.name)return!0;if(n===Q.name){const s=this.get(e),o=this.nodeFrame.renderId;return s.renderId!==o?(s.renderId=o,!0):!1}if(n===T_.name){const s=this.get(e),o=this.nodeFrame.frameId;return s.frameId!==o?(s.frameId=o,!0):!1}Wt[0]=t,Wt[1]=e;let r=this.groupsData.get(Wt);return r===void 0&&this.groupsData.set(Wt,r={}),Wt.length=0,r.version!==t.version?(r.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let n=t.nodeBuilderState;if(n===void 0){const{nodeBuilderCache:r}=this,s=this.getForRenderCacheKey(e);if(n=r.get(s),n===void 0){const o=u=>{const l=this.backend.createNodeBuilder(e.object,this.renderer);return l.scene=e.scene,l.material=u,l.camera=e.camera,l.context.material=u,l.lightsNode=e.lightsNode,l.environmentNode=this.getEnvironmentNode(e.scene),l.fogNode=this.getFogNode(e.scene),l.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&l.enableMultiview(),l};let a=o(e.material);try{a.build()}catch(u){a=o(new ze),a.build(),G("TSL: "+u)}n=this._createNodeBuilderState(a),r.set(s,n)}n.usedTimes++,t.nodeBuilderState=n}return n}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;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 r=this.backend.createNodeBuilder(e,this.renderer);r.build(),n=this._createNodeBuilderState(r),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new xR(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){Wt[0]=e,Wt[1]=t;const n=this.renderer.info.calls,r=this.callHashCache.get(Wt)||{};if(r.callId!==n){const s=this.getEnvironmentNode(e),o=this.getFogNode(e);t&&Sn.push(t.getCacheKey(!0)),s&&Sn.push(s.getCacheKey()),o&&Sn.push(o.getCacheKey()),Sn.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Sn.push(this.renderer.shadowMap.enabled?1:0),Sn.push(this.renderer.shadowMap.type),r.callId=n,r.cacheKey=ei(Sn),this.callHashCache.set(Wt,r),Sn.length=0}return Wt.length=0,r.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const r=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==n||r){const s=this.getCacheNode("background",n,()=>{if(n.isCubeTexture===!0||n.mapping===rl||n.mapping===sl||n.mapping===Ya){if(e.backgroundBlurriness>0||n.mapping===Ya)return rg(n);{let o;return n.isCubeTexture===!0?o=ut(n):o=Pe(n),Xp(o)}}else{if(n.isTexture===!0)return Pe(n,Ir.flipY()).setUpdateMatrix(!0);n.isColor!==!0&&G("WebGPUNodes: Unsupported background configuration.",n)}},r);t.backgroundNode=s,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,r=!1){const s=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let o=s.get(t);return(o===void 0||r)&&(o=n(),s.set(t,o)),o}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const r=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const s=Se("color","color",n).setGroup(Q),o=Se("density","float",n).setGroup(Q);return Pd(s,PN(o))}else if(n.isFog){const s=Se("color","color",n).setGroup(Q),o=Se("near","float",n).setGroup(Q),a=Se("far","float",n).setGroup(Q);return Pd(s,MN(o,a))}else G("Renderer: Unsupported fog configuration.",n)});t.fogNode=r,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 r=this.getCacheNode("environment",n,()=>{if(n.isCubeTexture===!0)return ut(n);if(n.isTexture===!0)return Pe(n);G("Nodes: Unsupported environment configuration.",n)});t.environmentNode=r,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,r=null,s=null){const o=this.nodeFrame;return o.renderer=e,o.scene=t,o.object=n,o.camera=r,o.material=s,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}hasOutputChange(e){return Id.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),r=e.isArrayTexture?yN(e,R(Ir,ni("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Pe(e,Ir).renderOutput(t.toneMapping,t.currentColorSpace);return Id.set(e,n),r}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 r of n.updateNodes)t.updateNode(r)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const r of n.updateNodes)t.updateNode(r)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Ud,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Ba=new vo;class _o{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Js,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 r=e.length;for(let s=0;s<r;s++){Ba.copy(e[s]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const o=t[n+s],a=Ba.normal;o.x=-a.x,o.y=-a.y,o.z=-a.z,o.w=Ba.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 r=t.clippingPlanes,s=r.length;let o,a;if(this.clipIntersection?(o=this.intersectionPlanes,a=e.intersectionPlanes.length):(o=this.unionPlanes,a=e.unionPlanes.length),o.length!==a+s){o.length=a+s;for(let u=0;u<s;u++)o[a+u]=new Oe;n=!0}this.projectPlanes(r,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 _o(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class iw{constructor(e,t){this.bundleGroup=e,this.camera=t}}const vs=[];class ow{constructor(){this.bundles=new It}get(e,t){const n=this.bundles;vs[0]=e,vs[1]=t;let r=n.get(vs);return r===void 0&&(r=new iw(e,t),n.set(vs,r)),vs.length=0,r}dispose(){this.bundles=new It}}class Sg{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 r in e)t[r]=e[r]}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 aw=new mg,Ss=[];class uw extends It{constructor(){super()}createNode(e=[]){return new mg().setLights(e)}getNode(e,t){if(e.isQuadMesh)return aw;Ss[0]=e,Ss[1]=t;let n=this.get(Ss);return n===void 0&&(n=this.createNode(),this.set(Ss,n)),Ss.length=0,n}}class Es extends Yr{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 kd=new I,Gd=new I;class lw extends tl{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Ws,this._cameraL.viewport=new Oe,this._cameraR=new Ws,this._cameraR.viewport=new Oe,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new lm,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding=typeof XRWebGLBinding<"u",this._frameBufferTargets=null,this._createXRLayer=gw.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new ce,this._onSessionEvent=hw.bind(this),this._onSessionEnd=fw.bind(this),this._onInputSourcesChange=pw.bind(this),this._onAnimationFrame=mw.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,r,s,o,a,u={}){const l=new cm(e,t),c=new Es(s,o,{format:Ft,type:bt,depthTexture:new Qt(s,o,u.stencil?Bn:je,void 0,void 0,void 0,void 0,void 0,void 0,u.stencil?Dn:Fn),stencilBuffer:u.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const d=new An({color:16777215,side:Cs});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const h=new Ut(l,d);h.position.copy(n),h.quaternion.copy(r);const p={type:"quad",width:e,height:t,translation:n,quaternion:r,pixelwidth:s,pixelheight:o,plane:h,material:d,rendercall:a,renderTarget:c};if(this._layers.push(p),this._session!==null){p.plane.material=new An({color:16777215,side:Cs}),p.plane.material.blending=Ms,p.plane.material.blendEquation=an,p.plane.material.blendSrc=wn,p.plane.material.blendDst=wn,p.xrlayer=this._createXRLayer(p);const f=this._session.renderState.layers;f.unshift(p.xrlayer),this._session.updateRenderState({layers:f})}else c.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,n,r,s,o,a,u,l={}){const c=new xh(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),d=new Es(o,a,{format:Ft,type:bt,depthTexture:new Qt(o,a,l.stencil?Bn:je,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?Dn:Fn),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});d._autoAllocateDepthBuffer=!0;const h=new An({color:16777215,side:ht});h.map=d.texture,h.map.offset.y=1,h.map.repeat.y=-1;const p=new Ut(c,h);p.position.copy(r),p.quaternion.copy(s);const f={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:r,quaternion:s,pixelwidth:o,pixelheight:a,plane:p,material:h,rendercall:u,renderTarget:d};if(this._layers.push(f),this._session!==null){f.plane.material=new An({color:16777215,side:ht}),f.plane.material.blending=Ms,f.plane.material.blendEquation=an,f.plane.material.blendSrc=wn,f.plane.material.blendDst=wn,f.xrlayer=this._createXRLayer(f);const g=this._session.renderState.layers;g.unshift(f.xrlayer),this._session.updateRenderState({layers:g})}else d.isXRRenderTarget=!1;return p}renderLayers(){const e=new I,t=new kr,n=this._renderer,r=this.isPresenting,s=n.getOutputRenderTarget(),o=n._frameBufferTarget;this.isPresenting=!1;const a=new ce;n.getSize(a);const u=n._quad;for(const l of this._layers)if(l.renderTarget.isXRRenderTarget=this._session!==null,l.renderTarget._hasExternalTextures=l.renderTarget.isXRRenderTarget,l.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){l.xrlayer.transform=new XRRigidTransform(l.plane.getWorldPosition(e),l.plane.getWorldQuaternion(t));const c=this._glBinding.getSubImage(l.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(l.renderTarget,c.colorTexture,void 0),n._setXRLayerSize(l.renderTarget.width,l.renderTarget.height),n.setOutputRenderTarget(l.renderTarget),n.setRenderTarget(null),n._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:d,quad:h}=this._frameBufferTargets.get(l.renderTarget)||{frameBufferTarget:null,quad:null};d?(n._frameBufferTarget=d,n._quad=h):(n._quad=new kl(new ze),this._frameBufferTargets.set(l.renderTarget,{frameBufferTarget:n._getFrameBufferTarget(),quad:n._quad})),l.rendercall(),n._frameBufferTarget=null}else n.setRenderTarget(l.renderTarget),l.rendercall();n.setRenderTarget(null),n.setOutputRenderTarget(s),n._frameBufferTarget=o,n._setXRLayerSize(a.x,a.y),n._quad=u,this.isPresenting=r}getSession(){return this._session}async setSession(e){const t=this._renderer,n=t.backend;this._gl=t.getContext();const r=this._gl,s=r.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?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24,o=t.stencil?Dn:Fn,a=t.stencil?Bn:je);const l={colorFormat:r.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,p=new Qt(c.textureWidth,c.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,o,h);if(this._xrRenderTarget=new Es(c.textureWidth,c.textureHeight,{format:Ft,type:bt,colorSpace:t.outputColorSpace,depthTexture:p,stencilBuffer:t.stencil,samples:s.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 f of this._layers)f.plane.material=new An({color:16777215,side:f.type==="cylinder"?ht:Cs}),f.plane.material.blending=Ms,f.plane.material.blendEquation=an,f.plane.material.blendSrc=wn,f.plane.material.blendDst=wn,f.xrlayer=this._createXRLayer(f),d.unshift(f.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,r,o);this._glBaseLayer=a,e.updateRenderState({baseLayer:a}),t.setPixelRatio(1),t._setXRLayerSize(a.framebufferWidth,a.framebufferHeight),this._xrRenderTarget=new Es(a.framebufferWidth,a.framebufferHeight,{format:Ft,type:bt,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,r=e.far,s=this._cameraXR,o=this._cameraL,a=this._cameraR;s.near=a.near=o.near=n,s.far=a.far=o.far=r,s.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==s.near||this._currentDepthFar!==s.far)&&(t.updateRenderState({depthNear:s.near,depthFar:s.far}),this._currentDepthNear=s.near,this._currentDepthFar=s.far),s.layers.mask=e.layers.mask|6,o.layers.mask=s.layers.mask&3,a.layers.mask=s.layers.mask&5;const u=e.parent,l=s.cameras;Vd(s,u);for(let c=0;c<l.length;c++)Vd(l[c],u);l.length===2?cw(s,o,a):s.projectionMatrix.copy(o.projectionMatrix),dw(e,s,u)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new dm,this._controllers[e]=t),t}}function cw(i,e,t){kd.setFromMatrixPosition(e.matrixWorld),Gd.setFromMatrixPosition(t.matrixWorld);const n=kd.distanceTo(Gd),r=e.projectionMatrix.elements,s=t.projectionMatrix.elements,o=r[14]/(r[10]-1),a=r[14]/(r[10]+1),u=(r[9]+1)/r[5],l=(r[9]-1)/r[5],c=(r[8]-1)/r[0],d=(s[8]+1)/s[0],h=o*c,p=o*d,f=n/(-c+d),g=f*-c;if(e.matrixWorld.decompose(i.position,i.quaternion,i.scale),i.translateX(g),i.translateZ(f),i.matrixWorld.compose(i.position,i.quaternion,i.scale),i.matrixWorldInverse.copy(i.matrixWorld).invert(),r[10]===-1)i.projectionMatrix.copy(e.projectionMatrix),i.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const m=o+f,y=a+f,_=h-g,T=p+(n-g),A=u*a/y*m,B=l*a/y*m;i.projectionMatrix.makePerspective(_,T,A,B,m,y),i.projectionMatrixInverse.copy(i.projectionMatrix).invert()}}function Vd(i,e){e===null?i.matrixWorld.copy(i.matrix):i.matrixWorld.multiplyMatrices(e.matrixWorld,i.matrix),i.matrixWorldInverse.copy(i.matrixWorld).invert()}function dw(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=Pm*2*Math.atan(1/i.projectionMatrix.elements[5]),i.zoom=1)}function hw(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 fw(){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 Es(t.pixelwidth,t.pixelheight,{format:Ft,type:bt,depthTexture:new Qt(t.pixelwidth,t.pixelheight,t.stencilBuffer?Bn:je,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?Dn:Fn),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 pw(i){const e=this._controllers,t=this._controllerInputSources;for(let n=0;n<i.removed.length;n++){const r=i.removed[n],s=t.indexOf(r);s>=0&&(t[s]=null,e[s].disconnect(r))}for(let n=0;n<i.added.length;n++){const r=i.added[n];let s=t.indexOf(r);if(s===-1){for(let a=0;a<e.length;a++)if(a>=t.length){t.push(r),s=a;break}else if(t[a]===null){t[a]=r,s=a;break}if(s===-1)break}const o=e[s];o&&o.connect(r)}}function gw(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 mw(i,e){if(e===void 0)return;const t=this._cameraXR,n=this._renderer,r=n.backend,s=this._glBaseLayer,o=this.getReferenceSpace(),a=e.getViewerPose(o);if(this._xrFrame=e,a!==null){const u=a.views;this._glBaseLayer!==null&&r.setXRTarget(s.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 f=this._glBinding.getViewSubImage(this._glProjLayer,d);h=f.viewport,c===0&&r.setXRRenderTargetTextures(this._xrRenderTarget,f.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:f.depthStencilTexture)}else h=s.getViewport(d);let p=this._cameras[c];p===void 0&&(p=new Ws,p.layers.enable(c),p.viewport=new Oe,this._cameras[c]=p),p.matrix.fromArray(d.transform.matrix),p.matrix.decompose(p.position,p.quaternion,p.scale),p.projectionMatrix.fromArray(d.projectionMatrix),p.projectionMatrixInverse.copy(p.projectionMatrix).invert(),p.viewport.set(h.x,h.y,h.width,h.height),c===0&&(t.matrix.copy(p.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),l===!0&&t.cameras.push(p)}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 yw extends tl{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Oe(0,0,this._width,this._height),this._scissor=new Oe(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Rh,this.depthTexture=new Qt}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,r){const s=this._scissor;e.isVector4?s.copy(e):s.set(e,t,n,r)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,r,s=0,o=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,r),a.minDepth=s,a.maxDepth=o}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const $d=new So,wr=new ce,Da=new Oe,Fa=new Zg,La=new Qg,Ci=new Et,sn=new Oe;class bw{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,alpha:r=!0,depth:s=!0,stencil:o=!1,antialias:a=!1,samples:u=0,getFallback:l=null,outputBufferType:c=it,multiview:d=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=n,this.outputColorSpace=Ju,this.toneMapping=tr,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=s,this.stencil=o,this.info=new WS,this.contextNode=gr(),this.library=new Sg,this.lighting=new uw,this._samples=u||a===!0?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new yw(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new bp,this._inspector.setRenderer(this),this._getFallback=l,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._quad=new kl(new ze),this._quad.name="Output Color Transform",this._quad.material.name="outputColorTransform",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const h=this.alpha===!0?0:1;this._clearColor=new Il(0,0,0,h),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=c,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:Yg},this.xr=new lw(this,d),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(p,f,g)=>{await this.compileAsync(p,f);const m=this._renderLists.get(p,f),y=this._renderContexts.get(p,f,this._renderTarget,this._mrt),_=p.overrideMaterial||g.material,T=this._objects.get(g,_,p,f,m.lightsNode,y,y.clippingContext),{fragmentShader:A,vertexShader:B}=T.getNodeBuilderState();return{fragmentShader:A,vertexShader:B}}}}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(r){if(this._getFallback!==null)try{this.backend=n=this._getFallback(r),await n.init(this)}catch(s){t(s);return}else{t(r);return}}this._nodes=new sw(this,n),this._animation=new LS(this,this._nodes,this.info),this._attributes=new $S(n),this._background=new bR(this,this._nodes),this._geometries=new zS(this._attributes,this.info),this._textures=new iN(this,n,this.info),this._pipelines=new XS(n,this._nodes),this._bindings=new KS(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new kS(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new ZS(this.lighting),this._bundles=new ow,this._renderContexts=new rN,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 r=this._nodes.nodeFrame,s=r.renderId,o=this._currentRenderContext,a=this._currentRenderObjectFunction,u=this._compilationPromises,l=e.isScene===!0?e:$d;n===null&&(n=e);const c=this._renderTarget,d=this._renderContexts.get(n,t,c,this._mrt),h=this._activeMipmapLevel,p=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,r.renderId++,r.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new _o),d.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,c);const f=this._renderLists.get(e,t);if(f.begin(),this._projectObject(e,t,0,f,d.clippingContext),n!==e&&n.traverseVisible(function(T){T.isLight&&T.layers.test(t.layers)&&f.pushLight(T)}),f.finish(),c!==null){this._textures.updateRenderTarget(c,h);const T=this._textures.get(c);d.textures=T.textures,d.depthTexture=T.depthTexture}else d.textures=null,d.depthTexture=null;this._background.update(l,f,d);const g=f.opaque,m=f.transparent,y=f.transparentDoublePass,_=f.lightsNode;this.opaque===!0&&g.length>0&&this._renderObjects(g,t,l,_),this.transparent===!0&&m.length>0&&this._renderTransparents(m,y,t,l,_),r.renderId=s,this._currentRenderContext=o,this._currentRenderObjectFunction=a,this._compilationPromises=u,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(p)}async renderAsync(e,t){Ge('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){G("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=Vc,t.modelNormalViewMatrix=$c):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Vc&&e.modelNormalViewMatrix===$c}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Ge('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
540
+
541
+ Message: ${e.message}`;e.reason&&(t+=`
542
+ Reason: ${e.reason}`),G(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:r,camera:s,renderList:o}=e,a=this._currentRenderContext,u=this._bundles.get(r,s),l=this.backend.get(u);l.renderContexts===void 0&&(l.renderContexts=new Set);const c=r.version!==l.version,d=l.renderContexts.has(a)===!1||c;if(l.renderContexts.add(a),d){this.backend.beginBundle(a),(l.renderObjects===void 0||c)&&(l.renderObjects=[]),this._currentRenderBundle=u;const{transparentDoublePass:h,transparent:p,opaque:f}=o;this.opaque===!0&&f.length>0&&this._renderObjects(f,s,t,n),this.transparent===!0&&p.length>0&&this._renderTransparents(p,h,s,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,u),l.version=r.version}else{const{renderObjects:h}=l;for(let p=0,f=h.length;p<f;p++){const g=h[p];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!==tr,r=t!==Ve.workingColorSpace;if(n===!1&&r===!1)return null;const{width:s,height:o}=this.getDrawingBufferSize(wr),{depth:a,stencil:u}=this;let l=this._frameBufferTarget;l===null&&(l=new Yr(s,o,{depthBuffer:a,stencilBuffer:u,type:this._outputBufferType,format:Ft,colorSpace:Ve.workingColorSpace,generateMipmaps:!1,minFilter:Ot,magFilter:Ot,samples:this.samples}),l.isPostProcessingRenderTarget=!0,this._frameBufferTarget=l);const c=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=u,c!==null?l.setSize(c.width,c.height,c.depth):l.setSize(s,o,1);const d=this._canvasTarget;return l.viewport.copy(d._viewport),l.scissor.copy(d._scissor),l.viewport.multiplyScalar(d._pixelRatio),l.scissor.multiplyScalar(d._pixelRatio),l.scissorTest=d._scissorTest,l.multiview=c!==null?c.multiview:!1,l.resolveDepthBuffer=c!==null?c.resolveDepthBuffer:!0,l._autoAllocateDepthBuffer=c!==null?c._autoAllocateDepthBuffer:!1,l}_renderScene(e,t,n=!0){if(this._isDeviceLost===!0)return;const r=n?this._getFrameBufferTarget():null,s=this._nodes.nodeFrame,o=s.renderId,a=this._currentRenderContext,u=this._currentRenderObjectFunction,l=e.isScene===!0?e:$d,c=this._renderTarget||this._outputRenderTarget,d=this._activeCubeFace,h=this._activeMipmapLevel;let p;r!==null?(p=r,this.setRenderTarget(p)):p=c;const f=this._renderContexts.get(e,t,p,this._mrt);this._currentRenderContext=f,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(f),this.inspector.beginRender(this.backend.getTimestampUID(f),e,t,p);const g=this.coordinateSystem,m=this.xr;if(t.coordinateSystem!==g&&m.isPresenting===!1&&(t.coordinateSystem=g,t.updateProjectionMatrix(),t.isArrayCamera))for(const ne of t.cameras)ne.coordinateSystem=g,ne.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,A=y._pixelRatio;p!==null&&(_=p.viewport,T=p.scissor,A=1),this.getDrawingBufferSize(wr),Da.set(0,0,wr.width,wr.height);const B=_.minDepth===void 0?0:_.minDepth,S=_.maxDepth===void 0?1:_.maxDepth;f.viewportValue.copy(_).multiplyScalar(A).floor(),f.viewportValue.width>>=h,f.viewportValue.height>>=h,f.viewportValue.minDepth=B,f.viewportValue.maxDepth=S,f.viewport=f.viewportValue.equals(Da)===!1,f.scissorValue.copy(T).multiplyScalar(A).floor(),f.scissor=y._scissorTest&&f.scissorValue.equals(Da)===!1,f.scissorValue.width>>=h,f.scissorValue.height>>=h,f.clippingContext||(f.clippingContext=new _o),f.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const v=t.isArrayCamera?La:Fa;t.isArrayCamera||(Ci.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(Ci,t.coordinateSystem,t.reversedDepth));const E=this._renderLists.get(e,t);if(E.begin(),this._projectObject(e,t,0,E,f.clippingContext),E.finish(),this.sortObjects===!0&&E.sort(this._opaqueSort,this._transparentSort),p!==null){this._textures.updateRenderTarget(p,h);const ne=this._textures.get(p);f.textures=ne.textures,f.depthTexture=ne.depthTexture,f.width=ne.width,f.height=ne.height,f.renderTarget=p,f.depth=p.depthBuffer,f.stencil=p.stencilBuffer}else f.textures=null,f.depthTexture=null,f.width=wr.width,f.height=wr.height,f.depth=this.depth,f.stencil=this.stencil;f.width>>=h,f.height>>=h,f.activeCubeFace=d,f.activeMipmapLevel=h,f.occlusionQueryCount=E.occlusionQueryCount,f.scissorValue.max(sn.set(0,0,0,0)),f.scissorValue.x+f.scissorValue.width>f.width&&(f.scissorValue.width=Math.max(f.width-f.scissorValue.x,0)),f.scissorValue.y+f.scissorValue.height>f.height&&(f.scissorValue.height=Math.max(f.height-f.scissorValue.y,0)),this._background.update(l,E,f),f.camera=t,this.backend.beginRender(f);const{bundles:D,lightsNode:O,transparentDoublePass:Y,transparent:ee,opaque:te}=E;return D.length>0&&this._renderBundles(D,l,O),this.opaque===!0&&te.length>0&&this._renderObjects(te,t,l,O),this.transparent===!0&&ee.length>0&&this._renderTransparents(ee,Y,t,l,O),this.backend.finishRender(f),s.renderId=o,this._currentRenderContext=a,this._currentRenderObjectFunction=u,r!==null&&(this.setRenderTarget(c,d,h),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(f)),f}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const n=this.autoClear,r=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=n,this.xr.enabled=r}getMaxAnisotropy(){return this.backend.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){return await this.backend.getArrayBufferAsync(e)}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,r){this._canvasTarget.setScissor(e,t,n,r)}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,r,s=0,o=1){this._canvasTarget.setViewport(e,t,n,r,s,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._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 r=this._renderTarget||this._getFrameBufferTarget();let s=null;if(r!==null){this._textures.updateRenderTarget(r);const o=this._textures.get(r);s=this._renderContexts.getForClear(r),s.textures=o.textures,s.depthTexture=o.depthTexture,s.width=o.width,s.height=o.height,s.renderTarget=r,s.depth=r.depthBuffer,s.stencil=r.stencilBuffer,s.clearColorValue=this.backend.getClearColor(),s.activeCubeFace=this.getActiveCubeFace(),s.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,n,s),r!==null&&this._renderTarget===null&&this._renderOutput(r)}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){Ge('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(){Ge('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Ge('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Ge('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!==tr,t=this.currentColorSpace!==Ve.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:tr}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Ve.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){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(),this._frameBufferTarget!==null&&this._frameBufferTarget.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),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}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,r=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 s=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.");s.beginCompute(e);for(const c of l){if(o.has(c)===!1){const p=()=>{c.removeEventListener("dispose",p),o.delete(c),a.deleteForCompute(c),u.delete(c)};c.addEventListener("dispose",p);const f=c.onInitFunction;f!==null&&f.call(c,{renderer:this})}u.updateForCompute(c),a.updateForCompute(c);const d=a.getForCompute(c),h=o.getForCompute(c,d);s.compute(e,c,d,h,t)}s.finishCompute(e),n.renderId=r,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 Ge('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){Ge('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)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=sn.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=sn.copy(t).floor();else{G("Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=sn.set(0,0,e.image.width,e.image.height);let n=this._currentRenderContext,r;n!==null?r=n.renderTarget:(r=this._renderTarget||this._getFrameBufferTarget(),r!==null&&(this._textures.updateRenderTarget(r),n=this._textures.get(r))),this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,r=null,s=0,o=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,r,s,o),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,r,s,o=0,a=0){return this.backend.copyTextureToBuffer(e.textures[o],t,n,r,s,a)}_projectObject(e,t,n,r,s){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(s=s.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){const u=t.isArrayCamera?La:Fa;if(!e.frustumCulled||u.intersectsSprite(e,t)){this.sortObjects===!0&&sn.setFromMatrixPosition(e.matrixWorld).applyMatrix4(Ci);const{geometry:l,material:c}=e;c.visible&&r.push(e,l,c,n,sn.z,null,s)}}else if(e.isLineLoop)G("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?La:Fa;if(!e.frustumCulled||u.intersectsObject(e,t)){const{geometry:l,material:c}=e;if(this.sortObjects===!0&&(l.boundingSphere===null&&l.computeBoundingSphere(),sn.copy(l.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(Ci)),Array.isArray(c)){const d=l.groups;for(let h=0,p=d.length;h<p;h++){const f=d[h],g=c[f.materialIndex];g&&g.visible&&r.push(e,l,g,n,sn.z,f,s)}}else c.visible&&r.push(e,l,c,n,sn.z,null,s)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){const u=r;r=this._renderLists.get(e,t),r.begin(),u.pushBundle({bundleGroup:e,camera:t,renderList:r}),r.finish()}const a=e.children;for(let u=0,l=a.length;u<l;u++)this._projectObject(a[u],t,n,r,s)}_renderBundles(e,t,n){for(const r of e)this._renderBundle(r,t,n)}_renderTransparents(e,t,n,r,s){if(t.length>0){for(const{material:o}of t)o.side=ht;this._renderObjects(t,n,r,s,"backSide");for(const{material:o}of t)o.side=Cs;this._renderObjects(e,n,r,s);for(const{material:o}of t)o.side=rr}else this._renderObjects(e,n,r,s)}_renderObjects(e,t,n,r,s=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,r,h,s)}}_getShadowNodes(e){const t=e.version;let n=this._cacheShadowNodes.get(e);if(n===void 0||n.version!==t){const r=e.map!==null,s=e.colorNode&&e.colorNode.isNode,o=e.castShadowNode&&e.castShadowNode.isNode;let a=null,u=null,l=null;if(r||s||o){let c,d;o?(c=e.castShadowNode.rgb,d=e.castShadowNode.a):(c=R(0),d=N(1)),r&&(d=d.mul(Se("map","texture",e).a)),s&&(d=d.mul(e.colorNode.a)),u=se(c,d)}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?a=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(a=e.positionNode),n={version:t,colorNode:u,depthNode:l,positionNode:a},this._cacheShadowNodes.set(e,n)}return n}renderObject(e,t,n,r,s,o,a,u=null,l=null){let c=!1,d,h,p,f;if(e.onBeforeRender(this,t,n,r,s,o),s.allowOverride===!0&&t.overrideMaterial!==null){const g=t.overrideMaterial;if(c=!0,d=t.overrideMaterial.colorNode,h=t.overrideMaterial.depthNode,p=t.overrideMaterial.positionNode,f=t.overrideMaterial.side,s.positionNode&&s.positionNode.isNode&&(g.positionNode=s.positionNode),g.alphaTest=s.alphaTest,g.alphaMap=s.alphaMap,g.transparent=s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode,g.isShadowPassMaterial){const{colorNode:m,depthNode:y,positionNode:_}=this._getShadowNodes(s);g.side=s.shadowSide===null?s.side:s.shadowSide,m!==null&&(g.colorNode=m),y!==null&&(g.depthNode=y),_!==null&&(g.positionNode=_)}s=g}s.transparent===!0&&s.side===rr&&s.forceSinglePass===!1?(s.side=ht,this._handleObjectFunction(e,s,t,n,a,o,u,"backSide"),s.side=Cs,this._handleObjectFunction(e,s,t,n,a,o,u,l),s.side=rr):this._handleObjectFunction(e,s,t,n,a,o,u,l),c&&(t.overrideMaterial.colorNode=d,t.overrideMaterial.depthNode=h,t.overrideMaterial.positionNode=p,t.overrideMaterial.side=f),e.onAfterRender(this,t,n,r,s,o)}_renderObjectDirect(e,t,n,r,s,o,a,u){const l=this._objects.get(e,t,n,r,s,this._currentRenderContext,a,u);l.drawRange=e.geometry.drawRange,l.group=o;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._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup),this.backend.draw(l,this.info),c&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,n,r,s,o,a,u){const l=this._objects.get(e,t,n,r,s,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 Ng{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 _w(i){return i+(Cn-i%Cn)%Cn}class Rg extends Ng{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 _w(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}}class wg extends Rg{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let xw=0;class Ag extends wg{constructor(e,t){super("UniformBuffer_"+xw++,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 Tw extends wg{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}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,r=this.uniforms.length;n<r;n++){const s=this.uniforms[n],o=s.boundary,a=s.itemSize*e,u=t%Cn,l=u%o,c=u+l;t+=l,c!==0&&Cn-c<a&&(t+=Cn-c),s.offset=t/e,t+=a}return Math.ceil(t/Cn)*Cn}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);G("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,r=e.getValue(),s=e.offset,o=e.getType();if(n[s]!==r){const a=this._getBufferForType(o);a[s]=n[s]=r,t=!0}return t}updateVector2(e){let t=!1;const n=this.values,r=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==r.x||n[s+1]!==r.y){const a=this._getBufferForType(o);a[s+0]=n[s+0]=r.x,a[s+1]=n[s+1]=r.y,t=!0}return t}updateVector3(e){let t=!1;const n=this.values,r=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==r.x||n[s+1]!==r.y||n[s+2]!==r.z){const a=this._getBufferForType(o);a[s+0]=n[s+0]=r.x,a[s+1]=n[s+1]=r.y,a[s+2]=n[s+2]=r.z,t=!0}return t}updateVector4(e){let t=!1;const n=this.values,r=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==r.x||n[s+1]!==r.y||n[s+2]!==r.z||n[s+4]!==r.w){const a=this._getBufferForType(o);a[s+0]=n[s+0]=r.x,a[s+1]=n[s+1]=r.y,a[s+2]=n[s+2]=r.z,a[s+3]=n[s+3]=r.w,t=!0}return t}updateColor(e){let t=!1;const n=this.values,r=e.getValue(),s=e.offset;if(n[s+0]!==r.r||n[s+1]!==r.g||n[s+2]!==r.b){const o=this.buffer;o[s+0]=n[s+0]=r.r,o[s+1]=n[s+1]=r.g,o[s+2]=n[s+2]=r.b,t=!0}return t}updateMatrix3(e){let t=!1;const n=this.values,r=e.getValue().elements,s=e.offset;if(n[s+0]!==r[0]||n[s+1]!==r[1]||n[s+2]!==r[2]||n[s+4]!==r[3]||n[s+5]!==r[4]||n[s+6]!==r[5]||n[s+8]!==r[6]||n[s+9]!==r[7]||n[s+10]!==r[8]){const o=this.buffer;o[s+0]=n[s+0]=r[0],o[s+1]=n[s+1]=r[1],o[s+2]=n[s+2]=r[2],o[s+4]=n[s+4]=r[3],o[s+5]=n[s+5]=r[4],o[s+6]=n[s+6]=r[5],o[s+8]=n[s+8]=r[6],o[s+9]=n[s+9]=r[7],o[s+10]=n[s+10]=r[8],t=!0}return t}updateMatrix4(e){let t=!1;const n=this.values,r=e.getValue().elements,s=e.offset;return Sw(n,r,s)===!1&&(this.buffer.set(r,s),vw(n,r,s),t=!0),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 vw(i,e,t){for(let n=0,r=e.length;n<r;n++)i[t+n]=e[n]}function Sw(i,e,t){for(let n=0,r=e.length;n<r;n++)if(i[t+n]!==e[n])return!1;return!0}let Nw=0;class Eg extends Tw{constructor(e,t){super(e),this.id=Nw++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class Cg extends Ng{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=0},this.texture=t,this.version=t?t.version:0,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=0,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=0},e.texture=this.texture,e}}let Rw=0;class ww extends Cg{constructor(e,t){super(e,t),this.id=Rw++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class Go extends ww{constructor(e,t,n,r=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class Mg extends Go{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledCubeTexture=!0}}class Wu extends Go{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledTexture3D=!0}}const zd={bitcast_int_uint:new Qe("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new Qe("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},Aw={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"},Ew={low:"lowp",medium:"mediump",high:"highp"},Wd={swizzleAssign:!0,storageBuffer:!1},jd={perspective:"smooth",linear:"noperspective"},qd={centroid:"centroid"},Hd=`
543
+ precision highp float;
544
+ precision highp int;
545
+ precision highp sampler2D;
546
+ precision highp sampler3D;
547
+ precision highp samplerCube;
548
+ precision highp sampler2DArray;
549
+
550
+ precision highp usampler2D;
551
+ precision highp usampler3D;
552
+ precision highp usamplerCube;
553
+ precision highp usampler2DArray;
554
+
555
+ precision highp isampler2D;
556
+ precision highp isampler3D;
557
+ precision highp isamplerCube;
558
+ precision highp isampler2DArray;
559
+
560
+ precision lowp sampler2DShadow;
561
+ precision lowp sampler2DArrayShadow;
562
+ precision lowp samplerCubeShadow;
563
+ `;class Cw extends Tg{constructor(e,t){super(e,t,new rw),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==Vr}_include(e){const t=zd[e];return t.build(this),this.addInclude(t),t}getMethod(e){return zd[e]!==void 0&&this._include(e),Aw[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),r=[];for(const o of t.inputs)r.push(this.getType(o.type)+" "+o.name);return`${this.getType(t.type)} ${t.name}( ${r.join(", ")} ) {
564
+
565
+ ${n.vars}
566
+
567
+ ${n.code}
568
+ return ${n.result};
569
+
570
+ }`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const n=t.array,r=t.count*t.itemSize,{itemSize:s}=t,o=t.array.constructor.name.toLowerCase().includes("int");let a=o?al:ol;s===2?a=o?ul:hn:s===3?a=o?Jm:il:s===4&&(a=o?ll:Ft);const u={Float32Array:vt,Uint8Array:bt,Uint16Array:Pr,Uint32Array:je,Int8Array:Ps,Int16Array:Bs,Int32Array:st,Uint8ClampedArray:bt},l=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let c=Math.ceil(r/s/l);l*c*s<r&&c++;const d=l*c*s,h=new n.constructor(d);h.set(n,0),t.array=h;const p=new nf(t.array,l,c,a,u[t.array.constructor.name]||vt);p.needsUpdate=!0,p.isPBOTexture=!0;const f=new ts(p,null,null);f.setPrecision("high"),t.pboNode=f,t.pbo=f.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?t.charAt(0)+"_"+e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:n}=e,r=t.value;if(this.renderer.backend.has(r)){const c=this.renderer.backend.get(r);c.pbo=r.pbo}const s=this.getUniformFromNode(r.pboNode,"texture",this.shaderStage,this.context.nodeName),o=this.getPropertyName(s);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:p}=r,f="."+Zr.join("").slice(0,p),g=`ivec2(${a} % ${h}, ${a} / ${h})`,m=this.generateTextureLoad(null,o,g,"0",null,null);let y="vec4";r.pbo.type===je?y="uvec4":r.pbo.type===st&&(y="ivec4"),this.addLineFlowCode(`${l} = ${y}(${m})${f}`,e),u.propertyName=l}return l}generateTextureLoad(e,t,n,r,s,o){r===null&&(r="0");let a;return s?o?a=`texelFetchOffset( ${t}, ivec3( ${n}, ${s} ), ${r}, ${o} )`:a=`texelFetch( ${t}, ivec3( ${n}, ${s} ), ${r} )`:o?a=`texelFetchOffset( ${t}, ${n}, ${r}, ${o} )`:a=`texelFetch( ${t}, ${n}, ${r} )`,e!==null&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,n,r,s){return r&&(n=`vec3( ${n}, ${r} )`),e.isDepthTexture?s?`textureOffset( ${t}, ${n}, ${s} ).x`:`texture( ${t}, ${n} ).x`:s?`textureOffset( ${t}, ${n}, ${s} )`:`texture( ${t}, ${n} )`}generateTextureLevel(e,t,n,r,s){return s?`textureLodOffset( ${t}, ${n}, ${r}, ${s} )`:`textureLod( ${t}, ${n}, ${r} )`}generateTextureBias(e,t,n,r,s){return s?`textureOffset( ${t}, ${n}, ${s}, ${r} )`:`texture( ${t}, ${n}, ${r} )`}generateTextureGrad(e,t,n,r,s){return s?`textureGradOffset( ${t}, ${n}, ${r[0]}, ${r[1]}, ${s} )`:`textureGrad( ${t}, ${n}, ${r[0]}, ${r[1]} )`}generateTextureCompare(e,t,n,r,s,o,a=this.shaderStage){if(a==="fragment")return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${r} ) )`:s?o?`textureOffset( ${t}, vec4( ${n}, ${s}, ${r} ), ${o} )`:`texture( ${t}, vec4( ${n}, ${s}, ${r} ) )`:o?`textureOffset( ${t}, vec3( ${n}, ${r} ), ${o} )`:`texture( ${t}, vec3( ${n}, ${r} ) )`;G(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}getVars(e){const t=[],n=this.vars[e];if(n!==void 0)for(const r of n)t.push(`${this.getVar(r.type,r.name,r.count)};`);return t.join(`
571
+ `)}getUniforms(e){const t=this.uniforms[e],n=[],r={};for(const o of t){let a=null,u=!1;if(o.type==="texture"||o.type==="texture3D"){const c=o.node.value;let d="";(c.isDataTexture===!0||c.isData3DTexture===!0)&&(c.type===je?d="u":c.type===st&&(d="i")),o.type==="texture3D"&&c.isArrayTexture===!1?a=`${d}sampler3D ${o.name};`:c.compareFunction?c.isArrayTexture===!0?a=`sampler2DArrayShadow ${o.name};`:a=`sampler2DShadow ${o.name};`:c.isArrayTexture===!0||c.isDataArrayTexture===!0||c.isCompressedArrayTexture===!0?a=`${d}sampler2DArray ${o.name};`:a=`${d}sampler2D ${o.name};`}else if(o.type==="cubeTexture")a=`samplerCube ${o.name};`;else if(o.type==="cubeDepthTexture")a=`samplerCubeShadow ${o.name};`;else if(o.type==="buffer"){const c=o.node,d=this.getType(c.bufferType),h=c.bufferCount,p=h>0?h:"";a=`${c.name} {
572
+ ${d} ${o.name}[${p}];
573
+ };
574
+ `}else a=`${this.getVectorType(o.type)} ${this.getPropertyName(o,e)};`,u=!0;const l=o.node.precision;if(l!==null&&(a=Ew[l]+" "+a),u){a=" "+a;const c=o.groupNode.name;(r[c]||(r[c]=[])).push(a)}else a="uniform "+a,n.push(a)}let s="";for(const o in r){const a=r[o];s+=this._getGLSLUniformStruct(e+"_"+o,a.join(`
575
+ `))+`
576
+ `}return s+=n.join(`
577
+ `),s}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==st){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const r=n.array;r instanceof Uint32Array||r instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t="";if(e==="vertex"||e==="compute"){const n=this.getAttributesArray();let r=0;for(const s of n)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};
578
+ `}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(` ${n.type} ${n.name};`);return t.join(`
579
+ `)}getStructs(e){const t=[],n=this.structs[e],r=[];for(const s of n)if(s.output)for(const o of s.members)r.push(`layout( location = ${o.index} ) out ${o.type} ${o.name};`);else{let o="struct "+s.name+` {
580
+ `;o+=this.getStructMembers(s),o+=`
581
+ };
582
+ `,t.push(o)}return r.length===0&&r.push("layout( location = 0 ) out vec4 fragColor;"),`
583
+ `+r.join(`
584
+ `)+`
585
+
586
+ `+t.join(`
587
+ `)}getVaryings(e){let t="";const n=this.varyings;if(e==="vertex"||e==="compute")for(const r of n){e==="compute"&&(r.needsInterpolation=!0);const s=this.getType(r.type);if(r.needsInterpolation)if(r.interpolationType){const o=jd[r.interpolationType]||r.interpolationType,a=qd[r.interpolationSampling]||"";t+=`${o} ${a} out ${s} ${r.name};
588
+ `}else{const o=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${o}out ${s} ${r.name};
589
+ `}else t+=`${s} ${r.name};
590
+ `}else if(e==="fragment"){for(const r of n)if(r.needsInterpolation){const s=this.getType(r.type);if(r.interpolationType){const o=jd[r.interpolationType]||r.interpolationType,a=qd[r.interpolationSampling]||"";t+=`${o} ${a} in ${s} ${r.name};
591
+ `}else{const o=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${o}in ${s} ${r.name};
592
+ `}}}for(const r of this.builtins[e])t+=`${r};
593
+ `;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((n,r)=>n*r,1)}u`}getSubgroupSize(){G("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){G("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){G("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const r=this.extensions[n]||(this.extensions[n]=new Map);r.has(e)===!1&&r.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if(e==="vertex"){const r=this.renderer.backend.extensions;this.object.isBatchedMesh&&r.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(n!==void 0)for(const{name:r,behavior:s}of n.values())t.push(`#extension ${r} : ${s}`);return t.join(`
594
+ `)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=Wd[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 r=this.renderer.backend.extensions;r.has(n)&&(r.get(n),t=!0)}Wd[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 r=e[n],s=this.getPropertyName(r.attributeNode);s&&(t+=`${r.varyingName} = ${s};
595
+ `)}return t}_getGLSLUniformStruct(e,t){return`
596
+ layout( std140 ) uniform ${e} {
597
+ ${t}
598
+ };`}_getGLSLVertexCode(e){return`#version 300 es
599
+
600
+ ${this.getSignature()}
601
+
602
+ // extensions
603
+ ${e.extensions}
604
+
605
+ // precision
606
+ ${Hd}
607
+
608
+ // uniforms
609
+ ${e.uniforms}
610
+
611
+ // varyings
612
+ ${e.varyings}
613
+
614
+ // attributes
615
+ ${e.attributes}
616
+
617
+ // codes
618
+ ${e.codes}
619
+
620
+ void main() {
621
+
622
+ // vars
623
+ ${e.vars}
624
+
625
+ // transforms
626
+ ${e.transforms}
627
+
628
+ // flow
629
+ ${e.flow}
630
+
631
+ gl_PointSize = 1.0;
632
+
633
+ }
634
+ `}_getGLSLFragmentCode(e){return`#version 300 es
635
+
636
+ ${this.getSignature()}
637
+
638
+ // extensions
639
+ ${e.extensions}
640
+
641
+ // precision
642
+ ${Hd}
643
+
644
+ // structs
645
+ ${e.structs}
646
+
647
+ // uniforms
648
+ ${e.uniforms}
649
+
650
+ // varyings
651
+ ${e.varyings}
652
+
653
+ // codes
654
+ ${e.codes}
655
+
656
+ void main() {
657
+
658
+ // vars
659
+ ${e.vars}
660
+
661
+ // flow
662
+ ${e.flow}
663
+
664
+ }
665
+ `}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n=`// code
666
+
667
+ `;n+=this.flowCode[t];const r=this.flowNodes[t],s=r[r.length-1];for(const a of r){const u=this.getFlowData(a),l=a.name;l&&(n.length>0&&(n+=`
668
+ `),n+=` // flow -> ${l}
669
+ `),n+=`${u.code}
670
+ `,a===s&&t!=="compute"&&(n+=`// result
671
+ `,t==="vertex"?(n+="gl_Position = ",n+=`${u.result};`):t==="fragment"&&(a.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${u.result};`)))}const o=e[t];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),o.structs=this.getStructs(t),o.codes=this.getCodes(t),o.transforms=this.getTransforms(t),o.flow=n}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,r=null){const s=super.getUniformFromNode(e,t,n,r),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 Go(s.name,s.node,u),c.push(a);else if(t==="cubeTexture"||t==="cubeDepthTexture")a=new Mg(s.name,s.node,u),c.push(a);else if(t==="texture3D")a=new Wu(s.name,s.node,u),c.push(a);else if(t==="buffer"){s.name=`buffer${e.id}`;const d=this.getSharedDataFromNode(e);let h=d.buffer;h===void 0&&(e.name=`NodeBuffer_${e.id}`,h=new Ag(e,u),h.name=e.name,d.buffer=h),c.push(h),a=h}else{const d=this.uniformGroups[n]||(this.uniformGroups[n]={});let h=d[l];h===void 0&&(h=new Eg(n+"_"+l,u),d[l]=h,c.push(h)),a=this.getNodeUniform(s,t),h.addUniform(a)}o.uniformGPU=a}return s}}let Ua=null,Ar=null;class Pg{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Kt.RENDER]:null,[Kt.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 r;e.isComputeNode===!0?r="c:"+this.renderer.info.compute.frameCalls:r="r:"+this.renderer.info.render.frameCalls,t.timestampUID=r+":"+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:")?Kt.COMPUTE:Kt.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){Ge("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(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Ua=Ua||new ce,this.renderer.getDrawingBufferSize(Ua)}setScissorTest(){}getClearColor(){const e=this.renderer;return Ar=Ar||new Il,e.getClearColor(Ar),Ar.getRGB(Ar),Ar}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:fm(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${No} webgpu`),this.domElement=e),e}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 Mw=0;class Pw{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 Bw{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:r}=n,s=e.array,o=e.usage||r.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,u=n.get(a);let l=u.bufferGPU;l===void 0&&(l=this._createBuffer(r,t,s,o),u.bufferGPU=l,u.bufferType=t,u.version=a.version);let c;if(s instanceof Float32Array)c=r.FLOAT;else if(typeof Float16Array<"u"&&s instanceof Float16Array)c=r.HALF_FLOAT;else if(s instanceof Uint16Array)e.isFloat16BufferAttribute?c=r.HALF_FLOAT:c=r.UNSIGNED_SHORT;else if(s instanceof Int16Array)c=r.SHORT;else if(s instanceof Uint32Array)c=r.UNSIGNED_INT;else if(s instanceof Int32Array)c=r.INT;else if(s instanceof Int8Array)c=r.BYTE;else if(s instanceof Uint8Array)c=r.UNSIGNED_BYTE;else if(s instanceof Uint8ClampedArray)c=r.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+s);let d={bufferGPU:l,bufferType:t,type:c,byteLength:s.byteLength,bytesPerElement:s.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:c===r.INT||c===r.UNSIGNED_INT||e.gpuType===st,id:Mw++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const h=this._createBuffer(r,t,s,o);d=new Pw(d,h)}n.set(e,d)}updateAttribute(e){const t=this.backend,{gl:n}=t,r=e.array,s=e.isInterleavedBufferAttribute?e.data:e,o=t.get(s),a=o.bufferType,u=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,o.bufferGPU),u.length===0)n.bufferSubData(a,0,r);else{for(let l=0,c=u.length;l<c;l++){const d=u[l];n.bufferSubData(a,d.start*r.BYTES_PER_ELEMENT,r,d.start,d.count)}s.clearUpdateRanges()}n.bindBuffer(a,null),o.version=s.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const r=t.get(e);n.deleteBuffer(r.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:n}=t,r=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:s}=t.get(r),o=e.array,a=o.byteLength;n.bindBuffer(n.COPY_READ_BUFFER,s);const u=n.createBuffer();n.bindBuffer(n.COPY_WRITE_BUFFER,u),n.bufferData(n.COPY_WRITE_BUFFER,a,n.STREAM_READ),n.copyBufferSubData(n.COPY_READ_BUFFER,n.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const l=new e.array.constructor(o.length);return n.bindBuffer(n.COPY_WRITE_BUFFER,u),n.getBufferSubData(n.COPY_WRITE_BUFFER,0,l),n.deleteBuffer(u),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),l.buffer}_createBuffer(e,t,n,r){const s=e.createBuffer();return e.bindBuffer(t,s),e.bufferData(t,n,r),e.bindBuffer(t,null),s}}let Oa,Ns;class Dw{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},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.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;Oa={[an]:e.FUNC_ADD,[Lh]:e.FUNC_SUBTRACT,[Fh]:e.FUNC_REVERSE_SUBTRACT},Ns={[wn]:e.ZERO,[jh]:e.ONE,[Wh]:e.SRC_COLOR,[zh]:e.SRC_ALPHA,[$h]:e.SRC_ALPHA_SATURATE,[Vh]:e.DST_COLOR,[Gh]:e.DST_ALPHA,[kh]:e.ONE_MINUS_SRC_COLOR,[Ih]:e.ONE_MINUS_SRC_ALPHA,[Oh]:e.ONE_MINUS_DST_COLOR,[Uh]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=new Oe().fromArray(t),this.currentViewport=new Oe().fromArray(n),this._tempVec4=new Oe}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!==gm?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===mm?t.cullFace(t.BACK):e===ym?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){const t=this.gl,n=this.backend.drawBuffersIndexedExt;if(n)for(let r=1;r<e.length;r++)n.blendFuncSeparateiOES(r,t.ONE,t.ZERO,t.ONE,t.ZERO)}setBlending(e,t,n,r,s,o,a,u){const{gl:l}=this;if(e===$r){this.currentBlendingEnabled===!0&&(this.disable(l.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),e!==Ms){if(e!==this.currentBlending||u!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==an||this.currentBlendEquationAlpha!==an)&&(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=an,this.currentBlendEquationAlpha=an),u)switch(e){case ir:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case ro:l.blendFunc(l.ONE,l.ONE);break;case no:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case to:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:G("WebGLState: Invalid blending: ",e);break}else switch(e){case ir:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case ro:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case no:G("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case to:G("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:G("WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=u}return}s=s||t,o=o||n,a=a||r,(t!==this.currentBlendEquation||s!==this.currentBlendEquationAlpha)&&(l.blendEquationSeparate(Oa[t],Oa[s]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=s),(n!==this.currentBlendSrc||r!==this.currentBlendDst||o!==this.currentBlendSrcAlpha||a!==this.currentBlendDstAlpha)&&(l.blendFuncSeparate(Ns[n],Ns[r],Ns[o],Ns[a]),this.currentBlendSrc=n,this.currentBlendDst=r,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)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case Jh:t.depthFunc(t.NEVER);break;case Zh:t.depthFunc(t.ALWAYS);break;case Qh:t.depthFunc(t.LESS);break;case Yh:t.depthFunc(t.LEQUAL);break;case Kh:t.depthFunc(t.EQUAL);break;case Xh:t.depthFunc(t.GEQUAL);break;case Hh:t.depthFunc(t.GREATER);break;case qh:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,r){const s=this._tempVec4.set(e,t,n,r);if(this.currentScissor.equals(s)===!1){const{gl:o}=this;o.scissor(s.x,s.y,s.z,s.w),this.currentScissor.copy(s)}}viewport(e,t,n,r){const s=this._tempVec4.set(e,t,n,r);if(this.currentViewport.equals(s)===!1){const{gl:o}=this;o.viewport(s.x,s.y,s.z,s.w),this.currentViewport.copy(s)}}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:r}=this;e.side===rr?this.disable(r.CULL_FACE):this.enable(r.CULL_FACE);let s=e.side===ht;t&&(s=!s),this.setFlipSided(s),e.blending===ir&&e.transparent===!1?this.setBlending($r):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(r.SAMPLE_ALPHA_TO_COVERAGE):this.disable(r.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:r}=this;e?(this.enable(r.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==n)&&(r.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(r.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:r}=this;return r[e]!==t?(n.bindFramebuffer(e,t),r[e]=t,e===n.DRAW_FRAMEBUFFER&&(r[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(r[n.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){const{gl:n}=this;let r=[],s=!1;if(e.textures!==null){r=this.currentDrawbuffers.get(t),r===void 0&&(r=[],this.currentDrawbuffers.set(t,r));const o=e.textures;if(r.length!==o.length||r[0]!==n.COLOR_ATTACHMENT0){for(let a=0,u=o.length;a<u;a++)r[a]=n.COLOR_ATTACHMENT0+a;r.length=o.length,s=!0}}else r[0]!==n.BACK&&(r[0]=n.BACK,s=!0);s&&n.drawBuffers(r)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:r}=this;e===void 0&&(e=t.TEXTURE0+r-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:r,currentTextureSlot:s,currentBoundTextures:o,maxTextures:a}=this;n===void 0&&(s===null?n=r.TEXTURE0+a-1:n=s);let u=o[n];u===void 0&&(u={type:void 0,texture:void 0},o[n]=u),(u.type!==e||u.texture!==t)&&(s!==n&&(r.activeTexture(n),this.currentTextureSlot=n),r.bindTexture(e,t),u.type=e,u.texture=t)}bindBufferBase(e,t,n){const{gl:r}=this,s=`${e}-${t}`;return this.currentBoundBufferBases[s]!==n?(r.bindBufferBase(e,t,n),this.currentBoundBufferBases[s]=n,!0):!1}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,r=n[t];r!==void 0&&r.type!==void 0&&(e.bindTexture(r.type,null),r.type=void 0,r.texture=void 0)}}class Fw{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=Vr){const{gl:n,extensions:r}=this;let s;const o=Ve.getTransfer(t);if(e===bt)return n.UNSIGNED_BYTE;if(e===bm)return n.UNSIGNED_SHORT_4_4_4_4;if(e===_m)return n.UNSIGNED_SHORT_5_5_5_1;if(e===ef)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===tf)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===Ps)return n.BYTE;if(e===Bs)return n.SHORT;if(e===Pr)return n.UNSIGNED_SHORT;if(e===st)return n.INT;if(e===je)return n.UNSIGNED_INT;if(e===vt)return n.FLOAT;if(e===it)return n.HALF_FLOAT;if(e===xm)return n.ALPHA;if(e===il)return n.RGB;if(e===Ft)return n.RGBA;if(e===Fn)return n.DEPTH_COMPONENT;if(e===Dn)return n.DEPTH_STENCIL;if(e===ol)return n.RED;if(e===al)return n.RED_INTEGER;if(e===hn)return n.RG;if(e===ul)return n.RG_INTEGER;if(e===ll)return n.RGBA_INTEGER;if(e===Vi||e===$i||e===zi||e===Wi)if(o===re)if(s=r.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(e===Vi)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===$i)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===zi)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Wi)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=r.get("WEBGL_compressed_texture_s3tc"),s!==null){if(e===Vi)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===$i)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===zi)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Wi)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===Kl||e===Yl||e===Ql||e===Zl)if(s=r.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(e===Kl)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Yl)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Ql)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Zl)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===Za||e===Ja||e===eu||e===tu||e===nu||e===so||e===ru)if(s=r.get("WEBGL_compressed_texture_etc"),s!==null){if(e===Za||e===Ja)return o===re?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(e===eu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(e===tu)return s.COMPRESSED_R11_EAC;if(e===nu)return s.COMPRESSED_SIGNED_R11_EAC;if(e===so)return s.COMPRESSED_RG11_EAC;if(e===ru)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(e===su||e===iu||e===ou||e===au||e===uu||e===lu||e===cu||e===du||e===hu||e===fu||e===pu||e===gu||e===mu||e===yu)if(s=r.get("WEBGL_compressed_texture_astc"),s!==null){if(e===su)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===iu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===ou)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===au)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===uu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===lu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===cu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===du)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===hu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===fu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===pu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===gu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===mu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===yu)return o===re?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===bu)if(s=r.get("EXT_texture_compression_bptc"),s!==null){if(e===bu)return o===re?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(e===_u||e===xu||e===io||e===Tu)if(s=r.get("EXT_texture_compression_rgtc"),s!==null){if(e===_u)return s.COMPRESSED_RED_RGTC1_EXT;if(e===xu)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===io)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Tu)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===Bn?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,r)=>{function s(){const o=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(o===e.WAIT_FAILED){e.deleteSync(t),r();return}if(o===e.TIMEOUT_EXPIRED){requestAnimationFrame(s);return}e.deleteSync(t),n()}s()})}}let Xd=!1,Mi,Ia,Kd;class Lw{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,Xd===!1&&(this._init(),Xd=!0)}_init(){const e=this.gl;Mi={[wo]:e.REPEAT,[js]:e.CLAMP_TO_EDGE,[Ro]:e.MIRRORED_REPEAT},Ia={[Bt]:e.NEAREST,[wh]:e.NEAREST_MIPMAP_NEAREST,[qs]:e.NEAREST_MIPMAP_LINEAR,[Ot]:e.LINEAR,[Qa]:e.LINEAR_MIPMAP_NEAREST,[sr]:e.LINEAR_MIPMAP_LINEAR},Kd={[Dh]:e.NEVER,[Bh]:e.ALWAYS,[Ao]:e.LESS,[Ph]:e.LEQUAL,[Mh]:e.EQUAL,[Ch]:e.GEQUAL,[Eh]:e.GREATER,[Ah]: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,r,s=!1){const{gl:o,extensions:a}=this;if(e!==null){if(o[e]!==void 0)return o[e];z("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let u=t;if(t===o.RED&&(n===o.FLOAT&&(u=o.R32F),n===o.HALF_FLOAT&&(u=o.R16F),n===o.UNSIGNED_BYTE&&(u=o.R8),n===o.UNSIGNED_SHORT&&(u=o.R16),n===o.UNSIGNED_INT&&(u=o.R32UI),n===o.BYTE&&(u=o.R8I),n===o.SHORT&&(u=o.R16I),n===o.INT&&(u=o.R32I)),t===o.RED_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.R8UI),n===o.UNSIGNED_SHORT&&(u=o.R16UI),n===o.UNSIGNED_INT&&(u=o.R32UI),n===o.BYTE&&(u=o.R8I),n===o.SHORT&&(u=o.R16I),n===o.INT&&(u=o.R32I)),t===o.RG&&(n===o.FLOAT&&(u=o.RG32F),n===o.HALF_FLOAT&&(u=o.RG16F),n===o.UNSIGNED_BYTE&&(u=o.RG8),n===o.UNSIGNED_SHORT&&(u=o.RG16),n===o.UNSIGNED_INT&&(u=o.RG32UI),n===o.BYTE&&(u=o.RG8I),n===o.SHORT&&(u=o.RG16I),n===o.INT&&(u=o.RG32I)),t===o.RG_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.RG8UI),n===o.UNSIGNED_SHORT&&(u=o.RG16UI),n===o.UNSIGNED_INT&&(u=o.RG32UI),n===o.BYTE&&(u=o.RG8I),n===o.SHORT&&(u=o.RG16I),n===o.INT&&(u=o.RG32I)),t===o.RGB){const l=s?Xl:Ve.getTransfer(r);n===o.FLOAT&&(u=o.RGB32F),n===o.HALF_FLOAT&&(u=o.RGB16F),n===o.UNSIGNED_BYTE&&(u=o.RGB8),n===o.UNSIGNED_SHORT&&(u=o.RGB16),n===o.UNSIGNED_INT&&(u=o.RGB32UI),n===o.BYTE&&(u=o.RGB8I),n===o.SHORT&&(u=o.RGB16I),n===o.INT&&(u=o.RGB32I),n===o.UNSIGNED_BYTE&&(u=l===re?o.SRGB8:o.RGB8),n===o.UNSIGNED_SHORT_5_6_5&&(u=o.RGB565),n===o.UNSIGNED_SHORT_5_5_5_1&&(u=o.RGB5_A1),n===o.UNSIGNED_SHORT_4_4_4_4&&(u=o.RGB4),n===o.UNSIGNED_INT_5_9_9_9_REV&&(u=o.RGB9_E5),n===o.UNSIGNED_INT_10F_11F_11F_REV&&(u=o.R11F_G11F_B10F)}if(t===o.RGB_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.RGB8UI),n===o.UNSIGNED_SHORT&&(u=o.RGB16UI),n===o.UNSIGNED_INT&&(u=o.RGB32UI),n===o.BYTE&&(u=o.RGB8I),n===o.SHORT&&(u=o.RGB16I),n===o.INT&&(u=o.RGB32I)),t===o.RGBA){const l=s?Xl:Ve.getTransfer(r);n===o.FLOAT&&(u=o.RGBA32F),n===o.HALF_FLOAT&&(u=o.RGBA16F),n===o.UNSIGNED_BYTE&&(u=o.RGBA8),n===o.UNSIGNED_SHORT&&(u=o.RGBA16),n===o.UNSIGNED_INT&&(u=o.RGBA32UI),n===o.BYTE&&(u=o.RGBA8I),n===o.SHORT&&(u=o.RGBA16I),n===o.INT&&(u=o.RGBA32I),n===o.UNSIGNED_BYTE&&(u=l===re?o.SRGB8_ALPHA8:o.RGBA8),n===o.UNSIGNED_SHORT_4_4_4_4&&(u=o.RGBA4),n===o.UNSIGNED_SHORT_5_5_5_1&&(u=o.RGB5_A1)}return t===o.RGBA_INTEGER&&(n===o.UNSIGNED_BYTE&&(u=o.RGBA8UI),n===o.UNSIGNED_SHORT&&(u=o.RGBA16UI),n===o.UNSIGNED_INT&&(u=o.RGBA32UI),n===o.BYTE&&(u=o.RGBA8I),n===o.SHORT&&(u=o.RGBA16I),n===o.INT&&(u=o.RGBA32I)),t===o.DEPTH_COMPONENT&&(n===o.UNSIGNED_SHORT&&(u=o.DEPTH_COMPONENT16),n===o.UNSIGNED_INT&&(u=o.DEPTH_COMPONENT24),n===o.FLOAT&&(u=o.DEPTH_COMPONENT32F)),t===o.DEPTH_STENCIL&&n===o.UNSIGNED_INT_24_8&&(u=o.DEPTH24_STENCIL8),(u===o.R16F||u===o.R32F||u===o.RG16F||u===o.RG32F||u===o.RGBA16F||u===o.RGBA32F)&&a.get("EXT_color_buffer_float"),u}setTextureParameters(e,t){const{gl:n,extensions:r,backend:s}=this,o=Ve.getPrimaries(Ve.workingColorSpace),a=t.colorSpace===Vr?null:Ve.getPrimaries(t.colorSpace),u=t.colorSpace===Vr||o===a?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,u),n.texParameteri(e,n.TEXTURE_WRAP_S,Mi[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,Mi[t.wrapT]),(e===n.TEXTURE_3D||e===n.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,Mi[t.wrapR])),n.texParameteri(e,n.TEXTURE_MAG_FILTER,Ia[t.magFilter]);const l=t.mipmaps!==void 0&&t.mipmaps.length>0,c=t.minFilter===Ot&&l?sr:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,Ia[c]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,Kd[t.compareFunction])),r.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===Bt||t.minFilter!==qs&&t.minFilter!==sr||t.type===vt&&r.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const d=r.get("EXT_texture_filter_anisotropic");n.texParameterf(e,d.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,s.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:r}=this,s=this.getGLTextureType(e);let o=r[s];o===void 0&&(o=t.createTexture(),n.state.bindTexture(s,o),t.texParameteri(s,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(s,t.TEXTURE_MAG_FILTER,t.NEAREST),r[s]=o),n.set(e,{textureGPU:o,glTextureType:s})}createTexture(e,t){const{gl:n,backend:r}=this,{levels:s,width:o,height:a,depth:u}=t,l=r.utils.convert(e.format,e.colorSpace),c=r.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,l,c,e.colorSpace,e.isVideoTexture),h=n.createTexture(),p=this.getGLTextureType(e);r.state.bindTexture(p,h),this.setTextureParameters(p,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,s,d,o,a,u):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,s,d,o,a,u):e.isVideoTexture||n.texStorage2D(p,s,d,o,a),r.set(e,{textureGPU:h,glTextureType:p,glFormat:l,glType:c,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:n,backend:r}=this,{textureGPU:s,glTextureType:o,glFormat:a,glType:u}=r.get(t),{width:l,height:c}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),r.state.bindTexture(o,s),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(o,0,0,0,l,c,a,u,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),r.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:r,height:s}=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 p=0;p<d.length;p++){const f=d[p];e.isCompressedArrayTexture?e.format!==n.RGBA?u!==null?n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,h.depth,u,f.data):z("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texSubImage3D(n.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,h.depth,u,l,f.data):u!==null?n.compressedTexSubImage2D(n.TEXTURE_2D,p,0,0,f.width,f.height,u,f.data):z("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const d=t.images,h=e.mipmaps;for(let p=0;p<6;p++){const f=Pi(d[p]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,0,0,r,s,u,l,f);for(let g=0;g<h.length;g++){const m=h[g],y=Pi(m.images[p]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+p,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=pm(d.width,d.height,e.format,e.type);for(const p of e.layerUpdates){const f=d.data.subarray(p*h/d.data.BYTES_PER_ELEMENT,(p+1)*h/d.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,p,d.width,d.height,1,u,l,f)}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{const d=e.mipmaps;if(d.length>0)for(let h=0,p=d.length;h<p;h++){const f=d[h],g=Pi(f);n.texSubImage2D(a,h,0,0,f.width,f.height,u,l,g)}else{const h=Pi(t.image);n.texSubImage2D(a,0,0,0,r,s,u,l,h)}}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:r,glTextureType:s}=n.get(e);n.state.bindTexture(s,r),t.generateMipmap(s)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const r=n.get(e);if(r.renderBufferStorageSetup=void 0,r.framebuffers){for(const s in r.framebuffers)t.deleteFramebuffer(r.framebuffers[s]);delete r.framebuffers}if(r.depthRenderbuffer&&(t.deleteRenderbuffer(r.depthRenderbuffer),delete r.depthRenderbuffer),r.stencilRenderbuffer&&(t.deleteRenderbuffer(r.stencilRenderbuffer),delete r.stencilRenderbuffer),r.msaaFrameBuffer&&(t.deleteFramebuffer(r.msaaFrameBuffer),delete r.msaaFrameBuffer),r.msaaRenderbuffers){for(let s=0;s<r.msaaRenderbuffers.length;s++)t.deleteRenderbuffer(r.msaaRenderbuffers[s]);delete r.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:n,backend:r}=this,{textureGPU:s,renderTarget:o}=r.get(e);this.deallocateRenderBuffers(o),t===!1&&n.deleteTexture(s),r.delete(e)}copyTextureToTexture(e,t,n=null,r=null,s=0,o=0){const{gl:a,backend:u}=this,{state:l}=this.backend,{textureGPU:c,glTextureType:d,glType:h,glFormat:p}=u.get(t);l.bindTexture(d,c);let f,g,m,y,_,T,A,B,S;const v=e.isCompressedTexture?e.mipmaps[o]:e.image;if(n!==null)f=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 ue=Math.pow(2,-s);f=Math.floor(v.width*ue),g=Math.floor(v.height*ue),e.isDataArrayTexture||e.isArrayTexture?m=v.depth:e.isData3DTexture?m=Math.floor(v.depth*ue):m=1,y=0,_=0,T=0}r!==null?(A=r.x,B=r.y,S=r.z):(A=0,B=0,S=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const E=a.getParameter(a.UNPACK_ROW_LENGTH),D=a.getParameter(a.UNPACK_IMAGE_HEIGHT),O=a.getParameter(a.UNPACK_SKIP_PIXELS),Y=a.getParameter(a.UNPACK_SKIP_ROWS),ee=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,v.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,v.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,y),a.pixelStorei(a.UNPACK_SKIP_ROWS,_),a.pixelStorei(a.UNPACK_SKIP_IMAGES,T);const te=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,ne=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const ue=u.get(e),le=u.get(t),F=u.get(ue.renderTarget),V=u.get(le.renderTarget),K=F.framebuffers[ue.cacheKey],ye=V.framebuffers[le.cacheKey];l.bindFramebuffer(a.READ_FRAMEBUFFER,K),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,ye);for(let k=0;k<m;k++)te&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,ue.textureGPU,s,T+k),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,c,o,S+k)),a.blitFramebuffer(y,_,f,g,A,B,f,g,a.DEPTH_BUFFER_BIT,a.NEAREST);l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(s!==0||e.isRenderTargetTexture||u.has(e)){const ue=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 le=0;le<m;le++)te?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,ue.textureGPU,s,T+le):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,ue.textureGPU,s),ne?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,c,o,S+le):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,c,o),s!==0?a.blitFramebuffer(y,_,f,g,A,B,f,g,a.COLOR_BUFFER_BIT,a.NEAREST):ne?a.copyTexSubImage3D(d,o,A,B,S+le,y,_,f,g):a.copyTexSubImage2D(d,o,A,B,y,_,f,g);l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else ne?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(d,o,A,B,S,f,g,m,p,h,v.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(d,o,A,B,S,f,g,m,p,v.data):a.texSubImage3D(d,o,A,B,S,f,g,m,p,h,v):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,o,A,B,f,g,p,h,v.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,o,A,B,v.width,v.height,p,v.data):a.texSubImage2D(a.TEXTURE_2D,o,A,B,f,g,p,h,v);a.pixelStorei(a.UNPACK_ROW_LENGTH,E),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,D),a.pixelStorei(a.UNPACK_SKIP_PIXELS,O),a.pixelStorei(a.UNPACK_SKIP_ROWS,Y),a.pixelStorei(a.UNPACK_SKIP_IMAGES,ee),o===0&&t.generateMipmaps&&a.generateMipmap(d),l.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:r}=this,{state:s}=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 p=a!==0||u!==0;let f,g;if(e.isDepthTexture===!0?(f=r.DEPTH_BUFFER_BIT,g=r.DEPTH_ATTACHMENT,t.stencil&&(f|=r.STENCIL_BUFFER_BIT)):(f=r.COLOR_BUFFER_BIT,g=r.COLOR_ATTACHMENT0),p){const m=this.backend.get(t.renderTarget),y=m.framebuffers[t.getCacheKey()],_=m.msaaFrameBuffer;s.bindFramebuffer(r.DRAW_FRAMEBUFFER,y),s.bindFramebuffer(r.READ_FRAMEBUFFER,_);const T=h-u-c;r.blitFramebuffer(a,T,a+l,T+c,a,T,a+l,T+c,f,r.NEAREST),s.bindFramebuffer(r.READ_FRAMEBUFFER,y),s.bindTexture(r.TEXTURE_2D,o),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,T,l,c),s.unbindTexture()}else{const m=r.createFramebuffer();s.bindFramebuffer(r.DRAW_FRAMEBUFFER,m),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,g,r.TEXTURE_2D,o,0),r.blitFramebuffer(0,0,l,c,0,0,l,c,f,r.NEAREST),r.deleteFramebuffer(m)}}else s.bindTexture(r.TEXTURE_2D,o),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,h-c-u,l,c),s.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,r=!1){const{gl:s}=this,o=t.renderTarget,{depthTexture:a,depthBuffer:u,stencilBuffer:l,width:c,height:d}=o;if(s.bindRenderbuffer(s.RENDERBUFFER,e),u&&!l){let h=s.DEPTH_COMPONENT24;r===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(s.RENDERBUFFER,o.samples,h,c,d):n>0?(a&&a.isDepthTexture&&a.type===s.FLOAT&&(h=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,n,h,c,d)):s.renderbufferStorage(s.RENDERBUFFER,h,c,d),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else u&&l&&(n>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,c,d):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,c,d),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e));s.bindRenderbuffer(s.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,r,s,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 p=e.isCubeTexture?u.TEXTURE_CUBE_MAP_POSITIVE_X+o:u.TEXTURE_2D;u.framebufferTexture2D(u.READ_FRAMEBUFFER,u.COLOR_ATTACHMENT0,p,l,0);const f=this._getTypedArrayType(d),g=this._getBytesPerTexel(d,c),y=r*s*g,_=u.createBuffer();u.bindBuffer(u.PIXEL_PACK_BUFFER,_),u.bufferData(u.PIXEL_PACK_BUFFER,y,u.STREAM_READ),u.readPixels(t,n,r,s,c,d,0),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const T=new f(y/f.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 r=0;if(e===n.UNSIGNED_BYTE&&(r=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)&&(r=2),(e===n.UNSIGNED_INT||e===n.FLOAT)&&(r=4),t===n.RGBA)return r*4;if(t===n.RGB)return r*3;if(t===n.ALPHA)return r}dispose(){const{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}}function Pi(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 Uw{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 Ow{constructor(e){this.backend=e,this.maxAnisotropy=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}}const Yd={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 Iw{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:r,object:s,type:o,info:a,index:u}=this;u!==0?n.drawElements(r,t,o,e):n.drawArrays(r,e,t),a.update(s,t,1)}renderInstances(e,t,n){const{gl:r,mode:s,type:o,index:a,object:u,info:l}=this;n!==0&&(a!==0?r.drawElementsInstanced(s,t,o,e,n):r.drawArraysInstanced(s,e,t,n),l.update(u,t,n))}renderMultiDraw(e,t,n){const{extensions:r,mode:s,object:o,info:a}=this;if(n===0)return;const u=r.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(s,t,0,this.type,e,0,n):u.multiDrawArraysWEBGL(s,e,0,t,0,n);let l=0;for(let c=0;c<n;c++)l+=t[c];a.update(o,l,1)}}renderMultiDrawInstances(e,t,n,r){const{extensions:s,mode:o,object:a,info:u}=this;if(n===0)return;const l=s.get("WEBGL_multi_draw");if(l===null)for(let c=0;c<n;c++)this.renderInstances(e[c],t[c],r[c]);else{this.index!==0?l.multiDrawElementsInstancedWEBGL(o,t,0,this.type,e,0,r,0,n):l.multiDrawArraysInstancedWEBGL(o,e,0,t,0,r,0,n);let c=0;for(let d=0;d<n;d++)c+=t[d]*r[d];u.update(a,c,1)}}}class Bg{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 kw extends Bg{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 r=0;r<this.maxQueries;r++)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 Ge(`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.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(r){G("Error in beginQuery:",r),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){G("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[s,o]of this.queryOffsets)if(this.queryStates.get(o)==="ended"){const u=this.queries[o];e.set(s,this.resolveQuery(u))}if(e.size===0)return this.lastValue;const t={},n=[];for(const[s,o]of e){const a=s.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(s,l),t[u]+=l}const r=t[n[n.length-1]];return this.lastValue=r,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,r}catch(e){return G("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,r=!1;const s=()=>{n&&(clearTimeout(n),n=null)},o=u=>{r||(r=!0,s(),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){G("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 Qd extends Pg{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},r=t.context!==void 0?t.context:e.domElement.getContext("webgl2",n);function s(o){o.preventDefault();const a={api:"WebGL",message:o.statusMessage||"Unknown reason",reason:null,originalEvent:o};e.onDeviceLost(a)}this._onContextLost=s,e.domElement.addEventListener("webglcontextlost",s,!1),this.gl=r,this.extensions=new Uw(this),this.capabilities=new Ow(this),this.attributeUtils=new Bw(this),this.textureUtils=new Lw(this),this.bufferRenderer=new Iw(this),this.state=new Dw(this),this.utils=new Fw(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.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")}get coordinateSystem(){return Ji}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const r=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:r.RGBA8}),n!==null){const s=e.stencilBuffer?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:s}),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 kw(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:s,height:o}=this.getDrawingBufferSize();t.viewport(0,0,s,o)}if(e.scissor){const{x:s,y:o,width:a,height:u}=e.scissorValue;t.scissor(s,e.height-u-o,a,u)}this.initTimestampQuery(Kt.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 r=e.occlusionQueryCount;r>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(r),n.occlusionQueryObjects=new Array(r),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,r=this.get(e),s=r.previousContext;n.resetVertexState();const o=e.occlusionQueryCount;o>0&&(o>r.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=s,this._resolveRenderTarget(e),s!==null)if(this._setFramebuffer(s),s.viewport)this.updateViewport(s);else{const{width:u,height:l}=this.getDrawingBufferSize();n.viewport(0,0,u,l)}this.prepareTimestampBuffer(Kt.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:r}=t;if(n&&r){const s=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&&s.add(r[l]),n[l]=null,o.deleteQuery(c),u++)}u<n.length?requestAnimationFrame(a):t.occluded=s};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:r,width:s,height:o}=e.viewportValue;t.viewport(n,e.height-o-r,s,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,r=null,s=!0,o=!0){const{gl:a,renderer:u}=this;r===null&&(r={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;r.clearColorValue?c=r.clearColorValue:c=this.getClearColor();const d=u.getClearDepth(),h=u.getClearStencil();if(t&&this.state.setDepthMask(!0),r.textures===null)a.clearColor(c.r,c.g,c.b,c.a),a.clear(l);else{if(s&&this._setFramebuffer(r),e)for(let p=0;p<r.textures.length;p++)p===0?a.clearBufferfv(a.COLOR,p,[c.r,c.g,c.b,c.a]):a.clearBufferfv(a.COLOR,p,[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]),s&&o&&this._resolveRenderTarget(r)}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(Kt.COMPUTE,this.getTimestampUID(e))}compute(e,t,n,r,s=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(r),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 p=this._getTransformFeedback(l);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,p),a.beginTransformFeedback(a.POINTS),s=s!==null?s:t.count,Array.isArray(s)?(Ge("WebGLBackend.compute(): The count parameter must be a single number, not an array."),s=s[0]):s&&typeof s=="object"&&s.isIndirectStorageBufferAttribute&&(Ge("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),s=t.count),c[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,s):a.drawArrays(a.POINTS,0,s),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let f=0;f<l.length;f++){const g=l[f];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(Kt.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:n,material:r,context:s,hardwareClippingPlanes:o}=e,{programGPU:a}=this.get(n),{gl:u,state:l}=this,c=this.get(s),d=e.getDrawParameters();if(d===null)return;this._bindUniforms(e.getBindings());const h=t.isMesh&&t.matrixWorld.determinant()<0;l.setMaterial(r,h,o),s.textures!==null&&s.textures.length>1&&l.setMRTBlending(s.textures),l.useProgram(a);const p=e.getAttributes(),f=this.get(p);let g=f.vaoGPU;if(g===void 0){const E=this._getVaoKey(p);g=this.vaoCache[E],g===void 0&&(g=this._createVao(p),this.vaoCache[E]=g,f.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 E=u.createQuery();u.beginQuery(u.ANY_SAMPLES_PASSED,E),c.occlusionQueries[c.occlusionQueryIndex]=E,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:r.wireframe===!0?(l.setLineWidth(r.wireframeLinewidth*this.renderer.getPixelRatio()),T.mode=u.LINES):T.mode=u.TRIANGLES;const{vertexCount:A,instanceCount:B}=d;let{firstVertex:S}=d;if(T.object=t,m!==null){S*=m.array.BYTES_PER_ELEMENT;const E=this.get(m);T.index=m.count,T.type=E.type}else T.index=0;const v=()=>{t.isBatchedMesh?t._multiDrawInstances!==null?(Ge("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),T.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?T.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Ge("WebGLBackend: WEBGL_multi_draw not supported."):B>1?T.renderInstances(S,A,B):T.render(S,A)};if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const E=this.get(e.camera),D=e.camera.cameras,O=e.getBindingGroup("cameraIndex").bindings[0];if(E.indexesGPU===void 0||E.indexesGPU.length!==D.length){const le=new Uint32Array([0,0,0,0]),F=[];for(let V=0,K=D.length;V<K;V++){const ye=u.createBuffer();le[0]=V,u.bindBuffer(u.UNIFORM_BUFFER,ye),u.bufferData(u.UNIFORM_BUFFER,le,u.STATIC_DRAW),F.push(ye)}E.indexesGPU=F}const Y=this.get(O),ee=this.renderer.getPixelRatio(),te=this._currentContext.renderTarget,ne=this._isRenderCameraDepthArray(this._currentContext),ue=this._currentContext.activeCubeFace;if(ne){const le=this.get(te.depthTexture);if(le.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){le.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:F}=te;for(let V=0,K=D.length;V<K;V++)this.renderer._activeCubeFace=V,this._currentContext.activeCubeFace=V,this._setFramebuffer(this._currentContext),this.clear(!1,!0,F,this._currentContext,!1,!1);this.renderer._activeCubeFace=ue,this._currentContext.activeCubeFace=ue}}for(let le=0,F=D.length;le<F;le++){const V=D[le];if(t.layers.test(V.layers)){ne&&(this.renderer._activeCubeFace=le,this._currentContext.activeCubeFace=le,this._setFramebuffer(this._currentContext));const K=V.viewport;if(K!==void 0){const ye=K.x*ee,k=K.y*ee,q=K.width*ee,ie=K.height*ee;l.viewport(Math.floor(ye),Math.floor(e.context.height-ie-k),Math.floor(q),Math.floor(ie))}l.bindBufferBase(u.UNIFORM_BUFFER,Y.index,E.indexesGPU[le]),v()}this._currentContext.activeCubeFace=ue,this.renderer._activeCubeFace=ue}}else v()}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,r,s,o){return this.textureUtils.copyTextureToBuffer(e,t,n,r,s,o)}updateSampler(){return""}createNodeBuilder(e,t){return new Cw(e,t)}createProgram(e){const t=this.gl,{stage:n,code:r}=e,s=n==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(s,r),t.compileShader(s),this.set(e,{shaderGPU:s})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,r=e.pipeline,{fragmentProgram:s,vertexProgram:o}=r,a=n.createProgram(),u=this.get(s).shaderGPU,l=this.get(o).shaderGPU;if(n.attachShader(a,u),n.attachShader(a,l),n.linkProgram(a),this.set(r,{programGPU:a,fragmentShader:u,vertexShader:l}),t!==null&&this.parallel){const c=new Promise(d=>{const h=this.parallel,p=()=>{n.getProgramParameter(a,h.COMPLETION_STATUS_KHR)?(this._completeCompile(e,r),d()):requestAnimationFrame(p)};p()});t.push(c);return}this._completeCompile(e,r)}_handleSource(e,t){const n=e.split(`
672
+ `),r=[],s=Math.max(t-6,0),o=Math.min(t+6,n.length);for(let a=s;a<o;a++){const u=a+1;r.push(`${u===t?">":" "} ${u}: ${n[a]}`)}return r.join(`
673
+ `)}_getShaderErrors(e,t,n){const r=e.getShaderParameter(t,e.COMPILE_STATUS),o=(e.getShaderInfoLog(t)||"").trim();if(r&&o==="")return"";const a=/ERROR: 0:(\d+)/.exec(o);if(a){const u=parseInt(a[1]);return n.toUpperCase()+`
674
+
675
+ `+o+`
676
+
677
+ `+this._handleSource(e.getShaderSource(t),u)}else return o}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const r=this.gl,o=(r.getProgramInfoLog(e)||"").trim();if(r.getProgramParameter(e,r.LINK_STATUS)===!1)if(typeof this.renderer.debug.onShaderError=="function")this.renderer.debug.onShaderError(r,e,n,t);else{const a=this._getShaderErrors(r,n,"vertex"),u=this._getShaderErrors(r,t,"fragment");G("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(e,r.VALIDATE_STATUS)+`
678
+
679
+ Program Info Log: `+o+`
680
+ `+a+`
681
+ `+u)}else o!==""&&z("WebGLProgram: Program Info Log:",o)}}_completeCompile(e,t){const{state:n,gl:r}=this,s=this.get(t),{programGPU:o,fragmentShader:a,vertexShader:u}=s;r.getProgramParameter(o,r.LINK_STATUS)===!1&&this._logProgramError(o,a,u),n.useProgram(o);const l=e.getBindings();this._setupBindings(l,o),this.set(t,{programGPU:o})}createComputePipeline(e,t){const{state:n,gl:r}=this,s={stage:"fragment",code:`#version 300 es
682
+ precision highp float;
683
+ void main() {}`};this.createProgram(s);const{computeProgram:o}=e,a=r.createProgram(),u=this.get(s).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)}r.attachShader(a,u),r.attachShader(a,l),r.transformFeedbackVaryings(a,d,r.SEPARATE_ATTRIBS),r.linkProgram(a),r.getProgramParameter(a,r.LINK_STATUS)===!1&&this._logProgramError(a,u,l),n.useProgram(a),this._setupBindings(t,a);const p=o.attributes,f=[],g=[];for(let m=0;m<p.length;m++){const y=p[m].node.attribute;f.push(y),this.has(y)||this.attributeUtils.createAttribute(y,r.ARRAY_BUFFER)}for(let m=0;m<h.length;m++){const y=h[m].attribute;this.has(y)||this.attributeUtils.createAttribute(y,r.ARRAY_BUFFER);const _=this.get(y);g.push(_)}this.set(e,{programGPU:a,transformBuffers:g,attributes:f})}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let n=0,r=0;for(const s of t){this.set(s,{textures:r,uniformBuffers:n});for(const o of s.bindings)o.isUniformBuffer&&n++,o.isSampledTexture&&r++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,n=this.get(e);let r=n.uniformBuffers,s=n.textures;for(const o of e.bindings){const a=this.get(o);if(o.isUniformsGroup||o.isUniformBuffer){const u=o.buffer;let{bufferGPU:l}=this.get(u);l===void 0?(l=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,l),t.bufferData(t.UNIFORM_BUFFER,u.byteLength,t.DYNAMIC_DRAW),this.set(u,{bufferGPU:l})):t.bindBuffer(t.UNIFORM_BUFFER,l);const c=o.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,l),c.length===0)t.bufferData(t.UNIFORM_BUFFER,u,t.DYNAMIC_DRAW);else{const d=eo(u),h=d?1:u.BYTES_PER_ELEMENT;for(let p=0,f=c.length;p<f;p++){const g=c[p],m=g.start*h,y=g.count*h,_=m*(d?u.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,_,u,m,y)}}a.index=r++,a.bufferGPU=l,this.set(o,a)}else if(o.isSampledTexture){const{textureGPU:u,glTextureType:l}=this.get(o.texture);a.index=s++,a.textureGPU=u,a.glTextureType=l,this.set(o,a)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const r=this.get(e).bufferGPU,s=e.buffer,o=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,r),o.length===0)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{const a=eo(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,p=d.count*u,f=h*(a?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,f,s,h,p)}}}}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(Yd).filter(r=>Yd[r]===e),n=this.extensions;for(let r=0;r<t.length;r++)if(n.has(t[r]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,n=null,r=null,s=0,o=0){this.textureUtils.copyTextureToTexture(e,t,n,r,s,o)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}_setFramebuffer(e){const{gl:t,state:n}=this;let r=null;if(e.textures!==null){const s=e.renderTarget,o=this.get(s),{samples:a,depthBuffer:u,stencilBuffer:l}=s,c=s.isWebGLCubeRenderTarget===!0,d=s.isRenderTarget3D===!0,h=s.depth>1,p=s.isXRRenderTarget===!0,f=p===!0&&s._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(s),A=lg(e);let B;if(c?(o.cubeFramebuffers||(o.cubeFramebuffers={}),B=o.cubeFramebuffers[A]):p&&f===!1?B=this._xrFramebuffer:(o.framebuffers||(o.framebuffers={}),B=o.framebuffers[A]),B===void 0){B=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,B);const S=e.textures,v=[];if(c){o.cubeFramebuffers[A]=B;const{textureGPU:D}=this.get(S[0]),O=this.renderer._activeCubeFace,Y=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+O,D,Y)}else{o.framebuffers[A]=B;for(let D=0;D<S.length;D++){const O=S[D],Y=this.get(O);Y.renderTarget=e.renderTarget,Y.cacheKey=A;const ee=t.COLOR_ATTACHMENT0+D;if(s.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,ee,Y.textureGPU,0,a,0,2);else if(d||h){const te=this.renderer._activeCubeFace,ne=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,ee,Y.textureGPU,ne,te)}else if(T)y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,ee,t.TEXTURE_2D,Y.textureGPU,0,a);else{const te=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,ee,t.TEXTURE_2D,Y.textureGPU,te)}}}const E=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._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,E,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=A,s.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,E,D.textureGPU,0,a,0,2);else if(f&&T)y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,E,t.TEXTURE_2D,D.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const O=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,E,D.textureGPU,0,O)}else if(e.depthTexture.isCubeTexture){const O=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,E,t.TEXTURE_CUBE_MAP_POSITIVE_X+O,D.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,E,t.TEXTURE_2D,D.textureGPU,0)}o.depthInvalidationArray=v}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,B);const v=this.renderer._activeCubeFace,E=this.get(e.depthTexture),D=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,D,E.textureGPU,0,v)}if((p||T||s.multiview)&&s._isOpaqueFramebuffer!==!0){n.bindFramebuffer(t.FRAMEBUFFER,B);const v=this.get(e.textures[0]);s.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 E=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._autoAllocateDepthBuffer===!0){const D=o.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,D),t.framebufferRenderbuffer(t.FRAMEBUFFER,E,t.RENDERBUFFER,D)}else{const D=this.get(e.depthTexture);s.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,E,D.textureGPU,0,a,0,2):T?y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,E,t.TEXTURE_2D,D.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,E,t.TEXTURE_2D,D.textureGPU,0)}}}if(a>0&&T===!1&&!s.multiview){if(g===void 0){const S=[];g=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,g);const v=[],E=e.textures;for(let D=0;D<E.length;D++){v[D]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,v[D]),S.push(t.COLOR_ATTACHMENT0+D);const O=e.textures[D],Y=this.get(O);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,Y.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;S.push(D)}o.invalidationArray=S}r=o.msaaFrameBuffer}else r=B;n.drawBuffers(e,B)}n.bindFramebuffer(t.FRAMEBUFFER,r)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){const r=this.get(e[n]);t+=":"+r.id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let r=0;r<e.length;r++){const s=e[r],o=this.get(s);t.bindBuffer(t.ARRAY_BUFFER,o.bufferGPU),t.enableVertexAttribArray(r);let a,u;s.isInterleavedBufferAttribute===!0?(a=s.data.stride*o.bytesPerElement,u=s.offset*o.bytesPerElement):(a=0,u=0),o.isInteger?t.vertexAttribIPointer(r,s.itemSize,o.type,a,u):t.vertexAttribPointer(r,s.itemSize,o.type,s.normalized,a,u),s.isInstancedBufferAttribute&&!s.isInterleavedBufferAttribute?t.vertexAttribDivisor(r,s.meshPerAttribute):s.isInterleavedBufferAttribute&&s.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(r,s.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let n=this.transformFeedbackCache[t];if(n!==void 0)return n;const{gl:r}=this;n=r.createTransformFeedback(),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,n);for(let s=0;s<e.length;s++){const o=e[s];r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,s,o.transformBuffer)}return r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;for(const r of e)for(const s of r.bindings){const a=this.get(s).index;if(s.isUniformsGroup||s.isUniformBuffer){const u=n.getUniformBlockIndex(t,s.name);n.uniformBlockBinding(t,u,a)}else if(s.isSampledTexture){const u=n.getUniformLocation(t,s.name);n.uniform1i(u,a)}}}_bindUniforms(e){const{gl:t,state:n}=this;for(const r of e)for(const s of r.bindings){const o=this.get(s),a=o.index;s.isUniformsGroup||s.isUniformBuffer?n.bindBufferBase(t.UNIFORM_BUFFER,a,o.bufferGPU):s.isSampledTexture&&n.bindTexture(o.glTextureType,o.textureGPU,t.TEXTURE0+a)}}_resolveRenderTarget(e){const{gl:t,state:n}=this,r=e.renderTarget;if(e.textures!==null&&r){const s=this.get(r);if(r.samples>0&&this._useMultisampledExtension(r)===!1){const o=s.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;r.resolveDepthBuffer&&(r.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),r.stencilBuffer&&r.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const u=s.msaaFrameBuffer,l=s.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:p}=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,p,0)}if(e.scissor){const{x:p,y:f,width:g,height:m}=e.scissorValue,y=e.height-m-f;t.blitFramebuffer(p,y,p+g,y+m,p,y,p+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:p}=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,p,0)}this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,s.invalidationArray)}else if(r.resolveDepthBuffer===!1&&s.framebuffers){const o=s.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,o),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,s.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 Fr={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list",TriangleStrip:"triangle-strip"},nr=typeof self<"u"?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"},rt={Store:"store"},xe={Load:"load",Clear:"clear"},Zd={CCW:"ccw",CW:"cw"},Jd={None:"none",Back:"back"},Xr={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",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",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rg11b10ufloat",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",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"},ka={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},er={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"},jn={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},eh={None:0,All:15},Nn={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},Ga={Storage:"storage",ReadOnlyStorage:"read-only-storage"},Va={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},th={NonFiltering:"non-filtering",Comparison:"comparison"},qn={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},nh={TwoD:"2d",ThreeD:"3d"},We={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},Gw={All:"all"},Bi={Vertex:"vertex",Instance:"instance"},ju={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"},rh={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class Vw extends Cg{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 $w extends Rg{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let zw=0;class Ww extends $w{constructor(e,t){super("StorageBuffer_"+zw++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Nt.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class jw extends kn{constructor(e){super(),this.device=e;const t=`
684
+ struct VarysStruct {
685
+ @builtin( position ) Position: vec4<f32>,
686
+ @location( 0 ) vTex : vec2<f32>
687
+ };
688
+
689
+ @vertex
690
+ fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
691
+
692
+ var Varys : VarysStruct;
693
+
694
+ var pos = array< vec2<f32>, 4 >(
695
+ vec2<f32>( -1.0, 1.0 ),
696
+ vec2<f32>( 1.0, 1.0 ),
697
+ vec2<f32>( -1.0, -1.0 ),
698
+ vec2<f32>( 1.0, -1.0 )
699
+ );
700
+
701
+ var tex = array< vec2<f32>, 4 >(
702
+ vec2<f32>( 0.0, 0.0 ),
703
+ vec2<f32>( 1.0, 0.0 ),
704
+ vec2<f32>( 0.0, 1.0 ),
705
+ vec2<f32>( 1.0, 1.0 )
706
+ );
707
+
708
+ Varys.vTex = tex[ vertexIndex ];
709
+ Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
710
+
711
+ return Varys;
712
+
713
+ }
714
+ `,n=`
715
+ @group( 0 ) @binding( 0 )
716
+ var imgSampler : sampler;
717
+
718
+ @group( 0 ) @binding( 1 )
719
+ var img : texture_2d<f32>;
720
+
721
+ @fragment
722
+ fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
723
+
724
+ return textureSample( img, imgSampler, vTex );
725
+
726
+ }
727
+ `,r=`
728
+ @group( 0 ) @binding( 0 )
729
+ var imgSampler : sampler;
730
+
731
+ @group( 0 ) @binding( 1 )
732
+ var img : texture_2d<f32>;
733
+
734
+ @fragment
735
+ fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
736
+
737
+ return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
738
+
739
+ }
740
+ `;this.mipmapSampler=e.createSampler({minFilter:er.Linear}),this.flipYSampler=e.createSampler({minFilter:er.Nearest}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:t}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:n}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:r})}getTransferPipeline(e){let t=this.transferPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Fr.TriangleStrip,stripIndexFormat:Xr.Uint32},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Fr.TriangleStrip,stripIndexFormat:Xr.Uint32},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,n=0){const r=t.format,{width:s,height:o}=t.size,a=this.getTransferPipeline(r),u=this.getFlipYPipeline(r),l=this.device.createTexture({size:{width:s,height:o,depthOrArrayLayers:1},format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:We.TwoD,baseArrayLayer:n}),d=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:We.TwoD,baseArrayLayer:0}),h=this.device.createCommandEncoder({}),p=(f,g,m)=>{const y=f.getBindGroupLayout(0),_=this.device.createBindGroup({layout:y,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:g}]}),T=h.beginRenderPass({colorAttachments:[{view:m,loadOp:xe.Clear,storeOp:rt.Store,clearValue:[0,0,0,0]}]});T.setPipeline(f),T.setBindGroup(0,_),T.draw(4,1,0,0),T.end()};p(a,c,d),p(u,d,c),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(e,t,n=0,r=null){const s=this.get(e);s.layers===void 0&&(s.layers=[]);const o=s.layers[n]||this._mipmapCreateBundles(e,t,n),a=r||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(a,o),r===null&&this.device.queue.submit([a.finish()]),s.layers[n]=o}_mipmapCreateBundles(e,t,n){const r=this.getTransferPipeline(t.format),s=r.getBindGroupLayout(0);let o=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:We.TwoD,baseArrayLayer:n});const a=[];for(let u=1;u<t.mipLevelCount;u++){const l=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:o}]}),c=e.createView({baseMipLevel:u,mipLevelCount:1,dimension:We.TwoD,baseArrayLayer:n}),d={colorAttachments:[{view:c,loadOp:xe.Clear,storeOp:rt.Store,clearValue:[0,0,0,0]}]},h=this.device.createRenderBundleEncoder({colorFormats:[t.format]});h.setPipeline(r),h.setBindGroup(0,l),h.draw(4,1,0,0),a.push({renderBundles:[h.finish()],passDescriptor:d}),o=c}return a}_mipmapRunBundles(e,t){const n=t.length;for(let r=0;r<n;r++){const s=t[r],o=e.beginRenderPass(s.passDescriptor);o.executeBundles(s.renderBundles),o.end()}}}const qw={[Dh]:"never",[Ao]:"less",[Mh]:"equal",[Ph]:"less-equal",[Eh]:"greater",[Ch]:"greater-equal",[Bh]:"always",[Ah]:"not-equal"},Hw=[0,1,3,2,4,5];class Xw{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 r=this._samplerCache.get(n);if(r===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};o.magFilter===er.Linear&&o.minFilter===er.Linear&&o.mipmapFilter===er.Linear&&(o.maxAnisotropy=e.anisotropy),e.isDepthTexture&&e.compareFunction!==null&&(o.compare=qw[e.compareFunction]),r={sampler:t.device.createSampler(o),usedTimes:0},this._samplerCache.set(n,r)}const s=t.get(e);if(s.sampler!==r.sampler){if(s.sampler!==void 0){const o=this._samplerCache.get(s.samplerKey);o.usedTimes--,o.usedTimes===0&&this._samplerCache.delete(s.samplerKey)}s.samplerKey=n,s.sampler=r.sampler,r.usedTimes++}return n}createDefaultTexture(e){let t;const n=qu(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(n):t=this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,r=n.get(e);if(r.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture){r.texture=e.sourceTexture,r.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:s,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||qu(e,n.device);r.format=c;const{samples:d,primarySamples:h,isMSAA:p}=n.utils.getTextureSampleData(e);let f=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(f|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&c!==b.RGB9E5UFloat&&(f|=GPUTextureUsage.RENDER_ATTACHMENT);const g={label:e.name,size:{width:s,height:o,depthOrArrayLayers:a},mipLevelCount:u,sampleCount:h,dimension:l,format:c,usage:f};if(c===void 0){z("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}if(e.isCubeTexture&&(g.textureBindingViewDimension=We.Cube),r.texture=n.device.createTexture(g),p){const m=Object.assign({},g);m.label=m.label+"-msaa",m.sampleCount=d,m.mipLevelCount=1,r.msaaTexture=n.device.createTexture(m)}r.initialized=!0,r.textureDescriptorGPU=g}destroyTexture(e,t=!1){const n=this.backend,r=n.get(e);r.texture!==void 0&&t===!1&&r.texture.destroy(),r.msaaTexture!==void 0&&r.msaaTexture.destroy(),n.delete(e)}generateMipmaps(e,t=null){const n=this.backend.get(e);if(e.isCubeTexture)for(let r=0;r<6;r++)this._generateMipmaps(n.texture,n.textureDescriptorGPU,r,t);else{const r=e.image.depth||1;for(let s=0;s<r;s++)this._generateMipmaps(n.texture,n.textureDescriptorGPU,s,t)}}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:r}=e.getDrawingBufferSize(),s=e.renderer.currentSamples,o=t.colorTexture,a=e.get(o);if(o.width===n&&o.height===r&&o.samples===s)return a.texture;let u=a.texture;return u&&u.destroy(),u=e.device.createTexture({label:"colorBuffer",size:{width:n,height:r,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=r,o.samples=s,a.texture=u,u}getDepthBuffer(e=!0,t=!1){const n=this.backend,r=n.renderer.getCanvasTarget(),{width:s,height:o}=n.getDrawingBufferSize(),a=n.renderer.currentSamples,u=r.depthTexture;if(u.width===s&&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=Dn,d=Bn):e&&(c=Fn,d=je),l!==void 0){if(u.image.width===s&&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=s,u.image.height=o,u.samples=a,this.createTexture(u,{width:s,height:o}),n.get(u).texture}updateTexture(e,t){const n=this.backend.get(e),r=e.mipmaps,{textureDescriptorGPU:s}=n;if(!(e.isRenderTargetTexture||s===void 0)){if(e.isDataTexture)if(r.length>0)for(let o=0,a=r.length;o<a;o++){const u=r[o];this._copyBufferToTexture(u,n.texture,s,0,e.flipY,0,o)}else this._copyBufferToTexture(t.image,n.texture,s,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let o=0;o<t.image.depth;o++)this._copyBufferToTexture(t.image,n.texture,s,o,e.flipY,o);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,n.texture,s);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,s);else if(r.length>0)for(let o=0,a=r.length;o<a;o++){const u=r[o];this._copyImageToTexture(u,n.texture,s,0,e.flipY,e.premultiplyAlpha,o)}else this._copyImageToTexture(t.image,n.texture,s,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,r,s,o){const a=this.backend.device,u=this.backend.get(e),l=u.texture,c=u.textureDescriptorGPU.format,d=this._getBytesPerTexel(c);let h=r*d;h=Math.ceil(h/256)*256;const p=a.createBuffer({size:(s-1)*h+r*d,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),f=a.createCommandEncoder();f.copyTextureToBuffer({texture:l,origin:{x:t,y:n,z:o}},{buffer:p,bytesPerRow:h},{width:r,height:s});const g=this._getTypedArrayType(c);a.queue.submit([f.finish()]),await p.mapAsync(GPUMapMode.READ);const m=p.getMappedRange();return new g(m)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const n=new dl;n.minFilter=Bt,n.magFilter=Bt,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 cl;n.minFilter=Bt,n.magFilter=Bt,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 r=e.images,s=e.mipmaps;for(let o=0;o<6;o++){const a=r[o],u=e.flipY===!0?Hw[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<s.length;l++){const d=s[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,r,s,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:s},{texture:t,mipLevel:a,origin:{x:0,y:0,z:r},premultipliedAlpha:o},{width:l,height:c,depthOrArrayLayers:1})}catch{}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new jw(this.backend.device)),e}_generateMipmaps(e,t,n=0,r=null){this._getPassUtils().generateMipmaps(e,t,n,r)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,r,s,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:r}},l,{offset:e.width*e.height*c*o,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),s===!0&&this._flipY(t,n,r)}_copyCompressedBufferToTexture(e,t,n){const r=this.backend.device,s=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/s.width)*s.byteLength,p=h*Math.ceil(c/s.height);for(let f=0;f<d;f++)r.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:f}},u.data,{offset:f*p,bytesPerRow:h,rowsPerImage:Math.ceil(c/s.height)},{width:Math.ceil(l/s.width)*s.width,height:Math.ceil(c/s.height)*s.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=ka.ClampToEdge;return e===wo?t=ka.Repeat:e===Ro&&(t=ka.MirrorRepeat),t}_convertFilterMode(e){let t=er.Linear;return(e===Bt||e===wh||e===qs)&&(t=er.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)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.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)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)return Uint16Array;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=nh.ThreeD:t=nh.TwoD,t}}function qu(i,e=null){const t=i.format,n=i.type,r=i.colorSpace,s=Ve.getTransfer(r);let o;if(i.isCompressedTexture===!0||i.isCompressedArrayTexture===!0)switch(t){case Vi:case $i:o=s===re?b.BC1RGBAUnormSRGB:b.BC1RGBAUnorm;break;case zi:o=s===re?b.BC2RGBAUnormSRGB:b.BC2RGBAUnorm;break;case Wi:o=s===re?b.BC3RGBAUnormSRGB:b.BC3RGBAUnorm;break;case _u:o=b.BC4RUnorm;break;case xu:o=b.BC4RSnorm;break;case io:o=b.BC5RGUnorm;break;case Tu:o=b.BC5RGSnorm;break;case bu:o=s===re?b.BC7RGBAUnormSRGB:b.BC7RGBAUnorm;break;case Ja:case Za:o=s===re?b.ETC2RGB8UnormSRGB:b.ETC2RGB8Unorm;break;case eu:o=s===re?b.ETC2RGBA8UnormSRGB:b.ETC2RGBA8Unorm;break;case tu:o=b.EACR11Unorm;break;case nu:o=b.EACR11Snorm;break;case so:o=b.EACRG11Unorm;break;case ru:o=b.EACRG11Snorm;break;case su:o=s===re?b.ASTC4x4UnormSRGB:b.ASTC4x4Unorm;break;case iu:o=s===re?b.ASTC5x4UnormSRGB:b.ASTC5x4Unorm;break;case ou:o=s===re?b.ASTC5x5UnormSRGB:b.ASTC5x5Unorm;break;case au:o=s===re?b.ASTC6x5UnormSRGB:b.ASTC6x5Unorm;break;case uu:o=s===re?b.ASTC6x6UnormSRGB:b.ASTC6x6Unorm;break;case lu:o=s===re?b.ASTC8x5UnormSRGB:b.ASTC8x5Unorm;break;case cu:o=s===re?b.ASTC8x6UnormSRGB:b.ASTC8x6Unorm;break;case du:o=s===re?b.ASTC8x8UnormSRGB:b.ASTC8x8Unorm;break;case hu:o=s===re?b.ASTC10x5UnormSRGB:b.ASTC10x5Unorm;break;case fu:o=s===re?b.ASTC10x6UnormSRGB:b.ASTC10x6Unorm;break;case pu:o=s===re?b.ASTC10x8UnormSRGB:b.ASTC10x8Unorm;break;case gu:o=s===re?b.ASTC10x10UnormSRGB:b.ASTC10x10Unorm;break;case mu:o=s===re?b.ASTC12x10UnormSRGB:b.ASTC12x10Unorm;break;case yu:o=s===re?b.ASTC12x12UnormSRGB:b.ASTC12x12Unorm;break;case Ft:o=s===re?b.RGBA8UnormSRGB:b.RGBA8Unorm;break;default:G("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case Ft:switch(n){case Ps:o=b.RGBA8Snorm;break;case Bs:o=b.RGBA16Sint;break;case Pr:o=b.RGBA16Uint;break;case je:o=b.RGBA32Uint;break;case st:o=b.RGBA32Sint;break;case bt:o=s===re?b.RGBA8UnormSRGB:b.RGBA8Unorm;break;case it:o=b.RGBA16Float;break;case vt:o=b.RGBA32Float;break;default:G("WebGPURenderer: Unsupported texture type with RGBAFormat.",n)}break;case il:switch(n){case ef:o=b.RGB9E5UFloat;break;case tf:o=b.RG11B10UFloat;break;default:G("WebGPURenderer: Unsupported texture type with RGBFormat.",n)}break;case ol:switch(n){case Ps:o=b.R8Snorm;break;case Bs:o=b.R16Sint;break;case Pr:o=b.R16Uint;break;case je:o=b.R32Uint;break;case st:o=b.R32Sint;break;case bt:o=b.R8Unorm;break;case it:o=b.R16Float;break;case vt:o=b.R32Float;break;default:G("WebGPURenderer: Unsupported texture type with RedFormat.",n)}break;case hn:switch(n){case Ps:o=b.RG8Snorm;break;case Bs:o=b.RG16Sint;break;case Pr:o=b.RG16Uint;break;case je:o=b.RG32Uint;break;case st:o=b.RG32Sint;break;case bt:o=b.RG8Unorm;break;case it:o=b.RG16Float;break;case vt:o=b.RG32Float;break;default:G("WebGPURenderer: Unsupported texture type with RGFormat.",n)}break;case Fn:switch(n){case Pr:o=b.Depth16Unorm;break;case je:o=b.Depth24Plus;break;case vt:o=b.Depth32Float;break;default:G("WebGPURenderer: Unsupported texture type with DepthFormat.",n)}break;case Dn:switch(n){case Bn:o=b.Depth24PlusStencil8;break;case vt:e&&e.features.has(ju.Depth32FloatStencil8)===!1&&G('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=b.Depth32FloatStencil8;break;default:G("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",n)}break;case al:switch(n){case st:o=b.R32Sint;break;case je:o=b.R32Uint;break;default:G("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",n)}break;case ul:switch(n){case st:o=b.RG32Sint;break;case je:o=b.RG32Uint;break;default:G("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",n)}break;case ll:switch(n){case st:o=b.RGBA32Sint;break;case je:o=b.RGBA32Uint;break;default:G("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",n)}break;default:G("WebGPURenderer: Unsupported texture format.",t)}return o}const Kw=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,Yw=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,sh={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"},Qw=i=>{i=i.trim();const e=i.match(Kw);if(e!==null&&e.length===4){const t=e[2],n=[];let r=null;for(;(r=Yw.exec(t))!==null;)n.push({name:r[1],type:r[2]});const s=[];for(let c=0;c<n.length;c++){const{name:d,type:h}=n[c];let p=h;p.startsWith("ptr")?p="pointer":(p.startsWith("texture")&&(p=h.split("<")[0]),p=sh[p]),s.push(new Vl(p,d))}const o=i.substring(e[0].length),a=e[3]||"void",u=e[1]!==void 0?e[1]:"";return{type:sh[a]||a,inputs:s,name:u,inputsCode:t,blockCode:o,outputType:a}}else throw new Error("FunctionNode: Function is not a WGSL code.")};class Zw extends zl{constructor(e){const{type:t,inputs:n,name:r,inputsCode:s,blockCode:o,outputType:a}=Qw(e);super(t,n,r),this.inputsCode=s,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 Jw extends vg{parseFunction(e){return new Zw(e)}}const eA={[Nt.READ_ONLY]:"read",[Nt.WRITE_ONLY]:"write",[Nt.READ_WRITE]:"read_write"},ih={[wo]:"repeat",[js]:"clamp",[Ro]:"mirror"},Di={vertex:nr.VERTEX,fragment:nr.FRAGMENT,compute:nr.COMPUTE},oh={instance:!0,swizzleAssign:!1,storageBuffer:!0},tA={"^^":"tsl_xor"},nA={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>"},ah={},Rs={tsl_xor:new Qe("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Qe("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Qe("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Qe("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Qe("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Qe("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Qe("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Qe("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 Qe("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 Qe("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Qe("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 Qe("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Qe(`
741
+ fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
742
+
743
+ let res = vec2f( iRes );
744
+
745
+ let uvScaled = coord * res;
746
+ let uvWrapping = ( ( uvScaled % res ) + res ) % res;
747
+
748
+ // https://www.shadertoy.com/view/WtyXRy
749
+
750
+ let uv = uvWrapping - 0.5;
751
+ let iuv = floor( uv );
752
+ let f = fract( uv );
753
+
754
+ let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
755
+ let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
756
+ let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
757
+ let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
758
+
759
+ return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
760
+
761
+ }
762
+ `)},rA={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 Dg="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(Dg+=`diagnostic( off, derivative_uniformity );
763
+ `);class sA extends Tg{constructor(e,t){super(e,t,new Jw),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,n,r,s,o=this.shaderStage){return o==="fragment"?r?s?`textureSample( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:s?`textureSample( ${t}, ${t}_sampler, ${n}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",r)}generateTextureSampleLevel(e,t,n,r,s,o){return this.isUnfilterable(e)===!1?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,r):this.generateTextureLod(e,t,n,s,o,r)}generateWrapFunction(e){const t=`tsl_coord_${ih[e.wrapS]}S_${ih[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let n=ah[t];if(n===void 0){const r=[],s=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let o=`fn ${t}( coord : ${s} ) -> ${s} {
764
+
765
+ return ${s}(
766
+ `;const a=(u,l)=>{u===wo?(r.push(Rs.repeatWrapping_float),o+=` tsl_repeatWrapping_float( coord.${l} )`):u===js?(r.push(Rs.clampWrapping_float),o+=` tsl_clampWrapping_float( coord.${l} )`):u===Ro?(r.push(Rs.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+=`,
767
+ `,a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(o+=`,
768
+ `,a(e.wrapR,"z")),o+=`
769
+ );
770
+
771
+ }
772
+ `,ah[t]=n=new Qe(o,r)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const r=this.getDataFromNode(e,this.shaderStage,this.globalCache);r.dimensionsSnippet===void 0&&(r.dimensionsSnippet={});let s=r.dimensionsSnippet[n];if(r.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} )`:""}`,s=new Ki(new Yi(`textureDimensions( ${o} )`,a)),r.dimensionsSnippet[n]=s,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(r.arrayLayerCount=new Ki(new Yi(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(r.cubeFaceCount=new Ki(new Yi("6u","u32")))}return s.build(this)}generateFilteredTexture(e,t,n,r,s="0u"){this._include("biquadraticTexture");const o=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,s);return r&&(n=`${n} + vec2<f32>(${r}) / ${a}`),`tsl_biquadraticTexture( ${t}, ${o}( ${n} ), ${a}, u32( ${s} ) )`}generateTextureLod(e,t,n,r,s,o="0u"){const a=this.generateWrapFunction(e),u=this.generateTextureDimension(e,t,o),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";s&&(n=`${n} + ${l}<f32>(${s}) / ${l}<f32>( ${u} )`);const c=`${l}<u32>( ${a}( ${n} ) * ${l}<f32>( ${u} ) )`;return this.generateTextureLoad(e,t,c,o,r,null)}generateTextureLoad(e,t,n,r,s,o){r===null&&(r="0u"),o&&(n=`${n} + ${o}`);let a;return s?a=`textureLoad( ${t}, ${n}, ${s}, u32( ${r} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${r} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,n,r,s){let o;return r?o=`textureStore( ${t}, ${n}, ${r}, ${s} )`:o=`textureStore( ${t}, ${n}, ${s} )`,o}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.isDataTexture===!0&&e.type===vt||this.isSampleCompare(e)===!1&&e.minFilter===Bt&&e.magFilter===Bt||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,r,s,o=this.shaderStage){let a=null;return this.isUnfilterable(e)?a=this.generateTextureLod(e,t,n,r,s,"0",o):a=this._generateTextureSample(e,t,n,r,s,o),a}generateTextureGrad(e,t,n,r,s,o,a=this.shaderStage){if(a==="fragment")return o?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]}, ${o} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]} )`;G(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,r,s,o,a=this.shaderStage){if(a==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${r}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${r} )`:o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r} )`;G(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,n,r,s,o){return this.isUnfilterable(e)===!1?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,r):this.generateTextureLod(e,t,n,s,o,r)}generateTextureBias(e,t,n,r,s,o,a=this.shaderStage){if(a==="fragment")return o?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${o} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r} )`;G(`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,r=e.type;return r==="texture"||r==="cubeTexture"||r==="cubeDepthTexture"||r==="storageTexture"||r==="texture3D"?n:r==="buffer"||r==="storageBuffer"||r==="indirectStorageBuffer"?this.isCustomStruct(e)?n:n+".value":e.groupNode.name+"."+n}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=tA[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."),Nt.READ_WRITE):Nt.READ_ONLY:e.access}getStorageAccess(e,t){return eA[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,r=null){const s=super.getUniformFromNode(e,t,n,r),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 Wu(s.name,s.node,u,h):d=new Go(s.name,s.node,u,h):t==="cubeTexture"||t==="cubeDepthTexture"?d=new Mg(s.name,s.node,u,h):t==="texture3D"&&(d=new Wu(s.name,s.node,u,h)),d.store=e.isStorageTextureNode===!0,d.mipLevel=d.store?e.mipLevel:0,d.setVisibility(Di[n]),this.isUnfilterable(e.value)===!1&&d.store===!1){const p=new Vw(`${s.name}_sampler`,s.node,u);p.setVisibility(Di[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 p=t==="buffer"?Ag:Ww;h=new p(e,u),d.buffer=h}h.setVisibility(h.getVisibility()|Di[n]),c.push(h),a=h,s.name=r||"NodeBuffer_"+s.id}else{const d=this.uniformGroups[n]||(this.uniformGroups[n]={});let h=d[l];h===void 0&&(h=new Eg(l,u),h.setVisibility(Di[n]),d[l]=h,c.push(h)),a=this.getNodeUniform(s,t),h.addUniform(a)}o.uniformGPU=a}return s}getBuiltin(e,t,n,r=this.shaderStage){const s=this.builtins[r]||(this.builtins[r]=new Map);return s.has(e)===!1&&s.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),r=[];for(const o of t.inputs)r.push(o.name+" : "+this.getType(o.type));let s=`fn ${t.name}( ${r.join(", ")} ) -> ${this.getType(t.type)} {
773
+ ${n.vars}
774
+ ${n.code}
775
+ `;return n.result&&(s+=` return ${n.result};
776
+ `),s+=`
777
+ }
778
+ `,s}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 r of n)t.push(`enable ${r};`);return t.join(`
779
+ `)}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:r,property:s,type:o}of n.values())t.push(`@builtin( ${r} ) ${s} : ${o}`);return t.join(`,
780
+ `)}getScopedArray(e,t,n,r){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:r}),e}getScopedArrays(e){if(e!=="compute")return;const t=[];for(const{name:n,scope:r,bufferType:s,bufferCount:o}of this.scopedArrays.values()){const a=this.getType(s);t.push(`var<${r}> ${n}: array< ${a}, ${o} >;`)}return t.join(`
781
+ `)}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 r=this.getAttributesArray();for(let s=0,o=r.length;s<o;s++){const a=r[s],u=a.name,l=this.getType(a.type);t.push(`@location( ${s} ) ${u} : ${l}`)}}return t.join(`,
782
+ `)}getStructMembers(e){const t=[];for(const n of e.members){const r=e.output?"@location( "+n.index+" ) ":"";let s=this.getType(n.type);n.atomic&&(s="atomic< "+s+" >"),t.push(` ${r+n.name} : ${s}`)}return e.output&&t.push(` ${this.getBuiltins("output")}`),t.join(`,
783
+ `)}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const r=[];for(const s of n){let o=`struct ${s.name} {
784
+ `;o+=this.getStructMembers(s),o+=`
785
+ };`,r.push(o)}t=`
786
+ `+r.join(`
787
+
788
+ `)+`
789
+ `}return t}getVar(e,t,n=null){let r=`var ${t} : `;return n!==null?r+=this.generateArrayDeclaration(e,n):r+=this.getType(e),r}getVars(e){const t=[],n=this.vars[e];if(n!==void 0)for(const r of n)t.push(` ${this.getVar(r.type,r.name,r.count)};`);return`
790
+ ${t.join(`
791
+ `)}
792
+ `}getVaryings(e){const t=[];if(e==="vertex"&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),e==="vertex"||e==="fragment"){const s=this.varyings,o=this.vars[e];for(let a=0;a<s.length;a++){const u=s[a];if(u.needsInterpolation){let l=`@location( ${a} )`;if(u.interpolationType){const c=u.interpolationSampling!==null?`, ${u.interpolationSampling} )`:" )";l+=` @interpolate( ${u.interpolationType}${c}`}else/^(int|uint|ivec|uvec)/.test(u.type)&&(l+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${l} ${u.name} : ${this.getType(u.type)}`)}else e==="vertex"&&o.includes(u)===!1&&o.push(u)}}const n=this.getBuiltins(e);n&&t.push(n);const r=t.join(`,
793
+ `);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+r):r}isCustomStruct(e){const t=e.value,n=e.node,r=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&n.structTypeNode!==null,s=n.value&&n.value.array&&typeof n.value.itemSize=="number"&&n.value.array.length>n.value.itemSize;return r&&!s}getUniforms(e){const t=this.uniforms[e],n=[],r=[],s=[],o={};for(const u of t){const l=u.groupNode.name,c=this.bindingsIndexes[l];if(u.type==="texture"||u.type==="cubeTexture"||u.type==="cubeDepthTexture"||u.type==="storageTexture"||u.type==="texture3D"){const d=u.node.value;this.isUnfilterable(d)===!1&&u.node.isStorageTextureNode!==!0&&(this.isSampleCompare(d)?n.push(`@binding( ${c.binding++} ) @group( ${c.group} ) var ${u.name}_sampler : sampler_comparison;`):n.push(`@binding( ${c.binding++} ) @group( ${c.group} ) var ${u.name}_sampler : sampler;`));let h,p="";const{primarySamples:f}=this.renderer.backend.utils.getTextureSampleData(d);if(f>1&&(p="_multisampled"),d.isCubeTexture===!0&&d.isDepthTexture===!0)h="texture_depth_cube";else if(d.isCubeTexture===!0)h="texture_cube<f32>";else if(d.isDepthTexture===!0)this.renderer.backend.compatibilityMode&&d.compareFunction===null?h=`texture${p}_2d<f32>`:h=`texture_depth${p}_2d${d.isArrayTexture===!0?"_array":""}`;else if(u.node.isStorageTextureNode===!0){const g=qu(d),m=this.getStorageAccess(u.node,e),y=u.node.value.is3DTexture,_=u.node.value.isArrayTexture;h=`texture_storage_${y?"3d":`2d${_?"_array":""}`}<${g}, ${m}>`}else if(d.isArrayTexture===!0||d.isDataArrayTexture===!0||d.isCompressedArrayTexture===!0)h="texture_2d_array<f32>";else if(d.is3DTexture===!0||d.isData3DTexture===!0)h="texture_3d<f32>";else{const g=this.getComponentTypeFromTexture(d).charAt(0);h=`texture${p}_2d<${g}32>`}n.push(`@binding( ${c.binding++} ) @group( ${c.group} ) var ${u.name} : ${h};`)}else if(u.type==="buffer"||u.type==="storageBuffer"||u.type==="indirectStorageBuffer"){const d=u.node,h=this.getType(d.getNodeType(this)),p=d.bufferCount,f=p>0&&u.type==="buffer"?", "+p:"",g=d.isStorageBufferNode?`storage, ${this.getStorageAccess(d,e)}`:"uniform";if(this.isCustomStruct(u))r.push(`@binding( ${c.binding++} ) @group( ${c.group} ) var<${g}> ${u.name} : ${h};`);else{const y=` value : array< ${d.isAtomic?`atomic<${h}>`:`${h}`}${f} >`;r.push(this._getWGSLStructBinding(u.name,y,g,c.binding++,c.group))}}else{const d=this.getType(this.getVectorType(u.type)),h=u.groupNode.name;(o[h]||(o[h]={index:c.binding++,id:c.group,snippets:[]})).snippets.push(` ${u.name} : ${d}`)}}for(const u in o){const l=o[u];s.push(this._getWGSLStructBinding(u,l.snippets.join(`,
794
+ `),"uniform",l.index,l.id))}return[...n,...r,...s].join(`
795
+ `)}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let r=`// code
796
+
797
+ `;r+=this.flowCode[t];const s=this.flowNodes[t],o=s[s.length-1],a=o.outputNode,u=a!==void 0&&a.isOutputStructNode===!0;for(const l of s){const c=this.getFlowData(l),d=l.name;if(d&&(r.length>0&&(r+=`
798
+ `),r+=` // flow -> ${d}
799
+ `),r+=`${c.code}
800
+ `,l===o&&t!=="compute"){if(r+=`// result
801
+
802
+ `,t==="vertex")r+=`varyings.Vertex = ${c.result};`;else if(t==="fragment")if(u)n.returnType=a.getNodeType(this),n.structs+="var<private> output : "+n.returnType+";",r+=`return ${c.result};`;else{let h=" @location(0) color: vec4<f32>";const p=this.getBuiltins("output");p&&(h+=`,
803
+ `+p),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",h),n.structs+=`
804
+ var<private> output : OutputStruct;`,r+=`output.color = ${c.result};
805
+
806
+ return output;`}}}n.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 nA[e]||e}isAvailable(e){let t=oh[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),oh[e]=t),t}_getWGSLMethod(e){return Rs[e]!==void 0&&this._include(e),rA[e]}_include(e){const t=Rs[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}
807
+ // directives
808
+ ${e.directives}
809
+
810
+ // structs
811
+ ${e.structs}
812
+
813
+ // uniforms
814
+ ${e.uniforms}
815
+
816
+ // varyings
817
+ ${e.varyings}
818
+ var<private> varyings : VaryingsStruct;
819
+
820
+ // codes
821
+ ${e.codes}
822
+
823
+ @vertex
824
+ fn main( ${e.attributes} ) -> VaryingsStruct {
825
+
826
+ // vars
827
+ ${e.vars}
828
+
829
+ // flow
830
+ ${e.flow}
831
+
832
+ return varyings;
833
+
834
+ }
835
+ `}_getWGSLFragmentCode(e){return`${this.getSignature()}
836
+ // global
837
+ ${Dg}
838
+
839
+ // structs
840
+ ${e.structs}
841
+
842
+ // uniforms
843
+ ${e.uniforms}
844
+
845
+ // codes
846
+ ${e.codes}
847
+
848
+ @fragment
849
+ fn main( ${e.varyings} ) -> ${e.returnType} {
850
+
851
+ // vars
852
+ ${e.vars}
853
+
854
+ // flow
855
+ ${e.flow}
856
+
857
+ }
858
+ `}_getWGSLComputeCode(e,t){const[n,r,s]=t;return`${this.getSignature()}
859
+ // directives
860
+ ${e.directives}
861
+
862
+ // system
863
+ var<private> instanceIndex : u32;
864
+
865
+ // locals
866
+ ${e.scopedArrays}
867
+
868
+ // structs
869
+ ${e.structs}
870
+
871
+ // uniforms
872
+ ${e.uniforms}
873
+
874
+ // codes
875
+ ${e.codes}
876
+
877
+ @compute @workgroup_size( ${n}, ${r}, ${s} )
878
+ fn main( ${e.attributes} ) {
879
+
880
+ // system
881
+ instanceIndex = globalId.x
882
+ + globalId.y * ( ${n} * numWorkgroups.x )
883
+ + globalId.z * ( ${n} * numWorkgroups.x ) * ( ${r} * numWorkgroups.y );
884
+
885
+ // vars
886
+ ${e.vars}
887
+
888
+ // flow
889
+ ${e.flow}
890
+
891
+ }
892
+ `}_getWGSLStruct(e,t){return`
893
+ struct ${e} {
894
+ ${t}
895
+ };`}_getWGSLStructBinding(e,t,n,r=0,s=0){const o=e+"Struct";return`${this._getWGSLStruct(o,t)}
896
+ @binding( ${r} ) @group( ${s} )
897
+ var<${n}> ${e} : ${o};`}}class iA{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=b.Depth24PlusStencil8:e.depth&&(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 s=this.backend.renderer,o=s.getRenderTarget();t=o?o.samples:s.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 Fr.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return Fr.LineList;if(e.isLine)return Fr.LineStrip;if(e.isMesh)return Fr.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===bt)return b.BGRA8Unorm;if(t===it)return b.RGBA16Float;throw new Error("Unsupported output buffer type.")}}const Fg=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"&&Fg.set(Float16Array,["float16"]);const oA=new Map([[rf,["float16"]]]),aA=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class uA{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),r=this.backend,s=r.get(n);let o=s.buffer;if(o===void 0){const a=r.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,s._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(),s.buffer=o}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,r=n.device,s=n.get(t),o=n.get(t).buffer;let a=t.array;if(s._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)r.queue.writeBuffer(o,0,a,0);else{const l=eo(a),c=l?1:a.BYTES_PER_ELEMENT;for(let d=0,h=u.length;d<h;d++){const p=u[d];let f,g;if(s._force3to4BytesAlignment===!0){const y=Math.floor(p.start/3),_=Math.ceil(p.count/3);f=y*4*c,g=_*4*c}else f=p.start*c,g=p.count*c;const m=f*(l?a.BYTES_PER_ELEMENT:1);r.queue.writeBuffer(o,m,a,f,g)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let r=0;r<t.length;r++){const s=t[r],o=s.array.BYTES_PER_ELEMENT,a=this._getBufferAttribute(s);let u=n.get(a);if(u===void 0){let d,h;s.isInterleavedBufferAttribute===!0?(d=s.data.stride*o,h=s.data.isInstancedInterleavedBuffer?Bi.Instance:Bi.Vertex):(d=s.itemSize*o,h=s.isInstancedBufferAttribute?Bi.Instance:Bi.Vertex),s.normalized===!1&&(s.array.constructor===Int16Array||s.array.constructor===Uint16Array)&&(d=4),u={arrayStride:d,attributes:[],stepMode:h},n.set(a,u)}const l=this._getVertexFormat(s),c=s.isInterleavedBufferAttribute===!0?s.offset*o:0;u.attributes.push({shaderLocation:r,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){const t=this.backend,n=t.device,s=t.get(this._getBufferAttribute(e)).buffer,o=s.size,a=n.createBuffer({label:`${e.name}_readback`,size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),u=n.createCommandEncoder({label:`readback_encoder_${e.name}`});u.copyBufferToBuffer(s,0,a,0,o);const l=u.finish();n.queue.submit([l]),await a.mapAsync(GPUMapMode.READ);const c=a.getMappedRange(),d=new e.array.constructor(c.slice(0));return a.unmap(),d.buffer}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,r=e.array.constructor,s=e.constructor;let o;if(t===1)o=aA.get(r);else{const u=(oA.get(s)||Fg.get(r))[n?1:0];if(u){const l=r.BYTES_PER_ELEMENT*t,d=Math.floor((l+3)/4)*4/r.BYTES_PER_ELEMENT;if(d%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");o=`${u}x${d}`}}return o||G("WebGPUAttributeUtils: Vertex format not supported yet."),o}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class lA{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class cA{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,n=t.device,r=t.get(e);if(r.layout)return r.layout.layoutGPU;const s=this._createLayoutEntries(e),o=JSON.stringify(s);let a=this._bindGroupLayoutCache.get(o);return a===void 0&&(a=new lA(n.createBindGroupLayout({entries:s})),this._bindGroupLayoutCache.set(o,a)),a.usedTimes++,r.layout=a,r.layoutKey=o,a.layoutGPU}createBindings(e,t,n,r=0){const{backend:s}=this,o=s.get(e),a=this.createBindingsLayout(e);let u;n>0&&(o.groups===void 0&&(o.groups=[],o.versions=[]),o.versions[n]===r&&(u=o.groups[n])),u===void 0&&(u=this.createBindGroup(e,a),n>0&&(o.groups[n]=u,o.versions[n]=r)),o.group=u}updateBinding(e){const t=this.backend,n=t.device,r=e.buffer,s=t.get(e).buffer,o=e.updateRanges;if(o.length===0)n.queue.writeBuffer(s,0,r,0);else{const a=eo(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,p=d.count*u,f=h*(a?r.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(s,f,r,h,p)}e.clearUpdateRanges()}}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,o=e[0],a=r.createBuffer({label:"bindingCameraIndex_"+o,size:16,usage:s});r.queue.writeBuffer(a,0,e,0);const u=[{binding:0,resource:{buffer:a}}];return r.createBindGroup({label:"bindGroupCameraIndex_"+o,layout:t,entries:u})}createBindGroup(e,t){const n=this.backend,r=n.device;let s=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&nr.VERTEX&&d.push("vertex"),a.visibility&nr.FRAGMENT&&d.push("fragment"),a.visibility&nr.COMPUTE&&d.push("compute");const h=`(${d.join(",")})`,p=r.createBuffer({label:`bindingBuffer${a.id}_${a.name}_${h}`,size:l,usage:c});u.buffer=p}o.push({binding:s,resource:{buffer:u.buffer}})}else if(a.isStorageBuffer){const u=n.get(a);if(u.buffer===void 0){const l=a.attribute;u.buffer=n.get(l).buffer}o.push({binding:s,resource:{buffer:u.buffer}})}else if(a.isSampledTexture){const u=n.get(a.texture);let l;if(u.externalTexture!==void 0)l=r.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 p=Gw.All;let f;a.isSampledCubeTexture?f=We.Cube:a.isSampledTexture3D?f=We.ThreeD:a.texture.isArrayTexture||a.texture.isDataArrayTexture||a.texture.isCompressedArrayTexture?f=We.TwoDArray:f=We.TwoD,l=u[h]=u.texture.createView({aspect:p,dimension:f,mipLevelCount:c,baseMipLevel:d})}}o.push({binding:s,resource:l})}else if(a.isSampler){const u=n.get(a.texture);o.push({binding:s,resource:u.sampler})}s++}return r.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:o})}_createLayoutEntries(e){const t=[];let n=0;for(const r of e.bindings){const s=this.backend,o={binding:n,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){const a={};r.isStorageBuffer&&(r.visibility&nr.COMPUTE&&(r.access===Nt.READ_WRITE||r.access===Nt.WRITE_ONLY)?a.type=Ga.Storage:a.type=Ga.ReadOnlyStorage),o.buffer=a}else if(r.isSampledTexture&&r.store){const a={};a.format=this.backend.get(r.texture).texture.format;const u=r.access;u===Nt.READ_WRITE?a.access=Va.ReadWrite:u===Nt.WRITE_ONLY?a.access=Va.WriteOnly:a.access=Va.ReadOnly,r.texture.isArrayTexture?a.viewDimension=We.TwoDArray:r.texture.is3DTexture&&(a.viewDimension=We.ThreeD),o.storageTexture=a}else if(r.isSampledTexture){const a={},{primarySamples:u}=s.utils.getTextureSampleData(r.texture);if(u>1&&(a.multisampled=!0,r.texture.isDepthTexture||(a.sampleType=qn.UnfilterableFloat)),r.texture.isDepthTexture)s.compatibilityMode&&r.texture.compareFunction===null?a.sampleType=qn.UnfilterableFloat:a.sampleType=qn.Depth;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const l=r.texture.type;l===st?a.sampleType=qn.SInt:l===je?a.sampleType=qn.UInt:l===vt&&(this.backend.hasFeature("float32-filterable")?a.sampleType=qn.Float:a.sampleType=qn.UnfilterableFloat)}r.isSampledCubeTexture?a.viewDimension=We.Cube:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?a.viewDimension=We.TwoDArray:r.isSampledTexture3D&&(a.viewDimension=We.ThreeD),o.texture=a}else if(r.isSampler){const a={};r.texture.isDepthTexture&&(r.texture.compareFunction!==null?a.type=th.Comparison:s.compatibilityMode&&(a.type=th.NonFiltering)),o.sampler=a}else G(`WebGPUBindingUtils: Unsupported binding "${r}".`);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 dA{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:r,geometry:s,pipeline:o}=e,{vertexProgram:a,fragmentProgram:u}=o,l=this.backend,c=l.device,d=l.utils,h=l.get(o),p=[];for(const te of e.getBindings()){const ne=l.get(te),{layoutGPU:ue}=ne.layout;p.push(ue)}const f=l.attributeUtils.createShaderVertexBuffers(e);let g;r.blending!==$r&&(r.blending!==ir||r.transparent!==!1)&&(g=this._getBlending(r));let m={};r.stencilWrite===!0&&(m={compare:this._getStencilCompare(r),failOp:this._getStencilOperation(r.stencilFail),depthFailOp:this._getStencilOperation(r.stencilZFail),passOp:this._getStencilOperation(r.stencilZPass)});const y=this._getColorWriteMask(r),_=[];if(e.context.textures!==null){const te=e.context.textures;for(let ne=0;ne<te.length;ne++){const ue=d.getTextureFormatGPU(te[ne]);ne===0?_.push({format:ue,blend:g,writeMask:y}):_.push({format:ue,writeMask:y})}}else{const te=d.getCurrentColorFormat(e.context);_.push({format:te,blend:g,writeMask:y})}const T=l.get(a).module,A=l.get(u).module,B=this._getPrimitiveState(n,s,r),S=this._getDepthCompare(r),v=d.getCurrentDepthStencilFormat(e.context),E=this._getSampleCount(e.context),D={label:`renderPipeline_${r.name||r.type}_${r.id}`,vertex:Object.assign({},T,{buffers:f}),fragment:Object.assign({},A,{targets:_}),primitive:B,multisample:{count:E,alphaToCoverageEnabled:r.alphaToCoverage&&E>1},layout:c.createPipelineLayout({bindGroupLayouts:p})},O={},Y=e.context.depth,ee=e.context.stencil;if((Y===!0||ee===!0)&&(Y===!0&&(O.format=v,O.depthWriteEnabled=r.depthWrite,O.depthCompare=S),ee===!0&&(O.stencilFront=m,O.stencilBack={},O.stencilReadMask=r.stencilFuncMask,O.stencilWriteMask=r.stencilWriteMask),r.polygonOffset===!0&&(O.depthBias=r.polygonOffsetUnits,O.depthBiasSlopeScale=r.polygonOffsetFactor,O.depthBiasClamp=0),D.depthStencil=O),c.pushErrorScope("validation"),t===null)h.pipeline=c.createRenderPipeline(D),c.popErrorScope().then(te=>{te!==null&&(h.error=!0,G(te.message))});else{const te=new Promise(async ne=>{try{h.pipeline=await c.createRenderPipelineAsync(D)}catch{}const ue=await c.popErrorScope();ue!==null&&(h.error=!0,G(ue.message)),ne()});t.push(te)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:r,device:s}=n,o=r.getCurrentDepthStencilFormat(e),a=r.getCurrentColorFormats(e),u=this._getSampleCount(e),l={label:t,colorFormats:a,depthStencilFormat:o,sampleCount:u};return s.createRenderBundleEncoder(l)}createComputePipeline(e,t){const n=this.backend,r=n.device,s=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=r.createComputePipeline({compute:s,layout:r.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const r=e.blending,s=e.blendSrc,o=e.blendDst,a=e.blendEquation;if(r===Ms){const u=e.blendSrcAlpha!==null?e.blendSrcAlpha:s,l=e.blendDstAlpha!==null?e.blendDstAlpha:o,c=e.blendEquationAlpha!==null?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(s),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,p)=>{t={srcFactor:c,dstFactor:d,operation:jn.Add},n={srcFactor:h,dstFactor:p,operation:jn.Add}};if(u)switch(r){case ir:l(he.One,he.OneMinusSrcAlpha,he.One,he.OneMinusSrcAlpha);break;case ro:l(he.One,he.One,he.One,he.One);break;case no:l(he.Zero,he.OneMinusSrc,he.Zero,he.One);break;case to:l(he.Dst,he.OneMinusSrcAlpha,he.Zero,he.One);break}else switch(r){case ir:l(he.SrcAlpha,he.OneMinusSrcAlpha,he.One,he.OneMinusSrcAlpha);break;case ro:l(he.SrcAlpha,he.One,he.One,he.One);break;case no:G("WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case to:G("WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true");break}}if(t!==void 0&&n!==void 0)return{color:t,alpha:n};G("WebGPURenderer: Invalid blending: ",r)}_getBlendFactor(e){let t;switch(e){case wn:t=he.Zero;break;case jh:t=he.One;break;case Wh:t=he.Src;break;case kh:t=he.OneMinusSrc;break;case zh:t=he.SrcAlpha;break;case Ih:t=he.OneMinusSrcAlpha;break;case Vh:t=he.Dst;break;case Oh:t=he.OneMinusDst;break;case Gh:t=he.DstAlpha;break;case Uh:t=he.OneMinusDstAlpha;break;case $h:t=he.SrcAlphaSaturated;break;case GS:t=he.Constant;break;case VS:t=he.OneMinusConstant;break;default:G("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case $m:t=Ye.Never;break;case Vm:t=Ye.Always;break;case Gm:t=Ye.Less;break;case km:t=Ye.LessEqual;break;case Im:t=Ye.Equal;break;case Om:t=Ye.GreaterEqual;break;case Um:t=Ye.Greater;break;case Lm:t=Ye.NotEqual;break;default:G("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case Ym:t=Nn.Keep;break;case Km:t=Nn.Zero;break;case Xm:t=Nn.Replace;break;case Hm:t=Nn.Invert;break;case qm:t=Nn.IncrementClamp;break;case jm:t=Nn.DecrementClamp;break;case Wm:t=Nn.IncrementWrap;break;case zm:t=Nn.DecrementWrap;break;default:G("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case an:t=jn.Add;break;case Lh:t=jn.Subtract;break;case Fh:t=jn.ReverseSubtract;break;case Zm:t=jn.Min;break;case Qm:t=jn.Max;break;default:G("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const r={},s=this.backend.utils;r.topology=s.getPrimitiveTopology(e,n),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?Xr.Uint16:Xr.Uint32);let o=n.side===ht;return e.isMesh&&e.matrixWorld.determinant()<0&&(o=!o),r.frontFace=o===!0?Zd.CW:Zd.CCW,r.cullMode=n.side===rr?Jd.None:Jd.Back,r}_getColorWriteMask(e){return e.colorWrite===!0?eh.All:eh.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=Ye.Always;else{const n=e.depthFunc;switch(n){case Jh:t=Ye.Never;break;case Zh:t=Ye.Always;break;case Qh:t=Ye.Less;break;case Yh:t=Ye.LessEqual;break;case Kh:t=Ye.Equal;break;case Xh:t=Ye.GreaterEqual;break;case Hh:t=Ye.Greater;break;case qh:t=Ye.NotEqual;break;default:G("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class hA extends Bg{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 r=this.maxQueries*8;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Ge(`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 r=this.device.createCommandEncoder();r.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),r.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const s=r.finish();if(this.device.queue.submit([s]),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+)$/),p=parseInt(h[2]);u.includes(p)===!1&&u.push(p),a[p]===void 0&&(a[p]=0);const f=o[d],g=o[d+1],m=Number(g-f)/1e6;this.timestamps.set(c,m),a[p]+=m}const l=a[u[u.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=u,l}catch(e){return G("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){G("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){G("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}}}class fA extends Pg{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.compatibilityMode=e.compatibilityMode===void 0?!1:e.compatibilityMode,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new iA(this),this.attributeUtils=new uA(this),this.bindingUtils=new cA(this),this.pipelineUtils=new dA(this),this.textureUtils=new Xw(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let n;if(t.device===void 0){const r={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},s=typeof navigator<"u"?await navigator.gpu.requestAdapter(r):null;if(s===null)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const o=Object.values(ju),a=[];for(const l of o)s.features.has(l)&&a.push(l);const u={requiredFeatures:a,requiredLimits:t.requiredLimits};n=await s.requestDevice(u)}else n=t.device;n.lost.then(r=>{if(r.reason==="destroyed")return;const s={api:"WebGPU",message:r.message||"Unknown reason",reason:r.reason||null,originalEvent:r};e.onDeviceLost(s)}),this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(ju.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let n=t.context;if(n===void 0){const r=this.parameters;e.isDefaultCanvasTarget===!0&&r.context!==void 0?n=r.context:n=e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${No} webgpu`);const s=r.alpha?"premultiplied":"opaque",o=r.outputType===it?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:s,toneMapping:{mode:o}}),t.context=n}return n}get coordinateSystem(){return Gr}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),r=e.currentSamples;let s=n.descriptor;if(s===void 0||n.samples!==r){s={colorAttachments:[{view:null}]},(e.depth===!0||e.stencil===!0)&&(s.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const a=s.colorAttachments[0];r>0?a.view=this.textureUtils.getColorBuffer().createView():a.resolveTarget=void 0,n.descriptor=s,n.samples=r}const o=s.colorAttachments[0];return r>0?o.resolveTarget=this.context.getCurrentTexture().createView():o.view=this.context.getCurrentTexture().createView(),s}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,r=this.get(n);let s=r.descriptors;(s===void 0||r.width!==n.width||r.height!==n.height||r.samples!==n.samples)&&(s={},r.descriptors=s);const o=e.getCacheKey();let a=s[o];if(a===void 0){const l=e.textures,c=[];let d;const h=this._isRenderCameraDepthArray(e);for(let p=0;p<l.length;p++){const f=this.get(l[p]),g={label:`colorAttachment_${p}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:We.TwoD};if(n.isRenderTarget3D)d=e.activeCubeFace,g.baseArrayLayer=0,g.dimension=We.ThreeD,g.depthOrArrayLayers=l[p].image.depth;else if(n.isRenderTarget&&l[p].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:We.TwoD},T=f.texture.createView(_);c.push({view:T,resolveTarget:void 0,depthSlice:void 0})}}else g.dimension=We.TwoDArray,g.depthOrArrayLayers=l[p].image.depth;if(h!==!0){const m=f.texture.createView(g);let y,_;f.msaaTexture!==void 0?(y=f.msaaTexture.createView(),_=m):(y=m,_=void 0),c.push({view:y,resolveTarget:_,depthSlice:d})}}if(a={textureViews:c},e.depth){const p=this.get(e.depthTexture),f={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(f.dimension=We.TwoD,f.arrayLayerCount=1,f.baseArrayLayer=e.activeCubeFace),a.depthStencilView=p.texture.createView(f)}s[o]=a,r.width=n.width,r.height=n.height,r.samples=n.samples,r.activeMipmapLevel=e.activeMipmapLevel,r.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||xe.Load,storeOp:t.storeOp||rt.Store,clearValue:d})}return a.depthStencilView&&(u.depthStencilAttachment={view:a.depthStencilView}),u}beginRender(e){const t=this.get(e),n=this.device,r=e.occlusionQueryCount;let s;r>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,s=n.createQuerySet({type:"occlusion",count:r,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=s,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(r),t.lastOcclusionObject=null);let o;e.textures===null?o=this._getDefaultRenderPassDescriptor():o=this._getRenderPassDescriptor(e,{loadOp:xe.Load}),this.initTimestampQuery(Kt.RENDER,this.getTimestampUID(e),o),o.occlusionQuerySet=s;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?(d.clearValue=c===0?e.clearColorValue:{r:0,g:0,b:0,a:1},d.loadOp=xe.Clear):d.loadOp=xe.Load,d.storeOp=rt.Store}}else{const l=o.colorAttachments[0];e.clearColor?(l.clearValue=e.clearColorValue,l.loadOp=xe.Clear):l.loadOp=xe.Load,l.storeOp=rt.Store}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=xe.Clear):a.depthLoadOp=xe.Load,a.depthStoreOp=rt.Store),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=xe.Clear):a.stencilLoadOp=xe.Load,a.stencilStoreOp=rt.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,r){const s=n.depthStencilAttachment;t.layerDescriptors=[];const o=this.get(e.depthTexture);o.viewCache||(o.viewCache=[]);for(let a=0;a<r.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:We.TwoD,baseArrayLayer:a,arrayLayerCount:1})),u.depthStencilAttachment={view:o.viewCache[l],depthLoadOp:s.depthLoadOp||xe.Clear,depthStoreOp:s.depthStoreOp||rt.Store,depthClearValue:s.depthClearValue||1},e.stencil&&(u.depthStencilAttachment.stencilLoadOp=s.stencilLoadOp,u.depthStencilAttachment.stencilStoreOp=s.stencilStoreOp,u.depthStencilAttachment.stencilClearValue=s.stencilClearValue)}else u.depthStencilAttachment={...s};t.layerDescriptors.push(u)}}_updateDepthLayerDescriptors(e,t,n){for(let r=0;r<n.length;r++){const s=t.layerDescriptors[r];if(s.depthStencilAttachment){const o=s.depthStencilAttachment;e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=xe.Clear):o.depthLoadOp=xe.Load),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=xe.Clear):o.stencilLoadOp=xe.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 r=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const s=[];for(let o=0;o<t.bundleEncoders.length;o++){const a=t.bundleEncoders[o];s.push(a.finish())}for(let o=0;o<t.layerDescriptors.length;o++)if(o<s.length){const a=t.layerDescriptors[o],u=r.beginRenderPass(a);if(e.viewport){const{x:l,y:c,width:d,height:h,minDepth:p,maxDepth:f}=e.viewportValue;u.setViewport(l,c,d,h,p,f)}if(e.scissor){const{x:l,y:c,width:d,height:h}=e.scissorValue;u.setScissorRect(l,c,d,h)}u.executeBundles([s[o]]),u.end()}}else t.currentPass&&t.currentPass.end();if(n>0){const s=n*8;let o=this.occludedResolveCache.get(s);o===void 0&&(o=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,o));const a=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,o,0),t.encoder.copyBufferToBuffer(o,0,a,0,s),t.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),e.textures!==null){const s=e.textures;for(let o=0;o<s.length;o++){const a=s[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:r}=t;if(n&&r){const s=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<r.length;u++)a[u]===BigInt(0)&&s.add(r[u]);n.destroy(),t.occluded=s}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:r,width:s,height:o,minDepth:a,maxDepth:u}=e.viewportValue;t.setViewport(n,r,s,o,a,u)}updateScissor(e){const{currentPass:t}=this.get(e),{x:n,y:r,width:s,height:o}=e.scissorValue;t.setScissorRect(n,r,s,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,r=null){const s=this.device,o=this.renderer;let a=[],u,l,c,d;if(e){const f=this.getClearColor();l={r:f.r,g:f.g,b:f.b,a:f.a}}if(r===null){c=o.depth,d=o.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){a=f.colorAttachments;const g=a[0];g.clearValue=l,g.loadOp=xe.Clear,g.storeOp=rt.Store}(c||d)&&(u=f.depthStencilAttachment)}else{c=r.depth,d=r.stencil;const f={loadOp:e?xe.Clear:xe.Load,clearValue:e?l:void 0};c&&(f.depthLoadOp=t?xe.Clear:xe.Load,f.depthClearValue=t?o.getClearDepth():void 0,f.depthStoreOp=rt.Store),d&&(f.stencilLoadOp=n?xe.Clear:xe.Load,f.stencilClearValue=n?o.getClearStencil():void 0,f.stencilStoreOp=rt.Store);const g=this._getRenderPassDescriptor(r,f);a=g.colorAttachments,u=g.depthStencilAttachment}c&&u&&(t?(u.depthLoadOp=xe.Clear,u.depthClearValue=o.getClearDepth(),u.depthStoreOp=rt.Store):(u.depthLoadOp=xe.Load,u.depthStoreOp=rt.Store)),d&&u&&(n?(u.stencilLoadOp=xe.Clear,u.stencilClearValue=o.getClearStencil(),u.stencilStoreOp=rt.Store):(u.stencilLoadOp=xe.Load,u.stencilStoreOp=rt.Store));const h=s.createCommandEncoder({label:"clear"});h.beginRenderPass({colorAttachments:a,depthStencilAttachment:u}).end(),s.queue.submit([h.finish()])}beginCompute(e){const t=this.get(e),n={label:"computeGroup_"+e.id};this.initTimestampQuery(Kt.COMPUTE,this.getTimestampUID(e),n),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(n)}compute(e,t,n,r,s=null){const o=this.get(t),{passEncoderGPU:a}=this.get(e),u=this.get(r).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(s===null&&(s=t.count),s&&typeof s=="object"&&s.isIndirectStorageBufferAttribute){const l=this.get(s).buffer;a.dispatchWorkgroupsIndirect(l,0);return}if(typeof s=="number"){const l=s;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 f=1;f<c.length;f++)d*=c[f];const h=Math.ceil(l/d),p=this.device.limits.maxComputeWorkgroupsPerDimension;s=[h,1,1],h>p&&(s[0]=Math.min(h,p),s[1]=Math.ceil(h/p)),o.dispatchSize=s}s=o.dispatchSize}a.dispatchWorkgroups(s[0],s[1]||1,s[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:n,material:r,context:s,pipeline:o}=e,a=e.getBindings(),u=this.get(s),l=this.get(o),c=l.pipeline;if(l.error===!0)return;const d=e.getIndex(),h=d!==null,p=e.getDrawParameters();if(p===null)return;const f=(m,y)=>{this.pipelineUtils.setPipeline(m,c),y.pipeline=c;const _=y.bindingGroups;for(let A=0,B=a.length;A<B;A++){const S=a[A],v=this.get(S);_[S.index]!==S.id&&(m.setBindGroup(S.index,v.group),_[S.index]=S.id)}if(h===!0&&y.index!==d){const A=this.get(d).buffer,B=d.array instanceof Uint16Array?Xr.Uint16:Xr.Uint32;m.setIndexBuffer(A,B),y.index=d}const T=e.getVertexBuffers();for(let A=0,B=T.length;A<B;A++){const S=T[A];if(y.attributes[A]!==S){const v=this.get(S).buffer;m.setVertexBuffer(A,v),y.attributes[A]=S}}s.stencil===!0&&r.stencilWrite===!0&&u.currentStencilRef!==r.stencilRef&&(m.setStencilReference(r.stencilRef),u.currentStencilRef=r.stencilRef)},g=(m,y)=>{if(f(m,y),n.isBatchedMesh===!0){const _=n._multiDrawStarts,T=n._multiDrawCounts,A=n._multiDrawCount,B=n._multiDrawInstances;B!==null&&Ge("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let S=0;S<A;S++){const v=B?B[S]:1,E=v>1?0:S;h===!0?m.drawIndexed(T[S],v,_[S]/d.array.BYTES_PER_ELEMENT,0,E):m.draw(T[S],v,_[S],E),t.update(n,T[S],v)}}else if(h===!0){const{vertexCount:_,instanceCount:T,firstVertex:A}=p,B=e.getIndirect();if(B!==null){const S=this.get(B).buffer,v=e.getIndirectOffset(),E=Array.isArray(v)?v:[v];for(let D=0;D<E.length;D++)m.drawIndexedIndirect(S,E[D])}else m.drawIndexed(_,T,A,0,0);t.update(n,_,T)}else{const{vertexCount:_,instanceCount:T,firstVertex:A}=p,B=e.getIndirect();if(B!==null){const S=this.get(B).buffer,v=e.getIndirectOffset(),E=Array.isArray(v)?v:[v];for(let D=0;D<E.length;D++)m.drawIndirect(S,E[D])}else m.draw(_,T,A,0);t.update(n,_,T)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const m=this.get(e.camera),y=e.camera.cameras,_=e.getBindingGroup("cameraIndex");if(m.indexesGPU===void 0||m.indexesGPU.length!==y.length){const A=this.get(_),B=[],S=new Uint32Array([0,0,0,0]);for(let v=0,E=y.length;v<E;v++){S[0]=v;const{layoutGPU:D}=A.layout,O=this.bindingUtils.createBindGroupIndex(S,D);B.push(O)}m.indexesGPU=B}const T=this.renderer.getPixelRatio();for(let A=0,B=y.length;A<B;A++){const S=y[A];if(n.layers.test(S.layers)){const v=S.viewport;let E=u.currentPass,D=u.currentSets;if(u.bundleEncoders){const O=u.bundleEncoders[A],Y=u.bundleSets[A];E=O,D=Y}v&&E.setViewport(Math.floor(v.x*T),Math.floor(v.y*T),Math.floor(v.width*T),Math.floor(v.height*T),s.viewportValue.minDepth,s.viewportValue.maxDepth),_&&m.indexesGPU&&(E.setBindGroup(_.index,m.indexesGPU[A]),D.bindingGroups[_.index]=_.id),g(E,D)}}}else if(u.currentPass){if(u.occlusionQuerySet!==void 0){const m=u.lastOcclusionObject;m!==n&&(m!==null&&m.occlusionTest===!0&&(u.currentPass.endOcclusionQuery(),u.occlusionQueryIndex++),n.occlusionTest===!0&&(u.currentPass.beginOcclusionQuery(u.occlusionQueryIndex),u.occlusionQueryObjects[u.occlusionQueryIndex]=n),u.lastOcclusionObject=n)}g(u.currentPass,u.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:r}=e,s=this.utils,o=s.getSampleCountRenderContext(e.context),a=s.getCurrentColorSpace(e.context),u=s.getCurrentColorFormat(e.context),l=s.getCurrentDepthStencilFormat(e.context),c=s.getPrimitiveTopology(n,r);let d=!1;return(t.material!==r||t.materialVersion!==r.version||t.transparent!==r.transparent||t.blending!==r.blending||t.premultipliedAlpha!==r.premultipliedAlpha||t.blendSrc!==r.blendSrc||t.blendDst!==r.blendDst||t.blendEquation!==r.blendEquation||t.blendSrcAlpha!==r.blendSrcAlpha||t.blendDstAlpha!==r.blendDstAlpha||t.blendEquationAlpha!==r.blendEquationAlpha||t.colorWrite!==r.colorWrite||t.depthWrite!==r.depthWrite||t.depthTest!==r.depthTest||t.depthFunc!==r.depthFunc||t.stencilWrite!==r.stencilWrite||t.stencilFunc!==r.stencilFunc||t.stencilFail!==r.stencilFail||t.stencilZFail!==r.stencilZFail||t.stencilZPass!==r.stencilZPass||t.stencilFuncMask!==r.stencilFuncMask||t.stencilWriteMask!==r.stencilWriteMask||t.side!==r.side||t.alphaToCoverage!==r.alphaToCoverage||t.sampleCount!==o||t.colorSpace!==a||t.colorFormat!==u||t.depthStencilFormat!==l||t.primitiveTopology!==c||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=r,t.materialVersion=r.version,t.transparent=r.transparent,t.blending=r.blending,t.premultipliedAlpha=r.premultipliedAlpha,t.blendSrc=r.blendSrc,t.blendDst=r.blendDst,t.blendEquation=r.blendEquation,t.blendSrcAlpha=r.blendSrcAlpha,t.blendDstAlpha=r.blendDstAlpha,t.blendEquationAlpha=r.blendEquationAlpha,t.colorWrite=r.colorWrite,t.depthWrite=r.depthWrite,t.depthTest=r.depthTest,t.depthFunc=r.depthFunc,t.stencilWrite=r.stencilWrite,t.stencilFunc=r.stencilFunc,t.stencilFail=r.stencilFail,t.stencilZFail=r.stencilZFail,t.stencilZPass=r.stencilZPass,t.stencilFuncMask=r.stencilFuncMask,t.stencilWriteMask=r.stencilWriteMask,t.side=r.side,t.alphaToCoverage=r.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,r=this.utils,s=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,r.getSampleCountRenderContext(s),r.getCurrentColorSpace(s),r.getCurrentColorFormat(s),r.getCurrentDepthStencilFormat(s),r.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,r,s,o){return this.textureUtils.copyTextureToBuffer(e,t,n,r,s,o)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new hA(this.device,e,2048));const r=this.timestampQueryPool[e],s=r.allocateQueriesForContext(t);n.timestampWrites={querySet:r.querySet,beginningOfPassWriteIndex:s,endOfPassWriteIndex:s+1}}createNodeBuilder(e,t){return new sA(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),s=n.currentPass.finish();this.get(t).bundleGPU=s,n.currentSets=n._currentSets,n.currentPass=n._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}updateBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}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())}getMaxAnisotropy(){return 16}hasFeature(e){return rh[e]!==void 0&&(e=rh[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,r=null,s=0,o=0){let a=0,u=0,l=0,c=0,d=0,h=0,p=e.image.width,f=e.image.height,g=1;n!==null&&(n.isBox3===!0?(c=n.min.x,d=n.min.y,h=n.min.z,p=n.max.x-n.min.x,f=n.max.y-n.min.y,g=n.max.z-n.min.z):(c=n.min.x,d=n.min.y,p=n.max.x-n.min.x,f=n.max.y-n.min.y,g=1)),r!==null&&(a=r.x,u=r.y,l=r.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:s,origin:{x:c,y:d,z:h}},{texture:_,mipLevel:o,origin:{x:a,y:u,z:l}},[p,f,g]),this.device.queue.submit([m.finish()]),o===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const r=this.get(t);let s=null;t.renderTarget?e.isDepthTexture?s=this.get(t.depthTexture).texture:s=this.get(t.textures[0]).texture:e.isDepthTexture?s=this.textureUtils.getDepthBuffer(t.depth,t.stencil):s=this.context.getCurrentTexture();const o=this.get(e).texture;if(s.format!==o.format){G("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",s.format,o.format);return}let a;if(r.currentPass?(r.currentPass.end(),a=r.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:s,origin:[n.x,n.y,0]},{texture:o},[n.z,n.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),r.currentPass){const{descriptor:u}=r;for(let l=0;l<u.colorAttachments.length;l++)u.colorAttachments[l].loadOp=xe.Load;t.depth&&(u.depthStencilAttachment.depthLoadOp=xe.Load),t.stencil&&(u.depthStencilAttachment.stencilLoadOp=xe.Load),r.currentPass=a.beginRenderPass(u),r.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([a.finish()])}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 pA extends el{constructor(e,t,n,r,s,o){super(e,t,n,r,s,o),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class gA extends el{constructor(e,t,n,r,s,o){super(e,t,n,r,s,o),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class mA extends Sg{constructor(){super(),this.addMaterial(x0,"MeshPhongMaterial"),this.addMaterial(sg,"MeshStandardMaterial"),this.addMaterial(bS,"MeshPhysicalMaterial"),this.addMaterial(vS,"MeshToonMaterial"),this.addMaterial(f0,"MeshBasicMaterial"),this.addMaterial(b0,"MeshLambertMaterial"),this.addMaterial(u0,"MeshNormalMaterial"),this.addMaterial(RS,"MeshMatcapMaterial"),this.addMaterial(s0,"LineBasicMaterial"),this.addMaterial(o0,"LineDashedMaterial"),this.addMaterial(MS,"PointsMaterial"),this.addMaterial(og,"SpriteMaterial"),this.addMaterial(FS,"ShadowMaterial"),this.addLight(mR,Jg),this.addLight(jR,Sh),this.addLight(qR,em),this.addLight($l,el),this.addLight(YR,Nh),this.addLight(QR,tm),this.addLight(ZR,nm),this.addLight(HR,pA),this.addLight(KR,gA),this.addToneMapping(_N,rm),this.addToneMapping(xN,sm),this.addToneMapping(TN,im),this.addToneMapping(SN,om),this.addToneMapping(AN,am),this.addToneMapping(EN,um)}}class yA extends bw{constructor(e={}){let t;e.forceWebGL?t=Qd:(t=fA,e.getFallback=()=>(z("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Qd(e)));const n=new t(e);super(n,e),this.library=new mA,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const $a={type:"change"},Wl={type:"start"},jl={type:"end"},uh=1e-6,Te={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4},Fi=new ce,Rn=new ce,bA=new I,Li=new I,za=new I,Er=new kr,lh=new I,Ui=new I,Wa=new I,Oi=new I;class _A extends To{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:Ze.ROTATE,MIDDLE:Ze.DOLLY,RIGHT:Ze.PAN},this.target=new I,this.state=Te.NONE,this.keyState=Te.NONE,this._lastPosition=new I,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new I,this._movePrev=new ce,this._moveCurr=new ce,this._lastAxis=new I,this._zoomStart=new ce,this._zoomEnd=new ce,this._panStart=new ce,this._panEnd=new ce,this._pointers=[],this._pointerPositions={},this._onPointerMove=TA.bind(this),this._onPointerDown=xA.bind(this),this._onPointerUp=vA.bind(this),this._onPointerCancel=SA.bind(this),this._onContextMenu=MA.bind(this),this._onMouseWheel=CA.bind(this),this._onKeyDown=RA.bind(this),this._onKeyUp=NA.bind(this),this._onTouchStart=PA.bind(this),this._onTouchMove=BA.bind(this),this._onTouchEnd=DA.bind(this),this._onMouseDown=wA.bind(this),this._onMouseMove=AA.bind(this),this._onMouseUp=EA.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="auto"}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)>uh&&(this.dispatchEvent($a),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>uh||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent($a),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=Te.NONE,this.keyState=Te.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($a),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(Rn.copy(this._panEnd).sub(this._panStart),Rn.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;Rn.x*=e,Rn.y*=t}Rn.multiplyScalar(this._eye.length()*this.panSpeed),Li.copy(this._eye).cross(this.object.up).setLength(Rn.x),Li.add(bA.copy(this.object.up).setLength(Rn.y)),this.object.position.add(Li),this.target.add(Li),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(Rn.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){Oi.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=Oi.length();e?(this._eye.copy(this.object.position).sub(this.target),lh.copy(this._eye).normalize(),Ui.copy(this.object.up).normalize(),Wa.crossVectors(Ui,lh).normalize(),Ui.setLength(this._moveCurr.y-this._movePrev.y),Wa.setLength(this._moveCurr.x-this._movePrev.x),Oi.copy(Ui.add(Wa)),za.crossVectors(Oi,this._eye).normalize(),e*=this.rotateSpeed,Er.setFromAxisAngle(za,e),this._eye.applyQuaternion(Er),this.object.up.applyQuaternion(Er),this._lastAxis.copy(za),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),Er.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(Er),this.object.up.applyQuaternion(Er)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===Te.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=ao.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=ao.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 Fi.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),Fi}_getMouseOnCircle(e,t){return Fi.set((e-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-t))/this.screen.width),Fi}_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 xA(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 TA(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function vA(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 SA(i){this._removePointer(i)}function NA(){this.enabled!==!1&&(this.keyState=Te.NONE,window.addEventListener("keydown",this._onKeyDown))}function RA(i){this.enabled!==!1&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===Te.NONE&&(i.code===this.keys[Te.ROTATE]&&!this.noRotate?this.keyState=Te.ROTATE:i.code===this.keys[Te.ZOOM]&&!this.noZoom?this.keyState=Te.ZOOM:i.code===this.keys[Te.PAN]&&!this.noPan&&(this.keyState=Te.PAN)))}function wA(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 Ze.DOLLY:this.state=Te.ZOOM;break;case Ze.ROTATE:this.state=Te.ROTATE;break;case Ze.PAN:this.state=Te.PAN;break;default:this.state=Te.NONE}const t=this.keyState!==Te.NONE?this.keyState:this.state;t===Te.ROTATE&&!this.noRotate?(this._moveCurr.copy(this._getMouseOnCircle(i.pageX,i.pageY)),this._movePrev.copy(this._moveCurr)):t===Te.ZOOM&&!this.noZoom?(this._zoomStart.copy(this._getMouseOnScreen(i.pageX,i.pageY)),this._zoomEnd.copy(this._zoomStart)):t===Te.PAN&&!this.noPan&&(this._panStart.copy(this._getMouseOnScreen(i.pageX,i.pageY)),this._panEnd.copy(this._panStart)),this.dispatchEvent(Wl)}function AA(i){const e=this.keyState!==Te.NONE?this.keyState:this.state;e===Te.ROTATE&&!this.noRotate?(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(i.pageX,i.pageY))):e===Te.ZOOM&&!this.noZoom?this._zoomEnd.copy(this._getMouseOnScreen(i.pageX,i.pageY)):e===Te.PAN&&!this.noPan&&this._panEnd.copy(this._getMouseOnScreen(i.pageX,i.pageY))}function EA(){this.state=Te.NONE,this.dispatchEvent(jl)}function CA(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(Wl),this.dispatchEvent(jl)}}function MA(i){this.enabled!==!1&&i.preventDefault()}function PA(i){switch(this._trackPointer(i),this._pointers.length){case 1:this.state=Te.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this.state=Te.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,r=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,r)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(Wl)}function BA(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 r=(i.pageX+e.x)/2,s=(i.pageY+e.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,s));break}}function DA(i){switch(this._pointers.length){case 0:this.state=Te.NONE;break;case 1:this.state=Te.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(i.pageX,i.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=Te.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(jl)}const ch={type:"change"},ql={type:"start"},Lg={type:"end"},Ii=new by,dh=new vo,FA=Math.cos(70*ao.DEG2RAD),Xe=new I,ot=2*Math.PI,Ae={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ja=1e-6;class LA extends To{constructor(e,t=null){super(e,t),this.state=Ae.NONE,this.target=new I,this.cursor=new I,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:Ze.ROTATE,MIDDLE:Ze.DOLLY,RIGHT:Ze.PAN},this.touches={ONE:dn.ROTATE,TWO:dn.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new I,this._lastQuaternion=new kr,this._lastTargetPosition=new I,this._quat=new kr().setFromUnitVectors(e.up,new I(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Jl,this._sphericalDelta=new Jl,this._scale=1,this._panOffset=new I,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 I,this._mouse=new ce,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=OA.bind(this),this._onPointerDown=UA.bind(this),this._onPointerUp=IA.bind(this),this._onContextMenu=jA.bind(this),this._onMouseWheel=VA.bind(this),this._onKeyDown=$A.bind(this),this._onTouchStart=zA.bind(this),this._onTouchMove=WA.bind(this),this._onMouseDown=kA.bind(this),this._onMouseMove=GA.bind(this),this._interceptControlDown=qA.bind(this),this._interceptControlUp=HA.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}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="auto"}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(ch),this.update(),this.state=Ae.NONE}update(e=null){const t=this.object.position;Xe.copy(t).sub(this.target),Xe.applyQuaternion(this._quat),this._spherical.setFromVector3(Xe),this.autoRotate&&this.state===Ae.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,r=this.maxAzimuthAngle;isFinite(n)&&isFinite(r)&&(n<-Math.PI?n+=ot:n>Math.PI&&(n-=ot),r<-Math.PI?r+=ot:r>Math.PI&&(r-=ot),n<=r?this._spherical.theta=Math.max(n,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+r)/2?Math.max(n,this._spherical.theta):Math.min(r,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 s=!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),s=o!=this._spherical.radius}if(Xe.setFromSpherical(this._spherical),Xe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Xe),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=Xe.length();o=this._clampDistance(a*this._scale);const u=a-o;this.object.position.addScaledVector(this._dollyDirection,u),this.object.updateMatrixWorld(),s=!!u}else if(this.object.isOrthographicCamera){const a=new I(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(),s=u!==this.object.zoom;const l=new I(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),o=Xe.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):(Ii.origin.copy(this.object.position),Ii.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Ii.direction))<FA?this.object.lookAt(this.target):(dh.setFromNormalAndCoplanarPoint(this.object.up,this.target),Ii.intersectPlane(dh,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(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>ja||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ja||this._lastTargetPosition.distanceToSquared(this.target)>ja?(this.dispatchEvent(ch),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?ot/60*this.autoRotateSpeed*e:ot/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){Xe.setFromMatrixColumn(t,0),Xe.multiplyScalar(-e),this._panOffset.add(Xe)}_panUp(e,t){this.screenSpacePanning===!0?Xe.setFromMatrixColumn(t,1):(Xe.setFromMatrixColumn(t,0),Xe.crossVectors(this.object.up,Xe)),Xe.multiplyScalar(e),this._panOffset.add(Xe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;Xe.copy(r).sub(this.target);let s=Xe.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/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(),r=e-n.left,s=t-n.top,o=n.width,a=n.height;this._mouse.x=r/o*2-1,this._mouse.y=-(s/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(ot*this._rotateDelta.x/t.clientHeight),this._rotateUp(ot*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(ot*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(-ot*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(ot*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(-ot*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),r=.5*(e.pageY+t.y);this._rotateStart.set(n,r)}}_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),r=.5*(e.pageY+t.y);this._panStart.set(n,r)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(n*n+r*r);this._dollyStart.set(0,s)}_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),r=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(r,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(ot*this._rotateDelta.x/t.clientHeight),this._rotateUp(ot*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),r=.5*(e.pageY+t.y);this._panEnd.set(n,r)}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,r=e.pageY-t.y,s=Math.sqrt(n*n+r*r);this._dollyEnd.set(0,s),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 UA(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)))}function OA(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function IA(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(Lg),this.state=Ae.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function kA(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 Ze.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Ae.DOLLY;break;case Ze.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ae.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ae.ROTATE}break;case Ze.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ae.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ae.PAN}break;default:this.state=Ae.NONE}this.state!==Ae.NONE&&this.dispatchEvent(ql)}function GA(i){switch(this.state){case Ae.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Ae.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Ae.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function VA(i){this.enabled===!1||this.enableZoom===!1||this.state!==Ae.NONE||(i.preventDefault(),this.dispatchEvent(ql),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Lg))}function $A(i){this.enabled!==!1&&this._handleKeyDown(i)}function zA(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case dn.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Ae.TOUCH_ROTATE;break;case dn.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Ae.TOUCH_PAN;break;default:this.state=Ae.NONE}break;case 2:switch(this.touches.TWO){case dn.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Ae.TOUCH_DOLLY_PAN;break;case dn.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Ae.TOUCH_DOLLY_ROTATE;break;default:this.state=Ae.NONE}break;default:this.state=Ae.NONE}this.state!==Ae.NONE&&this.dispatchEvent(ql)}function WA(i){switch(this._trackPointer(i),this.state){case Ae.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Ae.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Ae.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Ae.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Ae.NONE}}function jA(i){this.enabled!==!1&&i.preventDefault()}function qA(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function HA(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const XA={type:"change"},hh=1e-6,fh=new kr;class KA extends To{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 I(0,0,0),this._rotationVector=new I(0,0,0),this._lastQuaternion=new kr,this._lastPosition=new I,this._status=0,this._onKeyDown=YA.bind(this),this._onKeyUp=QA.bind(this),this._onPointerMove=JA.bind(this),this._onPointerDown=ZA.bind(this),this._onPointerUp=eE.bind(this),this._onPointerCancel=tE.bind(this),this._onContextMenu=nE.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)}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)}dispose(){this.disconnect()}update(e){if(this.enabled===!1)return;const t=this.object,n=e*this.movementSpeed,r=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),fh.set(this._rotationVector.x*r,this._rotationVector.y*r,this._rotationVector.z*r,1).normalize(),t.quaternion.multiply(fh),(this._lastPosition.distanceToSquared(t.position)>hh||8*(1-this._lastQuaternion.dot(t.quaternion))>hh)&&(this.dispatchEvent(XA),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 YA(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 QA(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 ZA(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 JA(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 eE(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 tE(){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 nE(i){this.enabled!==!1&&i.preventDefault()}const rE={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
898
+
899
+ varying vec2 vUv;
900
+
901
+ void main() {
902
+
903
+ vUv = uv;
904
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
905
+
906
+ }`,fragmentShader:`
907
+
908
+ uniform float opacity;
909
+
910
+ uniform sampler2D tDiffuse;
911
+
912
+ varying vec2 vUv;
913
+
914
+ void main() {
915
+
916
+ vec4 texel = texture2D( tDiffuse, vUv );
917
+ gl_FragColor = opacity * texel;
918
+
919
+
920
+ }`};class Vo{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 sE=new nl(-1,1,1,-1,0,1);class iE extends Zs{constructor(){super(),this.setAttribute("position",new oo([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new oo([0,2,0,0,2,0],2))}}const oE=new iE;class aE{constructor(e){this._mesh=new Ut(oE,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,sE)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class uE extends Vo{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof ec?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=_y.clone(e.uniforms),this.material=new ec({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 aE(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 Vo{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const r=e.getContext(),s=e.state;s.buffers.color.setMask(!1),s.buffers.depth.setMask(!1),s.buffers.color.setLocked(!0),s.buffers.depth.setLocked(!0);let o,a;this.inverse?(o=0,a=1):(o=1,a=0),s.buffers.stencil.setTest(!0),s.buffers.stencil.setOp(r.REPLACE,r.REPLACE,r.REPLACE),s.buffers.stencil.setFunc(r.ALWAYS,o,4294967295),s.buffers.stencil.setClear(a),s.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),s.buffers.color.setLocked(!1),s.buffers.depth.setLocked(!1),s.buffers.color.setMask(!0),s.buffers.depth.setMask(!0),s.buffers.stencil.setLocked(!1),s.buffers.stencil.setFunc(r.EQUAL,1,4294967295),s.buffers.stencil.setOp(r.KEEP,r.KEEP,r.KEEP),s.buffers.stencil.setLocked(!0)}}class lE extends Vo{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class cE{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 xy(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 uE(rE),this.copyPass.material.blending=$r,this.clock=new lf}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){e===void 0&&(e=this.clock.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let r=0,s=this.passes.length;r<s;r++){const o=this.passes[r];if(o.enabled!==!1){if(o.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(r),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 lE&&(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,r=this._height*this._pixelRatio;this.renderTarget1.setSize(n,r),this.renderTarget2.setSize(n,r);for(let s=0;s<this.passes.length;s++)this.passes[s].setSize(n,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class dE extends Vo{constructor(e,t,n=null,r=null,s=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=r,this.clearAlpha=s,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new Ct}render(e,t,n){const r=e.autoClear;e.autoClear=!1;let s,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&&(s=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(s),this.overrideMaterial!==null&&(this.scene.overrideMaterial=o),e.autoClear=r}}function Hu(i){return Hu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Hu(i)}function hE(i){try{return Function.toString.call(i).indexOf("[native code]")!==-1}catch{return typeof i=="function"}}function Ug(){try{var i=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Ug=function(){return!!i})()}function fE(i,e,t){if(Ug())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var r=new(i.bind.apply(i,n));return t&&Hs(r,t.prototype),r}function Xu(i){var e=typeof Map=="function"?new Map:void 0;return Xu=function(n){if(n===null||!hE(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,r)}function r(){return fE(n,arguments,Hu(this).constructor)}return r.prototype=Object.create(n.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),Hs(r,n)},Xu(i)}var Yt=(function(i){Ly(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,Uy(n)}return e})(Xu(Error));function qa(i){return Math.round(i*255)}function pE(i,e,t){return qa(i)+","+qa(e)+","+qa(t)}function xo(i,e,t,n){if(n===void 0&&(n=pE),e===0)return n(t,t,t);var r=(i%360+360)%360/60,s=(1-Math.abs(2*t-1))*e,o=s*(1-Math.abs(r%2-1)),a=0,u=0,l=0;r>=0&&r<1?(a=s,u=o):r>=1&&r<2?(a=o,u=s):r>=2&&r<3?(u=s,l=o):r>=3&&r<4?(u=o,l=s):r>=4&&r<5?(a=o,l=s):r>=5&&r<6&&(a=s,l=o);var c=t-s/2,d=a+c,h=u+c,p=l+c;return n(d,h,p)}var gh={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 gE(i){if(typeof i!="string")return i;var e=i.toLowerCase();return gh[e]?"#"+gh[e]:i}var mE=/^#[a-fA-F0-9]{6}$/,yE=/^#[a-fA-F0-9]{8}$/,bE=/^#[a-fA-F0-9]{3}$/,_E=/^#[a-fA-F0-9]{4}$/,Ha=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,xE=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,TE=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,vE=/^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 Kr(i){if(typeof i!="string")throw new Yt(3);var e=gE(i);if(e.match(mE))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(yE)){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(bE))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(_E)){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 r=Ha.exec(e);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=xE.exec(e.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var o=TE.exec(e);if(o){var a=parseInt(""+o[1],10),u=parseInt(""+o[2],10)/100,l=parseInt(""+o[3],10)/100,c="rgb("+xo(a,u,l)+")",d=Ha.exec(c);if(!d)throw new Yt(4,e,c);return{red:parseInt(""+d[1],10),green:parseInt(""+d[2],10),blue:parseInt(""+d[3],10)}}var h=vE.exec(e.substring(0,50));if(h){var p=parseInt(""+h[1],10),f=parseInt(""+h[2],10)/100,g=parseInt(""+h[3],10)/100,m="rgb("+xo(p,f,g)+")",y=Ha.exec(m);if(!y)throw new Yt(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 Yt(5)}function SE(i){var e=i.red/255,t=i.green/255,n=i.blue/255,r=Math.max(e,t,n),s=Math.min(e,t,n),o=(r+s)/2;if(r===s)return i.alpha!==void 0?{hue:0,saturation:0,lightness:o,alpha:i.alpha}:{hue:0,saturation:0,lightness:o};var a,u=r-s,l=o>.5?u/(2-r-s):u/(r+s);switch(r){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 Vn(i){return SE(Kr(i))}var NE=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},Ku=NE;function Kn(i){var e=i.toString(16);return e.length===1?"0"+e:e}function Xa(i){return Kn(Math.round(i*255))}function RE(i,e,t){return Ku("#"+Xa(i)+Xa(e)+Xa(t))}function Og(i,e,t){return xo(i,e,t,RE)}function wE(i,e,t){if(typeof i=="object"&&e===void 0&&t===void 0)return Og(i.hue,i.saturation,i.lightness);throw new Yt(1)}function AE(i,e,t,n){if(typeof i=="object"&&e===void 0&&t===void 0&&n===void 0)return i.alpha>=1?Og(i.hue,i.saturation,i.lightness):"rgba("+xo(i.hue,i.saturation,i.lightness)+","+i.alpha+")";throw new Yt(2)}function Ig(i,e,t){if(typeof i=="number"&&typeof e=="number"&&typeof t=="number")return Ku("#"+Kn(i)+Kn(e)+Kn(t));if(typeof i=="object"&&e===void 0&&t===void 0)return Ku("#"+Kn(i.red)+Kn(i.green)+Kn(i.blue));throw new Yt(6)}function $o(i,e,t,n){if(typeof i=="object"&&e===void 0&&t===void 0&&n===void 0)return i.alpha>=1?Ig(i.red,i.green,i.blue):"rgba("+i.red+","+i.green+","+i.blue+","+i.alpha+")";throw new Yt(7)}var EE=function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||typeof e.alpha>"u")},CE=function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"},ME=function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||typeof e.alpha>"u")},PE=function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"};function $n(i){if(typeof i!="object")throw new Yt(8);if(CE(i))return $o(i);if(EE(i))return Ig(i);if(PE(i))return AE(i);if(ME(i))return wE(i);throw new Yt(8)}function kg(i,e,t){return function(){var r=t.concat(Array.prototype.slice.call(arguments));return r.length>=e?i.apply(this,r):kg(i,e,r)}}function _t(i){return kg(i,i.length,[])}function BE(i,e){if(e==="transparent")return e;var t=Vn(e);return $n(ft({},t,{hue:t.hue+parseFloat(i)}))}_t(BE);function is(i,e,t){return Math.max(i,Math.min(e,t))}function DE(i,e){if(e==="transparent")return e;var t=Vn(e);return $n(ft({},t,{lightness:is(0,1,t.lightness-parseFloat(i))}))}_t(DE);function FE(i,e){if(e==="transparent")return e;var t=Vn(e);return $n(ft({},t,{saturation:is(0,1,t.saturation-parseFloat(i))}))}_t(FE);function LE(i,e){if(e==="transparent")return e;var t=Vn(e);return $n(ft({},t,{lightness:is(0,1,t.lightness+parseFloat(i))}))}_t(LE);function UE(i,e,t){if(e==="transparent")return t;if(t==="transparent")return e;if(i===0)return t;var n=Kr(e),r=ft({},n,{alpha:typeof n.alpha=="number"?n.alpha:1}),s=Kr(t),o=ft({},s,{alpha:typeof s.alpha=="number"?s.alpha:1}),a=r.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,p={red:Math.floor(r.red*d+o.red*h),green:Math.floor(r.green*d+o.green*h),blue:Math.floor(r.blue*d+o.blue*h),alpha:r.alpha*parseFloat(i)+o.alpha*(1-parseFloat(i))};return $o(p)}var OE=_t(UE),Gg=OE;function IE(i,e){if(e==="transparent")return e;var t=Kr(e),n=typeof t.alpha=="number"?t.alpha:1,r=ft({},t,{alpha:is(0,1,(n*100+parseFloat(i)*100)/100)});return $o(r)}var kE=_t(IE),GE=kE;function VE(i,e){if(e==="transparent")return e;var t=Vn(e);return $n(ft({},t,{saturation:is(0,1,t.saturation+parseFloat(i))}))}_t(VE);function $E(i,e){return e==="transparent"?e:$n(ft({},Vn(e),{hue:parseFloat(i)}))}_t($E);function zE(i,e){return e==="transparent"?e:$n(ft({},Vn(e),{lightness:parseFloat(i)}))}_t(zE);function WE(i,e){return e==="transparent"?e:$n(ft({},Vn(e),{saturation:parseFloat(i)}))}_t(WE);function jE(i,e){return e==="transparent"?e:Gg(parseFloat(i),"rgb(0, 0, 0)",e)}_t(jE);function qE(i,e){return e==="transparent"?e:Gg(parseFloat(i),"rgb(255, 255, 255)",e)}_t(qE);function HE(i,e){if(e==="transparent")return e;var t=Kr(e),n=typeof t.alpha=="number"?t.alpha:1,r=ft({},t,{alpha:is(0,1,+(n*100-parseFloat(i)*100).toFixed(2)/100)});return $o(r)}_t(HE);function XE(i,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=i:r.appendChild(document.createTextNode(i))}}var KE=`.scene-nav-info {
921
+ position: absolute;
922
+ bottom: 5px;
923
+ width: 100%;
924
+ text-align: center;
925
+ color: slategrey;
926
+ opacity: 0.7;
927
+ font-size: 10px;
928
+ font-family: sans-serif;
929
+ pointer-events: none;
930
+ user-select: none;
931
+ }
932
+
933
+ .scene-container canvas:focus {
934
+ outline: none;
935
+ }`;XE(KE);function Yu(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 YE(i){if(Array.isArray(i))return i}function QE(i){if(Array.isArray(i))return Yu(i)}function ZE(i,e,t){return(e=iC(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function JE(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function eC(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,r,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(i)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,r=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw r}}return a}}function tC(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
936
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function nC(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
937
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rC(i,e){return YE(i)||eC(i,e)||Vg(i,e)||tC()}function Hn(i){return QE(i)||JE(i)||Vg(i)||nC()}function sC(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 iC(i){var e=sC(i,"string");return typeof e=="symbol"?e:e+""}function Vg(i,e){if(i){if(typeof i=="string")return Yu(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)?Yu(i,e):void 0}}var Fe=window.THREE?window.THREE:{WebGLRenderer:vy,Scene:So,PerspectiveCamera:Ws,Raycaster:yh,SRGBColorSpace:Ju,TextureLoader:Ty,Vector2:ce,Vector3:I,Box3:Th,Color:Ct,Mesh:Ut,SphereGeometry:Zu,MeshBasicMaterial:An,BackSide:ht,Clock:lf},$g=fl({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.clock.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 r=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&r.sort(function(o,a){return e.hoverOrderComparator(o.object,a.object)});var s=r.find(function(o){return e.hoverFilter(o.object)})||null;n=s?s.object:null,e.intersection=s||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,r=t.y;return{x:n,y:r}},cameraPosition:function(e,t,n,r){var s=e.camera;if(t&&e.initialised){var o=t,a=n||{x:0,y:0,z:0};if(!r)c(o),d(a);else{var u=Object.assign({},s.position),l=h();e.tweenGroup.add(new tc(u).to(o,r).easing(nc.Quadratic.Out).onUpdate(c).start()),e.tweenGroup.add(new tc(l).to(a,r/3).easing(nc.Quadratic.Out).onUpdate(d).start())}return this}return Object.assign({},s.position,{lookAt:h()});function c(p){var f=p.x,g=p.y,m=p.z;f!==void 0&&(s.position.x=f),g!==void 0&&(s.position.y=g),m!==void 0&&(s.position.z=m)}function d(p){var f=new Fe.Vector3(p.x,p.y,p.z);e.controls.enabled&&e.controls.target?e.controls.target=f:s.lookAt(f)}function h(){return Object.assign(new Fe.Vector3(0,0,-1e3).applyQuaternion(s.quaternion).add(s.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,r=arguments.length,s=new Array(r>3?r-3:0),o=3;o<r;o++)s[o-3]=arguments[o];return this.fitToBbox(this.getBbox.apply(this,s),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:10,s=e.camera;if(t){var o=new Fe.Vector3(0,0,0),a=Math.max.apply(Math,Hn(Object.entries(t).map(function(p){var f=rC(p,2),g=f[0],m=f[1];return Math.max.apply(Math,Hn(m.map(function(y){return Math.abs(o[g]-y)})))})))*2,u=(1-r*2/e.height)*s.fov,l=a/Math.atan(u*Math.PI/180),c=l/s.aspect,d=Math.max(l,c);if(d>0){var h=o.clone().sub(s.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 Fe.Box3(new Fe.Vector3(0,0,0),new Fe.Vector3(0,0,0)),r=e.objects.filter(t);return r.length?(r.forEach(function(s){return n.expandByObject(s)}),Object.assign.apply(Object,Hn(["x","y","z"].map(function(s){return ZE({},s,[n.min[s],n.max[s]])})))):null},getScreenCoords:function(e,t,n,r){var s=new Fe.Vector3(t,n,r);return s.project(this.camera()),{x:(s.x+1)*e.width/2,y:-(s.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,s=new Fe.Vector2(t/e.width*2-1,-(n/e.height)*2+1),o=new Fe.Raycaster;return o.setFromCamera(s,e.camera),Object.assign({},o.ray.at(r,new Fe.Vector3))},intersectingObjects:function(e,t,n){var r=new Fe.Vector2(t/e.width*2-1,-(n/e.height)*2+1),s=new Fe.Raycaster;return s.params.Line.threshold=e.lineHoverPrecision,s.params.Points.threshold=e.pointsHoverPrecision,s.setFromCamera(r,e.camera),s.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}},stateInit:function(){return{scene:new Fe.Scene,camera:new Fe.PerspectiveCamera,clock:new Fe.Clock,tweenGroup:new Py,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.controlType,s=r===void 0?"trackball":r,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,p=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"}[s]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new My(t.container),t.pointerPos=new Fe.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(f){return t.container.addEventListener(f,function(g){if(f==="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(),A=window.pageXOffset||document.documentElement.scrollLeft,B=window.pageYOffset||document.documentElement.scrollTop;return{top:T.top+B,left:T.left+A}}},{passive:!0})}),t.container.addEventListener("pointerup",function(f){t.isPointerPressed&&(t.isPointerPressed=!1,!(t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag))&&requestAnimationFrame(function(){f.button===0&&t.onClick(t.hoverObj||null,f,t.intersection),f.button===2&&t.onRightClick&&t.onRightClick(t.hoverObj||null,f,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(f){t.onRightClick&&f.preventDefault()}),t.renderer=new(a?yA:Fe.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(f){f.domElement.style.position="absolute",f.domElement.style.top="0px",f.domElement.style.pointerEvents="none",t.container.appendChild(f.domElement)}),t.postProcessingComposer=new cE(t.renderer),t.postProcessingComposer.addPass(new dE(t.scene,t.camera)),t.controls=new{trackball:_A,orbit:LA,fly:KA}[s](t.camera,t.renderer.domElement),s==="fly"&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),(s==="trackball"||s==="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(Hn(t.extraRenderers)).forEach(function(f){return f.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 Fe.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!p,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,r=e.width,s=e.height;e.container.style.width="".concat(r,"px"),e.container.style.height="".concat(s,"px"),[e.renderer,e.postProcessingComposer].concat(Hn(e.extraRenderers)).forEach(function(p){return p.setSize(r,s)}),e.camera.aspect=r/s;var o=e.viewOffset.slice(0,2);o.some(function(p){return p})&&(n=e.camera).setViewOffset.apply(n,[r,s].concat(Hn(o),[r,s])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,u=e.width,l=e.height,c=e.viewOffset.slice(0,2);c.some(function(p){return p})?(a=e.camera).setViewOffset.apply(a,[u,l].concat(Hn(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 Fe.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var d=Kr(e.backgroundColor).alpha;d===void 0&&(d=1),e.renderer.setClearColor(new Fe.Color(GE(1,e.backgroundColor)),d)}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?new Fe.TextureLoader().load(e.backgroundImageUrl,function(p){p.colorSpace=Fe.SRGBColorSpace,e.skysphere.material=new Fe.MeshBasicMaterial({map:p,side:Fe.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(p){return e.scene.remove(p)}),e.lights.forEach(function(p){return e.scene.add(p)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(p){return e.scene.remove(p)}),e.objects.forEach(function(p){return e.scene.add(p)}));function h(){e.loadComplete=e.scene.visible=!0}}});function oC(i,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=i:r.appendChild(document.createTextNode(i))}}var aC=`.graph-info-msg {
938
+ top: 50%;
939
+ width: 100%;
940
+ text-align: center;
941
+ color: lavender;
942
+ opacity: 0.7;
943
+ font-size: 22px;
944
+ position: absolute;
945
+ font-family: Sans-serif;
946
+ }
947
+
948
+ .scene-container .clickable {
949
+ cursor: pointer;
950
+ }
951
+
952
+ .scene-container .grabbable {
953
+ cursor: move;
954
+ cursor: grab;
955
+ cursor: -moz-grab;
956
+ cursor: -webkit-grab;
957
+ }
958
+
959
+ .scene-container .grabbable:active {
960
+ cursor: grabbing;
961
+ cursor: -moz-grabbing;
962
+ cursor: -webkit-grabbing;
963
+ }`;oC(aC);function Qu(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 uC(i){if(Array.isArray(i))return Qu(i)}function ii(i,e,t){return(e=hC(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function lC(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function cC(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
964
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function mh(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).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?mh(Object(t),!0).forEach(function(n){ii(i,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):mh(Object(t)).forEach(function(n){Object.defineProperty(i,n,Object.getOwnPropertyDescriptor(t,n))})}return i}function zo(i){return uC(i)||lC(i)||fC(i)||cC()}function dC(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 hC(i){var e=dC(i,"string");return typeof e=="symbol"?e:e+""}function fC(i,e){if(i){if(typeof i=="string")return Qu(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)?Qu(i,e):void 0}}function zg(i,e){var t=new e;return t._destructor&&t._destructor(),{linkProp:function(r){return{default:t[r](),onChange:function(o,a){a[i][r](o)},triggerUpdate:!1}},linkMethod:function(r){return function(s){for(var o=s[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[r].apply(o,u);return c===o?this:c}}}}var Ka=window.THREE?window.THREE:{AmbientLight:Nh,DirectionalLight:Sh,REVISION:No},pC=170,Wg=zg("forceGraph",Mf),gC=Object.assign.apply(Object,zo(["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 ii({},i,Wg.linkProp(i))}))),mC=Object.assign.apply(Object,zo(["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(function(i){return ii({},i,Wg.linkMethod(i))}))),Zi=zg("renderObjs",$g),yC=Object.assign.apply(Object,zo(["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(function(i){return ii({},i,Zi.linkProp(i))}))),bC=Object.assign.apply(Object,zo(["lights","cameraPosition","postProcessingComposer"].map(function(i){return ii({},i,Zi.linkMethod(i))})).concat([{graph2ScreenCoords:Zi.linkMethod("getScreenCoords"),screen2GraphCoords:Zi.linkMethod("getSceneCoords")}])),NC=fl({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}},gC),yC),methods:ki(ki({zoomToFit:function(e,t,n){for(var r,s=arguments.length,o=new Array(s>3?s-3:0),a=3;a<s;a++)o[a-3]=arguments[a];return e.renderObjs.fitToBbox((r=e.forceGraph).getGraphBbox.apply(r,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()},tbControls:function(e){return e.renderObjs.tbControls()},_destructor:function(){this.pauseAnimation(),this.graphData({nodes:[],links:[]})}},mC),bC),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,r=e.extraRenderers,s=new Mf;return{forceGraph:s,renderObjs:$g({controlType:t,rendererConfig:n,extraRenderers:r}).objects([s]).lights([new Ka.AmbientLight(13421772,Math.PI),new Ka.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 r=t.renderObjs.camera(),s=t.renderObjs.renderer(),o=t.renderObjs.controls();o.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=r.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(),r.position.x===0&&r.position.y===0&&r.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(r.lookAt(t.forceGraph.position),t.lastSetCameraZ=r.position.z=Math.cbrt(t.graphData.nodes.length)*pC)}).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 Oy(t.graphData.nodes.map(function(c){return c.__threeObj}).filter(function(c){return c}),r,s.domElement);l.addEventListener("dragstart",function(c){var d=on(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(p){return h["f".concat(p)]=h[p]}),s.domElement.classList.add("grabbable")}}),l.addEventListener("drag",function(c){var d=on(c.object);if(d){if(!c.object.hasOwnProperty("__graphObjType")){var h=c.object.__initialPos,p=c.object.__prevPos,f=c.object.position;d.position.add(f.clone().sub(p)),p.copy(f),f.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=on(c.object);if(d){delete c.object.__initialPos,delete c.object.__prevPos;var h=d.__data;h.__disposeControlsAfterDrag&&(l.dispose(),delete h.__disposeControlsAfterDrag);var p=h.__initialFixedPos,f=h.__initialPos,g={x:f.x-h.x,y:f.y-h.y,z:f.z-h.z};if(p&&(["x","y","z"].forEach(function(y){var _="f".concat(y);p[_]===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"}))}s.domElement.classList.remove("grabbable")}})}}),Ka.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(u,l){var c=on(u);if(!c)return 1;var d=on(l);if(!d)return-1;var h=function(f){return f.__graphObjType==="node"};return h(d)-h(c)}).tooltipContent(function(u){var l=on(u);return l&&fe(t["".concat(l.__graphObjType,"Label")])(l.__data)||""}).hoverDuringDrag(!1).onHover(function(u){var l=on(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,p=l?l.__data:null;if(c&&c!==h){var f=t["on".concat(c==="node"?"Node":"Link","Hover")];f&&f(null,d)}if(h){var g=t["on".concat(h==="node"?"Node":"Link","Hover")];g&&g(p,c===h?d:null)}s.domElement.classList[(l&&t["on".concat(h==="node"?"Node":"Link","Click")]||!l&&t.onBackgroundClick)&&fe(t.showPointerCursor)(p)?"add":"remove"]("clickable"),t.hoverObj=l}}).clickAfterDrag(!1).onClick(function(u,l){var c=on(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=on(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 on(i){for(var e=i;e&&!e.hasOwnProperty("__graphObjType");)e=e.parent;return e}export{NC as default};