able:!0}),Object.defineProperty(n.prototype,"Oprev",{get:function(){return this.Sym.Lnext},set:function(t){this.Sym.Lnext=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"Lprev",{get:function(){return this.Onext.Sym},set:function(t){this.Onext.Sym=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"Dprev",{get:function(){return this.Lnext.Sym},set:function(t){this.Lnext.Sym=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"Rprev",{get:function(){return this.Sym.Onext},set:function(t){this.Sym.Onext=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"Dnext",{get:function(){return this.Sym.Onext.Sym},set:function(t){this.Sym.Onext.Sym=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"Rnext",{get:function(){return this.Sym.Lnext.Sym},set:function(t){this.Sym.Lnext.Sym=t},enumerable:!0,configurable:!0}),n}(),Ad=function(){function n(){this.next=null,this.prev=null,this.anEdge=null,this.coords=[0,0,0],this.s=0,this.t=0,this.pqHandle=0,this.n=0,this.idx=0}return n}(),IO=function(){function n(){var t=new Ad,e=new um,r=new _0(0),i=new _0(1);t.next=t.prev=t,t.anEdge=null,e.next=e.prev=e,r.next=r,r.Sym=i,i.next=i,i.Sym=r,this.vHead=t,this.fHead=e,this.eHead=r,this.eHeadSym=i}return n.prototype.makeEdge_=function(t){var e=new _0(0),r=new _0(1);t.Sym.sidethis.size||this.leq(r[i].key,r[s].key)){e[t].handle=i,r[i].node=t;break}e[t].handle=s,r[s].node=t,t=o}},n.prototype.floatUp_=function(t){var e=this.nodes,r=this.handles,i,s,o;for(i=e[t].handle;;){if(o=t>>1,s=e[o].handle,o===0||this.leq(r[s].key,r[i].key)){e[t].handle=i,r[i].node=t;break}e[t].handle=s,r[s].node=t,t=o}},n.prototype.init=function(){for(var t=this.size;t>=1;--t)this.floatDown_(t);this.initialized=!0},n.prototype.min=function(){return this.handles[this.nodes[1].handle].key},n.prototype.insert=function(t){var e,r;if(e=++this.size,e*2>this.max){this.max*=2;var i,s;for(s=this.nodes.length,this.nodes.length=this.max+1,i=s;i0&&(t[1].handle=t[this.size].handle,e[t[1].handle].node=1,e[r].key=null,e[r].node=this.freeList,this.freeList=r,--this.size,this.size>0&&this.floatDown_(1)),i},n.prototype.delete=function(t){var e=this.nodes,r=this.handles,i;ut(t>=1&&t<=this.max&&r[t].key!==null),i=r[t].node,e[i].handle=e[this.size].handle,r[e[i].handle].node=i,--this.size,i<=this.size&&(i<=1||this.leq(r[e[i>>1].handle].key,r[e[i].handle].key)?this.floatDown_(i):this.floatUp_(i)),r[t].key=null,r[t].node=this.freeList,this.freeList=t},n}(),B1=function(){function n(){this.eUp=null,this.nodeUp=null,this.windingNumber=0,this.inside=!1,this.sentinel=!1,this.dirty=!1,this.fixUpperEdge=!1}return n}(),RO=function(){function n(){this.key=null,this.next=null,this.prev=null}return n}(),Z7=function(){function n(t,e){this.frame=t,this.leq=e,this.head=new RO,this.head.next=this.head,this.head.prev=this.head}return n.prototype.min=function(){return this.head.next},n.prototype.max=function(){return this.head.prev},n.prototype.insert=function(t){return this.insertBefore(this.head,t)},n.prototype.search=function(t){var e=this.head;do e=e.next;while(e.key!==null&&!this.leq(this.frame,t,e.key));return e},n.prototype.insertBefore=function(t,e){do t=t.prev;while(t.key!==null&&!this.leq(this.frame,t.key,e));var r=new RO;return r.key=e,r.next=t.next,t.next.prev=r,r.prev=t,t.next=r,r},n.prototype.delete=function(t){t.next.prev=t.prev,t.prev.next=t.next},n}(),J7=function(){function n(){}return n.regionBelow=function(t){return t.nodeUp.prev.key},n.regionAbove=function(t){return t.nodeUp.next.key},n.debugEvent=function(t){},n.addWinding=function(t,e){t.winding+=e.winding,t.Sym.winding+=e.Sym.winding},n.edgeLeq=function(t,e,r){var i=t.event,s=e.eUp,o=r.eUp;if(s.Dst===i)return o.Dst===i?ot.vertLeq(s.Org,o.Org)?ot.edgeSign(o.Dst,s.Org,o.Org)<=0:ot.edgeSign(s.Dst,o.Org,s.Org)>=0:ot.edgeSign(o.Dst,i,o.Org)<=0;if(o.Dst===i)return ot.edgeSign(s.Dst,i,s.Org)>=0;var a=ot.edgeEval(s.Dst,i,s.Org),l=ot.edgeEval(o.Dst,i,o.Org);return a>=l},n.deleteRegion=function(t,e){e.fixUpperEdge&&ut(e.eUp.winding===0),e.eUp.activeRegion=null,t.dict.delete(e.nodeUp)},n.fixUpperEdge=function(t,e,r){ut(e.fixUpperEdge),t.mesh.delete(e.eUp),e.fixUpperEdge=!1,e.eUp=r,r.activeRegion=e},n.topLeftRegion=function(t,e){var r=e.eUp.Org,i;do e=n.regionAbove(e);while(e.eUp.Org===r);if(e.fixUpperEdge){if(i=t.mesh.connect(n.regionBelow(e).eUp.Sym,e.eUp.Lnext),i===null)return null;n.fixUpperEdge(t,e,i),e=n.regionAbove(e)}return e},n.topRightRegion=function(t){var e=t.eUp.Dst;do t=n.regionAbove(t);while(t.eUp.Dst===e);return t},n.addRegionBelow=function(t,e,r){var i=new B1;return i.eUp=r,i.nodeUp=t.dict.insertBefore(e.nodeUp,i),i.fixUpperEdge=!1,i.sentinel=!1,i.dirty=!1,r.activeRegion=i,i},n.isWindingInside=function(t,e){switch(t.windingRule){case zt.ODD:return(e&1)!==0;case zt.NONZERO:return e!==0;case zt.POSITIVE:return e>0;case zt.NEGATIVE:return e<0;case zt.ABS_GEQ_TWO:return e>=2||e<=-2}throw new Error("Invalid winding rulle")},n.computeWinding=function(t,e){e.windingNumber=n.regionAbove(e).windingNumber+e.eUp.winding,e.inside=n.isWindingInside(t,e.windingNumber)},n.finishRegion=function(t,e){var r=e.eUp,i=r.Lface;i.inside=e.inside,i.anEdge=r,n.deleteRegion(t,e)},n.finishLeftRegions=function(t,e,r){for(var i,s=null,o=e,a=e.eUp;o!==r;){if(o.fixUpperEdge=!1,s=n.regionBelow(o),i=s.eUp,i.Org!=a.Org){if(!s.fixUpperEdge){n.finishRegion(t,o);break}i=t.mesh.connect(a.Lprev,i.Sym),n.fixUpperEdge(t,s,i)}a.Onext!==i&&(t.mesh.splice(i.Oprev,i),t.mesh.splice(a,i)),n.finishRegion(t,o),a=s.eUp,o=s}return a},n.addRightEdges=function(t,e,r,i,s,o){var a,l,c,u,h=!0;c=r;do ut(ot.vertLeq(c.Org,c.Dst)),n.addRegionBelow(t,e,c.Sym),c=c.Onext;while(c!==i);for(s===null&&(s=n.regionBelow(e).eUp.Rprev),l=e,u=s;a=n.regionBelow(l),c=a.eUp.Sym,c.Org===u.Org;)c.Onext!==u&&(t.mesh.splice(c.Oprev,c),t.mesh.splice(u.Oprev,c)),a.windingNumber=l.windingNumber-c.winding,a.inside=n.isWindingInside(t,a.windingNumber),l.dirty=!0,!h&&n.checkForRightSplice(t,l)&&(n.addWinding(c,u),n.deleteRegion(t,l),t.mesh.delete(u)),h=!1,l=a,u=c;l.dirty=!0,ut(l.windingNumber-c.winding===a.windingNumber),o&&n.walkDirtyRegions(t,l)},n.spliceMergeVertices=function(t,e,r){t.mesh.splice(e,r)},n.vertexWeights=function(t,e,r){var i=ot.vertL1dist(e,t),s=ot.vertL1dist(r,t),o=.5*s/(i+s),a=.5*i/(i+s);t.coords[0]+=o*e.coords[0]+a*r.coords[0],t.coords[1]+=o*e.coords[1]+a*r.coords[1],t.coords[2]+=o*e.coords[2]+a*r.coords[2]},n.getIntersectData=function(t,e,r,i,s,o){e.coords[0]=e.coords[1]=e.coords[2]=0,e.idx=-1,n.vertexWeights(e,r,i),n.vertexWeights(e,s,o)},n.checkForRightSplice=function(t,e){var r=n.regionBelow(e),i=e.eUp,s=r.eUp;if(ot.vertLeq(i.Org,s.Org)){if(ot.edgeSign(s.Dst,i.Org,s.Org)>0)return!1;ot.vertEq(i.Org,s.Org)?i.Org!==s.Org&&(t.pq.delete(i.Org.pqHandle),n.spliceMergeVertices(t,s.Oprev,i)):(t.mesh.splitEdge(s.Sym),t.mesh.splice(i,s.Oprev),e.dirty=r.dirty=!0)}else{if(ot.edgeSign(i.Dst,s.Org,i.Org)<0)return!1;n.regionAbove(e).dirty=e.dirty=!0,t.mesh.splitEdge(i.Sym),t.mesh.splice(s.Oprev,i)}return!0},n.checkForLeftSplice=function(t,e){var r=n.regionBelow(e),i=e.eUp,s=r.eUp,o;if(ut(!ot.vertEq(i.Dst,s.Dst)),ot.vertLeq(i.Dst,s.Dst)){if(ot.edgeSign(i.Dst,s.Dst,i.Org)<0)return!1;n.regionAbove(e).dirty=e.dirty=!0,o=t.mesh.splitEdge(i),t.mesh.splice(s.Sym,o),o.Lface.inside=e.inside}else{if(ot.edgeSign(s.Dst,i.Dst,s.Org)>0)return!1;e.dirty=r.dirty=!0,o=t.mesh.splitEdge(s),t.mesh.splice(i.Lnext,s.Sym),o.Rface.inside=e.inside}return!0},n.checkForIntersect=function(t,e){var r=n.regionBelow(e),i=e.eUp,s=r.eUp,o=i.Org,a=s.Org,l=i.Dst,c=s.Dst,u,h,d=new Ad,f,p;if(ut(!ot.vertEq(c,l)),ut(ot.edgeSign(l,t.event,o)<=0),ut(ot.edgeSign(c,t.event,a)>=0),ut(o!==t.event&&a!==t.event),ut(!e.fixUpperEdge&&!r.fixUpperEdge),o===a||(u=Math.min(o.t,l.t),h=Math.max(a.t,c.t),u>h))return!1;if(ot.vertLeq(o,a)){if(ot.edgeSign(c,o,a)>0)return!1}else if(ot.edgeSign(l,a,o)<0)return!1;return n.debugEvent(t),ot.intersect(l,o,c,a,d),ut(Math.min(o.t,l.t)<=d.t),ut(d.t<=Math.max(a.t,c.t)),ut(Math.min(c.s,l.s)<=d.s),ut(d.s<=Math.max(a.s,o.s)),ot.vertLeq(d,t.event)&&(d.s=t.event.s,d.t=t.event.t),f=ot.vertLeq(o,a)?o:a,ot.vertLeq(f,d)&&(d.s=f.s,d.t=f.t),ot.vertEq(d,o)||ot.vertEq(d,a)?(n.checkForRightSplice(t,e),!1):!ot.vertEq(l,t.event)&&ot.edgeSign(l,t.event,d)>=0||!ot.vertEq(c,t.event)&&ot.edgeSign(c,t.event,d)<=0?c===t.event?(t.mesh.splitEdge(i.Sym),t.mesh.splice(s.Sym,i),e=n.topLeftRegion(t,e),i=n.regionBelow(e).eUp,n.finishLeftRegions(t,n.regionBelow(e),r),n.addRightEdges(t,e,i.Oprev,i,i,!0),!0):l===t.event?(t.mesh.splitEdge(s.Sym),t.mesh.splice(i.Lnext,s.Oprev),r=e,e=n.topRightRegion(e),p=n.regionBelow(e).eUp.Rprev,r.eUp=s.Oprev,s=n.finishLeftRegions(t,r,null),n.addRightEdges(t,e,s.Onext,i.Rprev,p,!0),!0):(ot.edgeSign(l,t.event,d)>=0&&(n.regionAbove(e).dirty=e.dirty=!0,t.mesh.splitEdge(i.Sym),i.Org.s=t.event.s,i.Org.t=t.event.t),ot.edgeSign(c,t.event,d)<=0&&(e.dirty=r.dirty=!0,t.mesh.splitEdge(s.Sym),s.Org.s=t.event.s,s.Org.t=t.event.t),!1):(t.mesh.splitEdge(i.Sym),t.mesh.splitEdge(s.Sym),t.mesh.splice(s.Oprev,i),i.Org.s=d.s,i.Org.t=d.t,i.Org.pqHandle=t.pq.insert(i.Org),n.getIntersectData(t,i.Org,o,l,a,c),n.regionAbove(e).dirty=e.dirty=r.dirty=!0,!1)},n.walkDirtyRegions=function(t,e){for(var r=n.regionBelow(e),i,s;;){for(;r.dirty;)e=r,r=n.regionBelow(r);if(!e.dirty&&(r=e,e=n.regionAbove(e),e===null||!e.dirty))return;if(e.dirty=!1,i=e.eUp,s=r.eUp,i.Dst!==s.Dst&&n.checkForLeftSplice(t,e)&&(r.fixUpperEdge?(n.deleteRegion(t,r),t.mesh.delete(s),r=n.regionBelow(e),s=r.eUp):e.fixUpperEdge&&(n.deleteRegion(t,e),t.mesh.delete(i),e=n.regionAbove(r),i=e.eUp)),i.Org!==s.Org)if(i.Dst!==s.Dst&&!e.fixUpperEdge&&!r.fixUpperEdge&&(i.Dst===t.event||s.Dst===t.event)){if(n.checkForIntersect(t,e))return}else n.checkForRightSplice(t,e);i.Org===s.Org&&i.Dst===s.Dst&&(n.addWinding(s,i),n.deleteRegion(t,e),t.mesh.delete(i),e=n.regionAbove(r))}},n.connectRightVertex=function(t,e,r){var i,s=r.Onext,o=n.regionBelow(e),a=e.eUp,l=o.eUp,c=!1;if(a.Dst!==l.Dst&&n.checkForIntersect(t,e),ot.vertEq(a.Org,t.event)&&(t.mesh.splice(s.Oprev,a),e=n.topLeftRegion(t,e),s=n.regionBelow(e).eUp,n.finishLeftRegions(t,n.regionBelow(e),o),c=!0),ot.vertEq(l.Org,t.event)&&(t.mesh.splice(r,l.Oprev),r=n.finishLeftRegions(t,o,null),c=!0),c){n.addRightEdges(t,e,r.Onext,s,s,!0);return}ot.vertLeq(l.Org,a.Org)?i=l.Oprev:i=a,i=t.mesh.connect(r.Lprev,i),n.addRightEdges(t,e,i,i.Onext,i.Onext,!1),i.Sym.activeRegion.fixUpperEdge=!0,n.walkDirtyRegions(t,e)},n.connectLeftDegenerate=function(t,e,r){var i,s,o,a,l;if(i=e.eUp,ot.vertEq(i.Org,r)){ut(!1),n.spliceMergeVertices(t,i,r.anEdge);return}if(!ot.vertEq(i.Dst,r)){t.mesh.splitEdge(i.Sym),e.fixUpperEdge&&(t.mesh.delete(i.Onext),e.fixUpperEdge=!1),t.mesh.splice(r.anEdge,i),n.sweepEvent(t,r);return}ut(!1),e=n.topRightRegion(e),l=n.regionBelow(e),o=l.eUp.Sym,s=a=o.Onext,l.fixUpperEdge&&(ut(s!==o),n.deleteRegion(t,l),t.mesh.delete(o),o=s.Oprev),t.mesh.splice(r.anEdge,o),ot.edgeGoesLeft(s)||(s=null),n.addRightEdges(t,e,o.Onext,a,s,!0)},n.connectLeftVertex=function(t,e){var r,i,s,o,a,l,c=new B1;if(c.eUp=e.anEdge.Sym,r=t.dict.search(c).key,i=n.regionBelow(r),!!i){if(o=r.eUp,a=i.eUp,ot.edgeSign(o.Dst,e,o.Org)===0){n.connectLeftDegenerate(t,r,e);return}if(s=ot.vertLeq(a.Dst,o.Dst)?r:i,r.inside||s.fixUpperEdge){if(s===r)l=t.mesh.connect(e.anEdge.Sym,o.Lnext);else{var u=t.mesh.connect(a.Dnext,e.anEdge);l=u.Sym}s.fixUpperEdge?n.fixUpperEdge(t,s,l):n.computeWinding(t,n.addRegionBelow(t,r,l)),n.sweepEvent(t,e)}else n.addRightEdges(t,r,e.anEdge,e.anEdge,null,!0)}},n.sweepEvent=function(t,e){t.event=e,n.debugEvent(t);for(var r=e.anEdge;r.activeRegion===null;)if(r=r.Onext,r===e.anEdge){n.connectLeftVertex(t,e);return}var i=n.topLeftRegion(t,r.activeRegion);ut(i!==null);var s=n.regionBelow(i),o=s.eUp,a=n.finishLeftRegions(t,s,null);a.Onext===o?n.connectRightVertex(t,i,a):n.addRightEdges(t,i,a.Onext,o,o,!0)},n.addSentinel=function(t,e,r,i){var s=new B1,o=t.mesh.makeEdge();o.Org.s=r,o.Org.t=i,o.Dst.s=e,o.Dst.t=i,t.event=o.Dst,s.eUp=o,s.windingNumber=0,s.inside=!1,s.fixUpperEdge=!1,s.sentinel=!0,s.dirty=!1,s.nodeUp=t.dict.insert(s)},n.initEdgeDict=function(t){t.dict=new Z7(t,n.edgeLeq);var e=t.bmax[0]-t.bmin[0],r=t.bmax[1]-t.bmin[1],i=t.bmin[0]-e,s=t.bmax[0]+e,o=t.bmin[1]-r,a=t.bmax[1]+r;n.addSentinel(t,i,s,o),n.addSentinel(t,i,s,a)},n.doneEdgeDict=function(t){for(var e,r=0;(e=t.dict.min().key)!==null;)e.sentinel||(ut(e.fixUpperEdge),ut(++r===1)),ut(e.windingNumber===0),n.deleteRegion(t,e)},n.removeDegenerateEdges=function(t){var e,r,i,s=t.mesh.eHead;for(e=s.next;e!==s;e=r)r=e.next,i=e.Lnext,ot.vertEq(e.Org,e.Dst)&&e.Lnext.Lnext!==e&&(n.spliceMergeVertices(t,i,e),t.mesh.delete(e),e=i,i=e.Lnext),i.Lnext===e&&(i!==e&&((i===r||i===r.Sym)&&(r=r.next),t.mesh.delete(i)),(e===r||e===r.Sym)&&(r=r.next),t.mesh.delete(e))},n.initPriorityQ=function(t){var e,r,i,s=0;for(i=t.mesh.vHead,r=i.next;r!==i;r=r.next)s++;for(s+=8,e=t.pq=new Q7(s,ot.vertLeq),i=t.mesh.vHead,r=i.next;r!==i;r=r.next)r.pqHandle=e.insert(r);return r!==i?!1:(e.init(),!0)},n.donePriorityQ=function(t){t.pq=null},n.removeDegenerateFaces=function(t,e){var r,i,s;for(r=e.fHead.next;r!==e.fHead;r=i)i=r.next,s=r.anEdge,ut(s.Lnext!==s),s.Lnext.Lnext===s&&(n.addWinding(s.Onext,s),t.mesh.delete(s));return!0},n.computeInterior=function(t,e){e===void 0&&(e=!0);var r,i;if(n.removeDegenerateEdges(t),!n.initPriorityQ(t))return!1;for(n.initEdgeDict(t);(r=t.pq.extractMin())!==null;){for(;i=t.pq.min(),!(i===null||!ot.vertEq(i,r));)i=t.pq.extractMin(),n.spliceMergeVertices(t,r.anEdge,i.anEdge);n.sweepEvent(t,r)}return t.event=t.dict.min().key.eUp.Org,n.debugEvent(t),n.doneEdgeDict(t),n.donePriorityQ(t),n.removeDegenerateFaces(t,t.mesh)?(e&&t.mesh.check(),!0):!1},n}(),$7=function(){function n(){this.mesh=new IO,this.normal=[0,0,0],this.sUnit=[0,0,0],this.tUnit=[0,0,0],this.bmin=[0,0],this.bmax=[0,0],this.windingRule=zt.ODD,this.dict=null,this.pq=null,this.event=null,this.vertexIndexCounter=0,this.vertices=[],this.vertexIndices=[],this.vertexCount=0,this.elements=[],this.elementCount=0}return n.prototype.dot_=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},n.prototype.normalize_=function(t){var e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2];if(!e)throw"Zero-size vector!";e=Math.sqrt(e),t[0]/=e,t[1]/=e,t[2]/=e},n.prototype.longAxis_=function(t){var e=0;return Math.abs(t[1])>Math.abs(t[0])&&(e=1),Math.abs(t[2])>Math.abs(t[e])&&(e=2),e},n.prototype.computeNormal_=function(t){var e,r,i,s,o,a,l=[0,0,0],c=[0,0,0],u=[0,0,0],h=[0,0,0],d=[0,0,0],f=[null,null,null],p=[null,null,null],m=this.mesh.vHead;e=m.next;for(var g=0;g<3;++g)s=e.coords[g],c[g]=s,p[g]=e,l[g]=s,f[g]=e;for(e=m.next;e!==m;e=e.next)for(var y=0;y<3;++y)s=e.coords[y],sl[y]&&(l[y]=s,f[y]=e);var v=0;if(l[1]-c[1]>l[0]-c[0]&&(v=1),l[2]-c[2]>l[v]-c[v]&&(v=2),c[v]>=l[v]){t[0]=0,t[1]=0,t[2]=1;return}for(a=0,r=p[v],i=f[v],u[0]=r.coords[0]-i.coords[0],u[1]=r.coords[1]-i.coords[1],u[2]=r.coords[2]-i.coords[2],e=m.next;e!==m;e=e.next)h[0]=e.coords[0]-i.coords[0],h[1]=e.coords[1]-i.coords[1],h[2]=e.coords[2]-i.coords[2],d[0]=u[1]*h[2]-u[2]*h[1],d[1]=u[2]*h[0]-u[0]*h[2],d[2]=u[0]*h[1]-u[1]*h[0],o=d[0]*d[0]+d[1]*d[1]+d[2]*d[2],o>a&&(a=o,t[0]=d[0],t[1]=d[1],t[2]=d[2]);a<=0&&(t[0]=t[1]=t[2]=0,t[this.longAxis_(u)]=1)},n.prototype.checkOrientation_=function(){for(var t=this.mesh.fHead,e,r=this.mesh.vHead,i,s=0,o=t.next;o!==t;o=o.next)if(i=o.anEdge,!(i.winding<=0))do s+=(i.Org.s-i.Dst.s)*(i.Org.t+i.Dst.t),i=i.Lnext;while(i!==o.anEdge);if(s<0){for(e=r.next;e!==r;e=e.next)e.t=-e.t;this.tUnit[0]=-this.tUnit[0],this.tUnit[1]=-this.tUnit[1],this.tUnit[2]=-this.tUnit[2]}},n.prototype.projectPolygon_=function(){var t=this.mesh.vHead,e=[0,0,0],r,i,s=!1;e[0]=this.normal[0],e[1]=this.normal[1],e[2]=this.normal[2],!e[0]&&!e[1]&&!e[2]&&(this.computeNormal_(e),s=!0),r=this.sUnit,i=this.tUnit;var o=this.longAxis_(e);r[o]=0,r[(o+1)%3]=1,r[(o+2)%3]=0,i[o]=0,i[(o+1)%3]=0,i[(o+2)%3]=e[o]>0?1:-1;for(var a=t.next;a!==t;a=a.next)a.s=this.dot_(a.coords,r),a.t=this.dot_(a.coords,i);s&&this.checkOrientation_();for(var l=!0,c=t.next;c!==t;c=c.next)l?(this.bmin[0]=this.bmax[0]=c.s,this.bmin[1]=this.bmax[1]=c.t,l=!1):(c.sthis.bmax[0]&&(this.bmax[0]=c.s),c.tthis.bmax[1]&&(this.bmax[1]=c.t))},n.prototype.addWinding_=function(t,e){t.winding+=e.winding,t.Sym.winding+=e.Sym.winding},n.prototype.tessellateMonoRegion_=function(t,e){var r,i;if(r=e.anEdge,!(r.Lnext!==r&&r.Lnext.Lnext!==r))throw"Mono region invalid";for(;ot.vertLeq(r.Dst,r.Org);r=r.Lprev);for(;ot.vertLeq(r.Org,r.Dst);r=r.Lnext);i=r.Lprev;for(var s=void 0;r.Lnext!==i;)if(ot.vertLeq(r.Dst,i.Org)){for(;i.Lnext!==r&&(ot.edgeGoesLeft(i.Lnext)||ot.edgeSign(i.Org,i.Dst,i.Lnext.Dst)<=0);)s=t.connect(i.Lnext,i),i=s.Sym;i=i.Lprev}else{for(;i.Lnext!==r&&(ot.edgeGoesRight(r.Lprev)||ot.edgeSign(r.Dst,r.Org,r.Lprev.Org)>=0);)s=t.connect(r,r.Lprev),r=s.Sym;r=r.Lnext}if(i.Lnext===r)throw"Mono region invalid";for(;i.Lnext.Lnext!==r;)s=t.connect(i.Lnext,i),i=s.Sym;return!0},n.prototype.tessellateInterior_=function(t){for(var e,r=t.fHead.next;r!==t.fHead;r=e)if(e=r.next,r.inside&&!this.tessellateMonoRegion_(t,r))return!1;return!0},n.prototype.discardExterior_=function(t){for(var e,r=t.fHead.next;r!==t.fHead;r=e)e=r.next,r.inside||t.zapFace(r)},n.prototype.setWindingNumber_=function(t,e,r){for(var i,s=t.eHead.next;s!==t.eHead;s=i)i=s.next,s.Rface.inside!==s.Lface.inside?s.winding=s.Lface.inside?e:-e:r?t.delete(s):s.winding=0},n.prototype.getNeighbourFace_=function(t){return!t.Rface||!t.Rface.inside?-1:t.Rface.n},n.prototype.outputPolymesh_=function(t,e,r,i){var s,o=0,a=0,l;r>3&&t.mergeConvexFaces(r);for(var c=t.vHead.next;c!==t.vHead;c=c.next)c.n=-1;for(var u=t.fHead.next;u!==t.fHead;u=u.next)if(u.n=-1,!!u.inside){s=u.anEdge,l=0;do{var c=s.Org;c.n===-1&&(c.n=a,a++),l++,s=s.Lnext}while(s!==u.anEdge);if(l>r)throw"Face vertex greater that support polygon";u.n=o,++o}this.elementCount=o,e===jr.CONNECTED_POLYGONS&&(o*=2),this.elements=[],this.elements.length=o*r,this.vertexCount=a,this.vertices=[],this.vertices.length=a*i,this.vertexIndices=[],this.vertexIndices.length=a;for(var c=t.vHead.next;c!==t.vHead;c=c.next)if(c.n!==-1){var h=c.n*i;this.vertices[h+0]=c.coords[0],this.vertices[h+1]=c.coords[1],i>2&&(this.vertices[h+2]=c.coords[2]),this.vertexIndices[c.n]=c.idx}for(var d=0,u=t.fHead.next;u!==t.fHead;u=u.next)if(!!u.inside){s=u.anEdge,l=0;do{var c=s.Org;this.elements[d++]=c.n,l++,s=s.Lnext}while(s!==u.anEdge);for(var f=l;f2&&(this.vertices[l++]=r.Org.coords[2]),this.vertexIndices[c++]=this.vertexIdCallback?this.vertexIdCallback(r):r.Org.idx,o++,r=r.Lnext;while(r!==i);this.elements[u++]=s,this.elements[u++]=o,s+=o}},n.prototype.addContour=function(t,e){this.mesh===null&&(this.mesh=new IO),t<2&&(t=2),t>3&&(t=3);for(var r=null,i=0;i2?r.Org.coords[2]=e[i+2]:r.Org.coords[2]=0,r.Org.idx=this.vertexIndexCounter++,this.edgeCreateCallback&&this.edgeCreateCallback(r),r.winding=1,r.Sym.winding=-1},n.prototype.tesselate=function(t,e,r,i,s,o){if(t===void 0&&(t=zt.ODD),e===void 0&&(e=jr.POLYGONS),o===void 0&&(o=!0),this.vertices=[],this.elements=[],this.vertexIndices=[],this.vertexIndexCounter=0,s&&(this.normal[0]=s[0],this.normal[1]=s[1],this.normal[2]=s[2]),this.windingRule=t,i<2&&(i=2),i>3&&(i=3),!this.mesh)return!1;this.projectPolygon_(),J7.computeInterior(this,o);var a=this.mesh;return e===jr.BOUNDARY_CONTOURS?this.setWindingNumber_(a,1,!0):this.tessellateInterior_(a),o&&a.check(),e===jr.BOUNDARY_CONTOURS?this.outputContours_(a,i):this.outputPolymesh_(a,e,r,i),!0},n}();function qs(n){var t=n.windingRule,e=t===void 0?zt.ODD:t,r=n.elementType,i=r===void 0?jr.POLYGONS:r,s=n.polySize,o=s===void 0?3:s,a=n.vertexSize,l=a===void 0?2:a,c=n.normal,u=c===void 0?[0,0,1]:c,h=n.contours,d=h===void 0?[]:h,f=n.strict,p=f===void 0?!0:f,m=n.debug,g=m===void 0?!1:m;if(!d&&p)throw new Error("Contours can't be empty");if(!!d){var y=new $7;n.edgeCreateCallback&&(y.edgeCreateCallback=n.edgeCreateCallback),n.vertexIdCallback&&(y.vertexIdCallback=n.vertexIdCallback);for(var v=0;vthis.capacity){let i=this.capacity;for(;e>i;)i*=2;this.realloc(i)}let r=this.size;return this.size=e,r}reserve(t){let e=this.size+t;e>this.capacity&&this.realloc(e)}shrink(){this.debug&&console.log(`shrinking ${this.capacity} \u2192 ${this.size}`),this.realloc(this.size,!0)}},hm=I0;hm.eSize=(3+3+2)*Float32Array.BYTES_PER_ELEMENT;var FO=ta(NO()),dm={vertices:[160,160,-160,160,-160,-160,160,-160],vertexIndices:[1,0,3,2],vertexCount:4,elements:[0,4],elementCount:1,mesh:void 0},U1={vertices:[],vertexIndices:[],vertexCount:0,elements:[],elementCount:0,mesh:void 0},z1={vertices:[-160,160,160,-160,160,160,-160,-160],vertexIndices:[1,3,0,2],vertexCount:4,elements:[0,1,2,1,0,3],elementCount:2,mesh:void 0},k1=(n,t)=>([e,r])=>(r=e?n:n+t)<=r),Vl=class extends _e{constructor(e,r,i=0,s=12,o=3,a=zt.ODD,l=!1){super();this.forPathBevel=l;this.type="ShapeGeometry";this.vertexCache={};this._shape=e,this._depth=r,this._curveSegments=s,this._bevelSegmentsInput=o;let c=this._shape.extractShapePointsToFlatArray([],s),u=this._shape.shapeHoles.map(P=>{let I=P.extractShapePointsToFlatArray([],s),_=[];for(let D=I.length-1;D>=1;D-=2){let L=I[D-1],j=I[D-0];_.push(L,j)}return _}),h=[],d=[];for(let P=0;PI.position)).getSize(new k).length()*.1:h[0].length===0?f=i:f=(0,FO.default)(h).distance,i<=0?(this._bevel=0,this._bevelSegments=0):(this._bevel=Math.min(i,f,r/2),this._bevelSegments=Math.floor(o));let p;try{p=qs({windingRule:a,elementType:jr.BOUNDARY_CONTOURS,vertexSize:2,strict:!0,contours:[c]})}catch{p=dm}let m;try{m=qs({windingRule:zt.ODD,elementType:jr.BOUNDARY_CONTOURS,vertexSize:2,strict:!0,contours:[...u]})}catch{m=U1}if(!p)throw new Error("error generating geometry");let g=p.elementCount;if(m){p.elementCount+=m.elementCount;for(let P=0;Pv&&(v=D),LS&&(S=L)}this._minX=y,this._minY=x,this._width=v-y,this._height=S-x,this._buffer=new hm(this._computeBufferEstimatedSize(p));let w=[],A=[];for(let P=p.elementCount-1;P>=0;P--){let I=P>=g,_=P*2,D=p.elements[_+0],L=p.elements[_+1],j=D+L,V={start:D,count:L,normals:[],continuous:[],concave:[]},H=D,W=j-1,q=D+1,Q=this._shape.roundedCurves.length;do{let Y=H-D,oe=p.vertices[W*2+0],ie=p.vertices[W*2+1],re=p.vertices[H*2+0],J=p.vertices[H*2+1],Ae=p.vertices[q*2+0],xe=p.vertices[q*2+1],de=re-oe,De=J-ie,Ce=Math.sqrt(de*de+De*De);de/=Ce,De/=Ce;let ze=re-Ae,Ue=J-xe,Ve=Math.sqrt(ze*ze+Ue*Ue);ze/=Ve,Ue/=Ve,V.normals[Y*2+0]=-Ue,V.normals[Y*2+1]=ze,V.concave[Y]=de*Ue-De*ze>0;let Oe=p.vertexIndices[H];if(Array.isArray(Oe))V.continuous[Y]=!1;else{let[Ye,F]=this._shape.getCurveIndexFromVertexId(Oe-1,!0);if(F>0&&F<1)V.continuous[Y]=!0;else{let N=F===1?Ye+1:Ye-1;N=(N+Q)%Q;let B=F===1?0:1,ae=this._shape.roundedCurves[Ye].getTangent(F),ge=this._shape.roundedCurves[N].getTangent(B);V.continuous[Y]=ae.dot(ge)>.95}}I&&(V.normals[Y*2+0]*=-1,V.normals[Y*2+1]*=-1),[W,H,q]=[H,q,q+1],q>=j&&(q-=L)}while(q!==D+1);let G=[];G.push({bevelI:0,angle:0,size:0,boundary:{vertices:p.vertices.slice(D*2,j*2),vertexCount:L,vertexIndices:new Array(L).fill(!0).map((Y,oe)=>[oe,oe]),elements:[0,L],elementCount:1,mesh:null},reverseMap:[],insetPoints:p.vertices.slice(D*2,j*2)});let Z=0;for(let Y=1;Y<=this._bevelSegments;Y++){let oe=Y/this._bevelSegments*Math.PI/2,ie=(1-Math.cos(oe))*this._bevel,re=[],J=[],Ae=[],xe=[],de=0;for(let Ce=0;Ceae&&(ge-=Math.PI*2);let me=ge-ae;if(V.continuous[Ce]||I){let Le=ae+me/2,Ne=Math.cos(Le)*ie,Re=Math.sin(Le)*ie;re[2*de+0]=Ve+Ne*(I?-1:1),re[2*de+1]=Oe+Re*(I?-1:1),xe[de]=Ce,de++}else{let Le=Math.max(1,Math.floor(s/4*Math.abs(me)/Math.PI));for(let Ne=0;Ne<=Le;Ne++){let Re=ae+me*(Ne/Le),pe=Math.cos(Re)*ie,nt=Math.sin(Re)*ie;re[2*de+0]=Ve+pe,re[2*de+1]=Oe+nt,xe[de]=Ce,de++}}}else re[2*de+0]=Ve+Ye,re[2*de+1]=Oe+F,xe[de]=Ce,J[Ce]=de,de++,re[2*de+0]=Ve,re[2*de+1]=Oe,xe[de]=Ce,de++,re[2*de+0]=Ve+N,re[2*de+1]=Oe+B,xe[de]=Ce,Ae[Ce]=de,de++}let De=qs({windingRule:zt.POSITIVE,elementType:jr.BOUNDARY_CONTOURS,vertexSize:2,strict:!0,contours:[re],edgeCreateCallback:Ce=>{let Ue=Ce.Org.idx,Ve=xe[Ue],Oe=xe[(Ue+1)%xe.length];Ce.idx=[Ve,Oe],Ce.Sym.idx=[Oe,Ve]},vertexIdCallback:Ce=>{let ze=Ce.Lprev.idx;return[ze?ze[1]:0,Ce.idx?Ce.idx[0]:0]}});if(!De)throw console.log("Error"),new Error(`error generating bevel geometry for ${Y}'th loop`);if(!De.vertexCount){let Ce=(Y-1)/this._bevelSegments*Math.PI/2;Z=(1-Math.sin(Ce))*this._bevel;break}for(let Ce=0;Ce{let re=0,J=Y.boundary.vertexIndices.length;for(;reme){let Ne=ge/me,Re=0;for(let pe=1;pe(Re+1)*Ne&&(Re++,B=this._buildBevelVert(V,ie,(Ce+Re)%J,Re/(me-1),Ue),w.push(F.topN,N.topP,B.topP),l===!1&&w.push(N.bottomP,F.bottomN,B.bottomP),F=B)}else{let Ne=me/ge,Re=0;for(let pe=1;pe(Re+1)*Ne&&(Re++,N=this._buildBevelVert(V,oe,(De+Re)%re,Re/(ge-1),Ue),w.push(Ye.topN,N.topP,F.topN),l===!1&&w.push(N.bottomP,Ye.bottomN,F.bottomN),Ye=N)}De=(De+ge)%re,Ce=(Ce+me)%J,xe=(xe+1)%Ae}while(xe!==ze)}if(l===!1&&this._depth>this._bevel*2&&this._buildWall(G,V,w),I){let Y=[];for(let oe=w.length-1;oe>=$+2;oe-=3){let ie=w[oe-2],re=w[oe-1],J=w[oe-0];Y.push(J,re,ie)}w.splice($,w.length-$,...Y)}if(I){let Y=[];for(let oe=G[G.length-1].boundary.vertices.length-1;oe>=1;oe-=2){let ie=G[G.length-1].boundary.vertices[oe-1],re=G[G.length-1].boundary.vertices[oe-0];Y.push(ie,re)}A.push(Y)}if(!I){let Y=G[G.length-1],oe;try{oe=qs({windingRule:G.length>1?zt.POSITIVE:zt.ODD,elementType:jr.POLYGONS,vertexSize:2,strict:!0,contours:[Y.insetPoints,...A]})}catch{oe=z1}if(!oe)throw new Error("Error generating geometry for surface");u.length===0&&this._bevel0,d=e.continuous[u]||f);let p=Math.cos(r.angle),m=Math.sin(r.angle),g=i*2,y=u*2,v=h*2,x=r.boundary.vertices[g+0],S=r.boundary.vertices[g+1],w=(1-m)*this._bevel,A=(x-this._minX)/this._width,T=(S-this._minY)/this._height;this.forPathBevel&&(o!==void 0&&(A=o),T=1);let b=e.normals[y+0],M=e.normals[y+1],C=e.normals[v+0],P=e.normals[v+1];if(f){let j=C-b,V=P-M;b=b+j*(1-s),M=M+V*(1-s);let H=Math.sqrt(b*b+M*M);b/=H,M/=H}let I=this.forPathBevel?this._buffer.get(d?1:2):this._buffer.get(d?2:4),_=I*3,D=I*2,L={i,fi:u,topP:I+0,topN:I+0,bottomP:I+1,bottomN:I+1,pathBevelUCoord:o};return this._buffer.positions[_+0]=x,this._buffer.positions[_+1]=S,this._buffer.positions[_+2]=(this.forPathBevel?this._bevel:this._depth)-w,this._buffer.normals[_+0]=b*p,this._buffer.normals[_+1]=M*p,this._buffer.normals[_+2]=m,this._buffer.uvs[D+0]=A,this._buffer.uvs[D+1]=T,this.forPathBevel===!1&&(this._buffer.positions[_+3]=x,this._buffer.positions[_+4]=S,this._buffer.positions[_+5]=w,this._buffer.normals[_+3]=b*p,this._buffer.normals[_+4]=M*p,this._buffer.normals[_+5]=-m,this._buffer.uvs[D+2]=T,this._buffer.uvs[D+3]=A),d||(this.forPathBevel?(I+=1,_+=3,D+=2):(I+=2,_+=6,D+=4),L.topP=I+0,L.bottomP=I+1,this._buffer.positions[_+0]=x,this._buffer.positions[_+1]=S,this._buffer.positions[_+2]=(this.forPathBevel?this._bevel:this._depth)-w,this._buffer.normals[_+0]=C*p,this._buffer.normals[_+1]=P*p,this._buffer.normals[_+2]=m,this._buffer.uvs[D+0]=A,this._buffer.uvs[D+1]=T,this.forPathBevel===!1&&(this._buffer.positions[_+3]=x,this._buffer.positions[_+4]=S,this._buffer.positions[_+5]=w,this._buffer.normals[_+3]=C*p,this._buffer.normals[_+4]=P*p,this._buffer.normals[_+5]=-m,this._buffer.uvs[D+2]=T,this._buffer.uvs[D+3]=A)),this.vertexCache[a]=L,L}clone(){let e=new Vl(this._shape,this._depth,this._bevel,this._curveSegments,this._bevelSegmentsInput);return e.userData=ga(this.userData),e}};var Ed=class extends _e{constructor(e,r=12,i={}){super();this.type="ShapeGeometry";this.windingRule=zt.ODD;this.elementType=jr.POLYGONS;this.polySize=3;this.vertexSize=2;this.strict=!0;this._shape=e,this._curveSegments=r,this._triangulationOptions=Object.assign({windingRule:zt.ODD,elementType:jr.POLYGONS,polySize:3,vertexSize:2,strict:!0},i);let s=this._shape.extractShapePointsToFlatArray([],this._curveSegments),o=this._shape.shapeHoles.map(p=>p.extractShapePointsToFlatArray([],this._curveSegments)),a,l=!0,c=!0,u,h;for(let p=0,m=s.length/2;pm&&(m=T),by&&(y=b)}let v=m-p,x=y-g;for(let S=0,w=d;S0&&o.update());let l=o??new Xt(r,i);return{parameters:Object.assign(e,{width:r,height:i,depth:s,roundness:a}),shape:l}}static build(n){let{depth:t,extrudeBevelSize:e,extrudeBevelSegments:r,subdivisions:i,roundness:s,windingRule:o}=n.parameters;n.shape.roundness=s;let a;return t<=0?a=new Ed(n.shape,i,{windingRule:o}):a=new Td(n.shape,t,e,i,r,o),Object.assign(a,{userData:{...n,type:"VectorGeometry"}})}};var kO=Math.PI*2,Cd=class{static create(n){return this.build(this.normalizeInputs(n))}static normalizeInputs(n,t){let e=Object.assign({},t?.parameters??{width:100,depth:0,spikes:64,angle:360,innerRadius:0,extrudeBevelSize:0,extrudeBevelSegments:1},n.parameters);return e.angle=we.clamp(e.angle,0,360),{shape:n.shape&&n.shape instanceof Xt?n.shape:new Xt,parameters:Object.assign(e,{width:Math.abs(e.width),height:Math.abs(e.height??e.width),depth:Math.abs(e.depth??0)})}}static build(n){let{width:t,height:e,spikes:r,angle:i,innerRadius:s,depth:o,extrudeBevelSize:a,extrudeBevelSegments:l}=n.parameters,c=n.shape,u=t*.5,h=e*.5,d=nY(c,u,h,i*Math.PI/180,r,s);c.isClosed=!0,c.update();let f;return i===0?(f=new _e,f.setAttribute("position",new Te([],3))):f=Rn.create({shape:c,parameters:{subdivisions:d,depth:o,extrudeBevelSize:a,extrudeBevelSegments:l}}),Object.assign(f,{userData:{...n,type:"EllipseGeometry"}})}};function nY(n,t,e,r,i,s){if(r>=kO)return i>30||i%4===0?(oY(n,t,e,s),Math.round(i/4)):VO(n,r,i,t,e,s);r=Math.max(r,.001);let o={x:0,y:e},a=r+Math.PI*.5,l={x:Math.cos(a)*t,y:Math.sin(a)*e},c=_O({px:o.x,py:o.y,cx:l.x,cy:l.y,rx:t,ry:e,largeArcFlag:r>Math.PI,sweepFlag:!0});return i>30||i%c.length===0?sY(n,o.x,o.y,c,i,t,e,s):VO(n,r,i,t,e,s)}function sY(n,t,e,r,i,s,o,a){let l=Math.round(i/r.length);n.addPoint(Md(t,e));for(let c=0,u=r.length;c0?UO(n,s,o,a):n.addPoint(Md(0,0)),l}function VO(n,t,e,r,i,s){let o=-t/e;for(let a=0;a<=e;a++){let l=o*a,c=Math.sin(l)*r,u=Math.cos(l)*i;n.addPoint(Md(c,u))}return t0?UO(n,r,i,s):n.addPoint(Md(0,0)):(n.removePoint(n.points[n.points.length-1]),s>0&&zO(n,r,i,s)),1}function oY(n,t,e,r=0,i=0,s=0){let o=.5522847498,a=t*o,l=e*o;n.addPoint(O0(i-t,s,i-t,s-l,i-t,s+l)),n.addPoint(O0(i,s+e,i-a,s+e,i+a,s+e)),n.addPoint(O0(i+t,s,i+t,s+l,i+t,s-l)),n.addPoint(O0(i,s-e,i+a,s-e,i-a,s-e)),r>0&&zO(n,t,e,r)}function Md(n,t){return new Ws(we.generateUUID(),new k(n,t))}function O0(n,t,e,r,i,s){let o=Md(n,t);return o.controls[0].position.set(e,r),o.controls[1].position.set(i,s),o}function UO(n,t,e,r){GO(n,t,e,r).forEach(s=>n.addPoint(s))}function zO(n,t,e,r){let i=GO(n,t,e,r),s=new Xt;i.forEach(o=>s.addPoint(o)),s.isClosed=!0,n.shapeHoles.push(s)}function GO(n,t,e,r){let i=r*t/100,s=i*(Math.abs(e)/Math.abs(t)),o=new k(i/t,s/e),a=n.points.map(l=>{let c=l.clone();return c.uuid=we.generateUUID(),c}).reverse();return a.forEach(l=>{l.position.multiply(o);let c=l.controls[0].position.clone().multiply(o),u=l.controls[1].position.clone().multiply(o);l.controls[0].position.copy(u),l.controls[1].position.copy(c)}),a}var jO=class{static create(n){return this.build(this.normalizeInputs(n))}static normalizeInputs(n,t){let e=Object.assign({},t?.parameters??{width:100,revolutions:2,segments:40,pathRadius:10,pathType:0,pathSegments:30,cornerRadius:30,cornerSegments:4},n.parameters),r=Math.abs(e.width),i=Math.abs(e.height??r),s=Math.abs(e.depth??r),o=Math.abs(Math.min(r,s))/2;return{parameters:Object.assign(e,{width:r,height:i,depth:s,radius:o,segments:Math.round(e.segments),pathSegments:Math.round(e.pathSegments),cornerSegments:Math.round(e.cornerSegments)})}}static build(n){let{width:t,height:e,depth:r,radius:i,revolutions:s,segments:o,pathRadius:a,pathType:l,pathSegments:c,cornerRadius:u,cornerSegments:h}=n.parameters,d=new fm(!1,t,e,r,i,s,o,a,l,c,u,h);return Object.assign(d,{userData:{...n,type:"HelixGeometry"}})}},G1=new po([0,0,0],1),fm=class extends _e{constructor(t=!0,e=1,r=1,i=1,s=1,o=1,a=1,l=1,c=1,u=1,h=1,d=1){if(super(),o===0)return;let f=t&&o===1;f&&(d=0),h>100&&(h=100),h===0&&(d=0);let p=()=>new E,m=new E,g=p(),y=p(),v=p(),x,S,w,A,T,b,M,C,P=p(),I=p(),_=p(),D=p(),L=p(),j=p(),V=p(),H=p(),W=r-2*l+.001,q=W/o,Q=Math.ceil(a*o),G=Q+1,Z=W/Q,te=-W/2,$=u+1,Y=2*Math.PI/u,oe=Math.PI/2/d,ie=.01,re=Math.min((1-h/100)*l,l-ie),J=l-re,Ae=0,xe=2,de=d*xe+xe,De=$*de/xe,Ce=De+$*G,ze=Math.max(0,$*(G+de)),[Ue,Ve,Oe]=[3,3,2].map(Ge=>Array(ze*Ge).fill(0)),Ye=[],F=s-l;function N(Ge,Be){let et=Math.PI/2;b=Be*Z,C=2*Math.PI*(b%q)/q+et,b+=te,M=Math.sin(C)*F,T=Math.cos(C)*F,t?Ge.set(T,M,b):Ge.set(T,b,M)}N(m,-1e-10),N(g,0),P.copy(m),N(m,1);let B=m.distanceTo(g),ae=f?0:J+re,ge=B*Q+2*ae,me=re,Le=ge-ae;for(let Ge=0;Ge<=Q;Ge++){N(y,Ge),H.subVectors(y,P).normalize(),P.copy(y),j.copy(y).setComponent(+t+1,0).normalize(),V.crossVectors(H,j).normalize();let Be=Ge===0,et=Ge===Q,st=Be?3*Math.PI/2:oe,Bt=Be?me:Le,dr=Be?$:Ce,Tr=Be?0:ze-$,K=H.clone().multiplyScalar(Be?-J:J).add(y),ye=H.clone().multiplyScalar(Be?-1:1).normalize();for(let Me=0;Me<$;Me++){let je=Me*Y;if(I.addVectors(m.copy(j).multiplyScalar(l*Math.cos(je)),g.copy(V).multiplyScalar(l*Math.sin(je))),_.copy(I).normalize(),Be||et){f||(Ae=Tr+Me,[0,1,2].forEach(He=>{Ue[Ae*3+He]=K.getComponent(He),Ve[Ae*3+He]=ye.getComponent(He)}),Oe[Ae*2]=+et,Oe[Ae*2+1]=Me/u),g.copy(_).multiplyScalar(re),v.addVectors(y,g);for(let He=0;He{Ue[Ae*3+Vr]=g.getComponent(Vr),Ve[Ae*3+Vr]=L.getComponent(Vr)});let Fr=+Be+Math.sin(_t);Oe[Ae*2]=(Bt+J*Fr)/ge,Oe[Ae*2+1]=Me/u}}g.addVectors(y,I),Ae=De+Ge*$+Me,[0,1,2].forEach(He=>{Ue[Ae*3+He]=g.getComponent(He),Ve[Ae*3+He]=_.getComponent(He)}),Oe[Ae*2]=(ae+Ge*B)/ge,Oe[Ae*2+1]=Me/u}}let Ne=G+2*d+xe,Re=1,[pe,nt]=[+f,Ne-1];for(let Ge=pe;Ge<=nt-1;Ge++){let Be=f&&Ge===nt-1;for(let et=0;et<$-1;et++)x=Ge*$+et,S=x+1,w=(Be?et:x)+$,A=(Be?et+1:S)+$,Ge===0?Ye.push(S,A,w):Ge===Ne-2?Ye.push(x,S,w):Ye.push(x,S,w,S,A,w)}this.setIndex(Ye),this.setAttribute("position",new Te(Ue,3)),this.setAttribute("normal",new Te(Ve,3)),this.setAttribute("uv",new Te(Oe,2))}getClosedTorusIndicesForBooleanOrSubdiv(){let t=this.userData.parameters,e=Math.ceil(t.tubularSegments),r=t.radialSegments+1,i=Array.from(this.getIndex().array),s,o,a,l,c=6*(e-1)*t.radialSegments,u=e,h=u===e;for(let d=0;d{Array.isArray(r)&&(r.x=r[0],r.y=r[1])});let e=Object.assign({},t?.parameters??{width:100,segments:64,verticalSegments:64,points:[{x:0,y:-50,id:0},{x:50,y:-50,id:1},{x:50,y:50,id:2},{x:0,y:50,id:3}]},n.parameters);return{parameters:Object.assign(e,{width:Math.abs(e.width),height:Math.abs(e.height??e.width),depth:Math.abs(e.depth??e.width)})}}static build(n){let{points:t,segments:e,verticalSegments:r}=n.parameters,i=new ua;i.moveTo(t[0].x,t[0].y),i.bezierCurveTo(t[1].x,t[1].y,t[2].x,t[2].y,t[3].x,t[3].y);let s=new Uu(i.extractPoints(r).shape,e);return s.rotateZ(Math.PI),Object.assign(s,{userData:{...n,type:"LatheGeometry"}})}};var Lo=new ue,j1=new Tt,R0=new E,kl=class extends pr{constructor(){super(),this.uuid=we.generateUUID(),this.name="",this.type="Geometry",this.vertices=[],this.colors=[],this.faces=[],this.faceVertexUvs=[[]],this.morphTargets=[],this.morphNormals=[],this.skinWeights=[],this.skinIndices=[],this.lineDistances=[],this.boundingBox=null,this.boundingSphere=null,this.elementsNeedUpdate=!1,this.verticesNeedUpdate=!1,this.uvsNeedUpdate=!1,this.normalsNeedUpdate=!1,this.colorsNeedUpdate=!1,this.lineDistancesNeedUpdate=!1,this.groupsNeedUpdate=!1}applyMatrix4(t){let e=new fr().getNormalMatrix(t);for(let r=0,i=this.vertices.length;r0)for(let d=0;d0&&(this.normalsNeedUpdate=!0)}computeFlatVertexNormals(){this.computeFaceNormals();for(let t=0,e=this.faces.length;t0&&(this.normalsNeedUpdate=!0)}computeMorphNormals(){for(let e=0,r=this.faces.length;e=0;l--){let c=o[l];this.faces.splice(c,1);for(let u=0,h=this.faceVertexUvs.length;u0,S=m.vertexNormals.length>0,w=m.color.r!==1||m.color.g!==1||m.color.b!==1,A=m.vertexColors.length>0,T=0;if(T=u(T,0,0),T=u(T,1,g),T=u(T,2,y),T=u(T,3,v),T=u(T,4,x),T=u(T,5,S),T=u(T,6,w),T=u(T,7,A),r.push(T),r.push(m.a,m.b,m.c),r.push(m.materialIndex),v){let b=this.faceVertexUvs[0][p];r.push(f(b[0]),f(b[1]),f(b[2]))}if(x&&r.push(h(m.normal)),S){let b=m.vertexNormals;r.push(h(b[0]),h(b[1]),h(b[2]))}if(w&&r.push(d(m.color)),A){let b=m.vertexColors;r.push(d(b[0]),d(b[1]),d(b[2]))}}function u(p,m,g){return g?p|1<0&&(t.data.colors=o),l.length>0&&(t.data.uvs=[l]),t.data.faces=r,t}clone(){return new kl().copy(this)}copy(t){this.vertices=[],this.colors=[],this.faces=[],this.faceVertexUvs=[[]],this.morphTargets=[],this.morphNormals=[],this.skinWeights=[],this.skinIndices=[],this.lineDistances=[],this.boundingBox=null,this.boundingSphere=null,this.name=t.name;let e=t.vertices;for(let d=0,f=e.length;d0){let i=new Float32Array(t.normals.length*3);e.setAttribute("normal",L0.call(new Xe(i,3),t.normals))}if(t.colors.length>0){let i=new Float32Array(t.colors.length*3);e.setAttribute("color",qO.call(new Xe(i,3),t.colors))}if(t.uvs.length>0){let i=new Float32Array(t.uvs.length*2);e.setAttribute("uv",YO.call(new Xe(i,2),t.uvs))}if(t.uvs2.length>0){let i=new Float32Array(t.uvs2.length*2);e.setAttribute("uv2",YO.call(new Xe(i,2),t.uvs2))}e.groups=t.groups;for(let i in t.morphTargets){let s=[],o=t.morphTargets[i];for(let a=0,l=o.length;a0){let i=new Te(t.skinIndices.length*4,4);e.setAttribute("skinIndex",XO.call(i,t.skinIndices))}if(t.skinWeights.length>0){let i=new Te(t.skinWeights.length*4,4);e.setAttribute("skinWeight",XO.call(i,t.skinWeights))}return t.boundingSphere!==null&&(e.boundingSphere=t.boundingSphere.clone()),t.boundingBox!==null&&(e.boundingBox=t.boundingBox.clone()),e}computeTangents(){console.error("THREE.Geometry: .computeTangents() has been removed.")}computeLineDistances(){console.error("THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.")}applyMatrix(t){return console.warn("THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(t)}dispose(){this.dispatchEvent({type:"dispose"})}static createBufferGeometryFromObject(t){let e=new _e,r=t.geometry;if(t.isPoints||t.isLine){let i=new Te(r.vertices.length*3,3),s=new Te(r.colors.length*3,3);if(e.setAttribute("position",L0.call(i,r.vertices)),e.setAttribute("color",qO.call(s,r.colors)),r.lineDistances&&r.lineDistances.length===r.vertices.length){let o=new Te(r.lineDistances.length,1);e.setAttribute("lineDistance",aY.call(o,r.lineDistances))}r.boundingSphere!==null&&(e.boundingSphere=r.boundingSphere.clone()),r.boundingBox!==null&&(e.boundingBox=r.boundingBox.clone())}else t.isMesh&&(e=r.toBufferGeometry());return e}};kl.prototype.isGeometry=!0;var H1=class{constructor(){this.vertices=[],this.normals=[],this.colors=[],this.uvs=[],this.uvs2=[],this.groups=[],this.morphTargets={},this.skinWeights=[],this.skinIndices=[],this.boundingBox=null,this.boundingSphere=null,this.verticesNeedUpdate=!1,this.normalsNeedUpdate=!1,this.colorsNeedUpdate=!1,this.uvsNeedUpdate=!1,this.groupsNeedUpdate=!1}computeGroups(t){let e=[],r,i,s,o=t.faces;for(i=0;i0,o=i[1]&&i[1].length>0,a=t.morphTargets,l=a.length,c;if(l>0){c=[];for(let y=0;y0){d=[];for(let y=0;y0&&e.length===0&&console.error("THREE.DirectGeometry: Faceless geometries are not supported.");for(let y=0;y0;)this._smooth(t);return t.computeFaceNormals(),t.computeVertexNormals(),t}_smooth(t){let e=new E,r,i,s,o,a,l=t.vertices,c=t.faces,u=t.faceVertexUvs[0],h=u!==void 0&&u.length>0,d=[],f=new Map;uY(l,c,d,f);let p=[],m,g,y,v,x,S,w;for(let ie of Array.from(f.keys())){for(g=f.get(ie),y=new E,x=3/8,S=1/8,w=g.faces.length,w!=2&&(x=.5,S=0,w!=1),y.addVectors(g.a,g.b).multiplyScalar(x),e.set(0,0,0),o=0;o3&&(A=3/(8*r)),T=1-r*Number(A),b=A,r<=2&&(r==2?(T=3/4,b=1/8):r==1||r==0),I=P.clone().multiplyScalar(T),e.set(0,0,0),o=0;o0?(a===void 0||o?.subdivisions!==i)&&(a===void 0&&(a=s),s=new F0(i).modify(a).toBufferGeometry()):(a!==void 0&&(s=a),a=void 0,s.getAttribute("normal")===void 0&&s.computeVertexNormals())}catch{a!==void 0&&(s=a),a=void 0,s.getAttribute("normal")===void 0&&s.computeVertexNormals()}return a!==void 0&&Object.assign(s,{originalGeometry:a}),delete n.geometry,Object.assign(s,{userData:{...n,type:"NonParametricGeometry"}})}static loadFromUrl(n,t,e){new Ju(e).load(n,i=>{let s=this.normalizeInputs({geometry:i});i.boundingBox.getSize(Pi);let o=100/Pi.x;Object.assign(s.parameters,{width:100,height:Pi.y*o,depth:Pi.z*o}),t(this.build(s))})}};var V0=class{static create(n){return this.build(this.normalizeInputs(n))}static normalizeInputs(n,t){let e=Object.assign({},t?.parameters??{width:100,depth:0,spikes:5,cornerRadius:0,extrudeBevelSize:0,extrudeBevelSegments:3},n.parameters);return{shape:n.shape&&n.shape instanceof Xt?n.shape:new Xt,parameters:Object.assign(e,{width:Math.abs(e.width),height:Math.abs(e.height??e.width),depth:Math.abs(e.depth??0)})}}static build(n){let{width:t,height:e,spikes:r,cornerRadius:i,depth:s,extrudeBevelSize:o,extrudeBevelSegments:a}=n.parameters,l=n.shape,c=t*.5,u=e*.5,h=0,d=0,f=2*Math.PI/r;for(let m=0;m0){{let Ve=Q.clone().add(G).multiplyScalar(.5),Oe=S.clone().sub(Ve).normalize(),F=x.clone().sub(Ve).normalize().add(Oe).normalize().multiplyScalar(-1),N=$.clone().sub(te);H(Ve,N,F,T.angle())}let ze,Ue;{let Ve=new E;mm(C,xe,Ve);let Oe=$.clone().add(Z).multiplyScalar(.5);Oe=hY(Oe,G,S);let Ye=$.clone().sub(Z);[ze,Ue]=H(Oe,Ye,Ve,_,Z.y)}{let Ve=ze,Oe=Ve.clone().setY(0).normalize(),Ye=new E(0,-1,0),F=Oe.clone().cross(Ye);W(Ve,Oe,Ye,F)}V.concat(Ue);{let Ve=T.angle(),Oe=Math.PI-Ve,Ye=S.clone();Ye.y-=o/Math.sin(Ve-Math.PI/2);let F=new E,N=[];for(let ae=0;aee&&A>r?Math.min(S*e/w,S*r/A):w>e?S*e/w:A>r?S*r/A:S}let f=[];f[0]=i[0]===0?0:d(i[0],i[0]+i[3],i[0]+i[1]),f[1]=i[1]===0?0:d(i[1],i[1]+i[2],i[1]+i[0]),f[2]=i[2]===0?0:d(i[2],i[2]+i[1],i[2]+i[3]),f[3]=i[3]===0?0:d(i[3],i[3]+i[0],i[3]+i[2]);let p=u.x,m=h.x,g=h.y,y=u.y;t.addPoint(t.createPoint(p,g)),t.addPoint(t.createPoint(m,g)),t.addPoint(t.createPoint(m,y)),t.addPoint(t.createPoint(p,y)),t.isClosed=!0;let v=!0;for(let S=0,w=t.points.length;S0&&f[S]!==f[S-1]&&(v=!1);v&&(t.roundness=f[0]),t.useCubicForRoundedCorners=s!==1,t.update();let x=Rn.create({shape:t,parameters:{depth:o,extrudeBevelSize:a,extrudeBevelSegments:l}});return Object.assign(x,{userData:{...n,type:"RectangleGeometry"}})}};var ZO=class{static create(n){return this.build(this.normalizeInputs(n))}static normalizeInputs(n,t){let e=Object.assign({},t?.parameters??{width:100,widthSegments:64,heightSegments:64,phiStart:0,phiLength:2*Math.PI,thetaStart:0,thetaLength:180},n.parameters);return e.thetaLength=we.clamp(e.thetaLength,0,180),{parameters:Object.assign(e,{width:Math.abs(e.width),height:Math.abs(e.height??e.width),depth:Math.abs(e.depth??e.width)})}}static build(n){let{width:t=100,height:e=t,depth:r=t,widthSegments:i=64,heightSegments:s=64,phiStart:o,phiLength:a,thetaStart:l,thetaLength:c}=n.parameters,u;return c===0?(u=new _e,u.setAttribute("position",new Te([],3))):u=new Bs(.5*t,i,s,o,a,l,c*we.DEG2RAD),u.scale(1,e/t,r/t),Object.assign(u,{userData:{...n,type:"SphereGeometry"}})}};var JO=class{static create(n){return this.build(this.normalizeInputs(n))}static normalizeInputs(n,t){let e=Object.assign({},t?.parameters??{width:100,depth:0,widthSegments:8,heightSegments:8},n.parameters);return{parameters:Object.assign(e,{width:Math.abs(e.width),height:Math.abs(e.height??e.width),depth:0})}}static build(n){let{width:t=100,height:e=t,widthSegments:r=8,heightSegments:i=8}=n.parameters,s=new Li(t,e,r,i);return s.scale(1,1,1),Object.assign(s,{userData:{...n,type:"PlaneGeometry"}})}};var $O=class{static create(n){return this.build(this.normalizeInputs(n))}static normalizeInputs(n,t){let e=Object.assign({},t?.parameters??{width:100,angle:90,cornerRadius:24,cornerSegments:8},n.parameters);return{parameters:Object.assign(e,{width:Math.abs(e.width),height:Math.abs(e.height??e.width),depth:Math.abs(e.depth??e.width)})}}static build(n){let{width:t,height:e,depth:r,angle:i,cornerRadius:s,cornerSegments:o}=n.parameters,a=new K1(t,e,r,i,s,o);return Object.assign(a,{userData:{...n,type:"BackdropGeometry"}})}},K1=class extends _e{constructor(t=1,e=1,r=1,i=90,s=10,o=24){super(),this.type="BackdropGeometry";let a=[],l=[],c=[],u=.001;s==0&&(o=1),o=Math.max(1,Math.floor(o)),s=Math.min(s,100),i=Math.min(180-u,i),i*=Math.PI/180;let h=[],d=Math.PI/2,f=(ie=0,re=0,J=0)=>new E(ie,re,J),p=f(),m=f(),[g,y,v]=[e/2,t/2,r/2],x=-y,S=+y,[w,A,T]=[f(x,-g,+v),f(x,-g,-v),f(x,+g,-v)],b=(ie,re=!1)=>Math.sin(ie-Math.PI/(1+ +re)),M=(ie,re=!1)=>Math.cos(ie-Math.PI/(1+ +re));T.y=Math.sin(i)*e-g;let C=Math.cos(i)*e-v,P=w.z-u;i<=d?(T.z=Math.min(C,P),T.z==P&&(T.y-=(C-P)/Math.tan(d-i))):A.z=Math.min(A.z-C-v,w.z-u),p.subVectors(w,A),m.subVectors(T,A);let I=Math.min(p.length(),m.length())*s/100,_=I*Math.tan(i/2),D=I/Math.cos(i/2),L=p.clone().normalize().add(m.normalize()).setLength(D).add(A);p.set(0,b(i,!0),M(i,!0)),h.push([T,p.clone()]);let j=(Math.PI-i)/o;for(let ie=0;ie<=o;ie++){let re=d+i+ie*j;p.set(0,Math.sin(re)*_,Math.cos(re)*_),p.add(L),m.set(0,b(re),M(re)),h.push([p.clone(),m.clone()])}h.push([w,f(0,1,0)]);let V=Math.sin(j/2)*_*2,H=h.length-1,W=h[0][0].distanceTo(h[1][0]),q=h[H-1][0].distanceTo(h[H][0]),Q=W+V*o+q;h[0].push(1);for(let ie=0;ie<=o;ie++)h[ie+1].push(1-(W+ie*V)/Q);h[H].push(0);let[G,Z,te]=h[0],$,Y,oe;for(let ie=1;ie>16&255,g:n>>8&255,b:n&255}}function yY(n,t,e){return(n<<16)+(t<<8)+e}function vY(n,t,e){return n=Math.round(n),t=Math.round(t),e=Math.round(e),"#"+[n,t,e].map(r=>r.toString(16).padStart(2,"0")).join("").toUpperCase()}function xY(n){let t=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;n=n.replace(t,(r,i,s,o)=>String(i+i+s+s+o+o));let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(n);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:null}var sR={parseRgba:fY,hsvToRgb:pY,rgbToHsv:mY,hexToRgb:gY,rgbToHex:yY,rgbToHexString:vY,hexStringToRgb:xY};var Q1=class{add(t,e,r){if(typeof arguments[0]!="string")for(let i in arguments[0])this.add(i,arguments[0][i],arguments[1]);else(Array.isArray(t)?t:[t]).forEach(function(i){this[i]=this[i]||[],e&&this[i][r?"unshift":"push"](e)},this)}run(t,e){this[t]=this[t]||[],this[t].forEach(function(r){r.call(e&&e.context?e.context:e,e)})}},Z1=class{constructor(t){this.jsep=t,this.registered={}}register(...t){t.forEach(e=>{if(typeof e!="object"||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)})}},fe=class{static get version(){return"1.3.8"}static toString(){return"JavaScript Expression Parser (JSEP) v"+fe.version}static addUnaryOp(t){return fe.max_unop_len=Math.max(t.length,fe.max_unop_len),fe.unary_ops[t]=1,fe}static addBinaryOp(t,e,r){return fe.max_binop_len=Math.max(t.length,fe.max_binop_len),fe.binary_ops[t]=e,r?fe.right_associative.add(t):fe.right_associative.delete(t),fe}static addIdentifierChar(t){return fe.additional_identifier_chars.add(t),fe}static addLiteral(t,e){return fe.literals[t]=e,fe}static removeUnaryOp(t){return delete fe.unary_ops[t],t.length===fe.max_unop_len&&(fe.max_unop_len=fe.getMaxKeyLen(fe.unary_ops)),fe}static removeAllUnaryOps(){return fe.unary_ops={},fe.max_unop_len=0,fe}static removeIdentifierChar(t){return fe.additional_identifier_chars.delete(t),fe}static removeBinaryOp(t){return delete fe.binary_ops[t],t.length===fe.max_binop_len&&(fe.max_binop_len=fe.getMaxKeyLen(fe.binary_ops)),fe.right_associative.delete(t),fe}static removeAllBinaryOps(){return fe.binary_ops={},fe.max_binop_len=0,fe}static removeLiteral(t){return delete fe.literals[t],fe}static removeAllLiterals(){return fe.literals={},fe}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(t){this.expr=t,this.index=0}static parse(t){return new fe(t).parse()}static getMaxKeyLen(t){return Math.max(0,...Object.keys(t).map(e=>e.length))}static isDecimalDigit(t){return t>=48&&t<=57}static binaryPrecedence(t){return fe.binary_ops[t]||0}static isIdentifierStart(t){return t>=65&&t<=90||t>=97&&t<=122||t>=128&&!fe.binary_ops[String.fromCharCode(t)]||fe.additional_identifier_chars.has(String.fromCharCode(t))}static isIdentifierPart(t){return fe.isIdentifierStart(t)||fe.isDecimalDigit(t)}throwError(t){let e=new Error(t+" at character "+this.index);throw e.index=this.index,e.description=t,e}runHook(t,e){if(fe.hooks[t]){let r={context:this,node:e};return fe.hooks.run(t,r),r.node}return e}searchHook(t){if(fe.hooks[t]){let e={context:this};return fe.hooks[t].find(function(r){return r.call(e.context,e),e.node}),e.node}}gobbleSpaces(){let t=this.code;for(;t===fe.SPACE_CODE||t===fe.TAB_CODE||t===fe.LF_CODE||t===fe.CR_CODE;)t=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");let t=this.gobbleExpressions(),e=t.length===1?t[0]:{type:fe.COMPOUND,body:t};return this.runHook("after-all",e)}gobbleExpressions(t){let e=[],r,i;for(;this.index0;){if(fe.binary_ops.hasOwnProperty(t)&&(!fe.isIdentifierStart(this.code)||this.index+t.lengths.right_a&&h.right_a?r>h.prec:r<=h.prec;for(;i.length>2&&u(i[i.length-2]);)a=i.pop(),e=i.pop().value,o=i.pop(),t={type:fe.BINARY_EXP,operator:e,left:o,right:a},i.push(t);t=this.gobbleToken(),t||this.throwError("Expected expression after "+c),i.push(s,t)}for(l=i.length-1,t=i[l];l>1;)t={type:fe.BINARY_EXP,operator:i[l-1].value,left:i[l-2],right:t},l-=2;return t}gobbleToken(){let t,e,r,i;if(this.gobbleSpaces(),i=this.searchHook("gobble-token"),i)return this.runHook("after-token",i);if(t=this.code,fe.isDecimalDigit(t)||t===fe.PERIOD_CODE)return this.gobbleNumericLiteral();if(t===fe.SQUOTE_CODE||t===fe.DQUOTE_CODE)i=this.gobbleStringLiteral();else if(t===fe.OBRACK_CODE)i=this.gobbleArray();else{for(e=this.expr.substr(this.index,fe.max_unop_len),r=e.length;r>0;){if(fe.unary_ops.hasOwnProperty(e)&&(!fe.isIdentifierStart(this.code)||this.index+e.length=e.length&&this.throwError("Unexpected token "+String.fromCharCode(t));break}else if(s===fe.COMMA_CODE){if(this.index++,i++,i!==e.length){if(t===fe.CPAREN_CODE)this.throwError("Unexpected token ,");else if(t===fe.CBRACK_CODE)for(let o=e.length;o":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10},right_associative:new Set,additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"});fe.max_unop_len=fe.getMaxKeyLen(fe.unary_ops);fe.max_binop_len=fe.getMaxKeyLen(fe.binary_ops);var jc=n=>new fe(n).parse(),SY=Object.getOwnPropertyNames(fe);SY.forEach(n=>{jc[n]===void 0&&n!=="prototype"&&(jc[n]=fe[n])});jc.Jsep=fe;var wY="ConditionalExpression",AY={name:"ternary",init(n){n.hooks.add("after-expression",function(e){if(e.node&&this.code===n.QUMARK_CODE){this.index++;let r=e.node,i=this.gobbleExpression();if(i||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===n.COLON_CODE){this.index++;let s=this.gobbleExpression();if(s||this.throwError("Expected expression"),e.node={type:wY,test:r,consequent:i,alternate:s},r.operator&&n.binary_ops[r.operator]<=.9){let o=r;for(;o.right.operator&&n.binary_ops[o.right.operator]<=.9;)o=o.right;e.node.test=o.right,o.right=e.node,e.node=r}}else this.throwError("Expected :")}})}};jc.plugins.register(AY);function Ia(n){return{all:n=n||new Map,on:function(t,e){var r=n.get(t);r?r.push(e):n.set(t,[e])},off:function(t,e){var r=n.get(t);r&&(e?r.splice(r.indexOf(e)>>>0,1):n.set(t,[]))},emit:function(t,e){var r=n.get(t);r&&r.slice().map(function(i){i(e)}),(r=n.get("*"))&&r.slice().map(function(i){i(t,e)})}}}var Dd=class{constructor(t,e,r){this.id=t;this.userAPI=e;this.result=void 0;this.error="null";this.isPrefetched=!1;this.isLoading=!1;this.isLoaded=!1;this.prefetchPromise=new Promise(t=>t());this.emitter=Ia();this._innerCallUserAPI=async t=>{this.emitter.emit("start",{userAPIId:this.id}),this.isLoading=!0,this.isLoading=!1;try{this.result=await PY(this.userAPI,t),this.error="null",this.emitter.emit("success",{userAPIId:this.id})}catch(e){let r=e.message?.split("_:_")?.[0]?.replace("status:","")??"null";this.error=r,this.result=null,this.emitter.emit("error",{userAPIId:this.id})}this.isLoading=!1,this.isPrefetched=!0,this.isLoaded=!0};e?.integration?.type==="OpenAI"?this.result={content:""}:e.method==="GET"&&e.url!==""&&(this.prefetchPromise=this.prefetch(r)),this._debouncedCallUserAPI=this._innerCallUserAPI,this._updateDebouncedCallUserAPI(),this._debouncedPrefetch=vo(this.prefetch,1e3,{trailing:!0})}_updateDebouncedCallUserAPI(){this._debouncedCallUserAPI=this.userAPI.debounce!==void 0&&this.userAPI.debounce>0?vo(this._innerCallUserAPI,this.userAPI.debounce,{leading:!0,trailing:!0}):this._innerCallUserAPI}async prefetch(t){await this.callUserAPI(t)}async callUserAPI(t){await this._debouncedCallUserAPI(t)}update(t,e,r=!0){this.userAPI=t,this._updateDebouncedCallUserAPI(),this.userAPI.url!==""&&this.userAPI.method==="GET"&&r&&this._debouncedPrefetch(e)}retrieveValue(t){if(this.result)try{return Sr.zoom(this.result,t)}catch(e){console.error(e)}}retrieveZoomedKeyValues(t){if(this.result){let e=t&&t.length?Sr.zoom(this.result,t):this.result;if(CY(e))return Object.entries(e);if(MY(e))return e.map((r,i)=>[i.toString(),r]);throw TY(e)?new Error("This path points to a value, use retrieveValue() instead. "+t?.join(".")):new Error("Path error"+t?.join("."))}}dispose(){}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}get autostart(){return this.userAPI.autoStart}};function EY(n){let t=new Headers;return n.headers.forEach(e=>{e.data.key!==""&&t.append(e.data.key,e.data.value)}),t}function TY(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null}function MY(n){return Array.isArray(n)}function CY(n){return typeof n=="object"&&n!==null}async function PY(n,t,e=new AbortController){let r,i=n.url,s=n.proxy?.enabled??!1;if(s)i=`${!1&&window.location.search.includes("api-dev")?"https://api-dev.spline.design/":"https://apis.spline.design/"}file/${n.proxy.fileId}/external-api/request?uuidexternalapi=${n.proxy.proxyId}`;else if(n.integration?.type==="OpenAI"){let a=U0(n.integration.prompt===""?[]:JSON.parse(n.integration.prompt),t),l=n.integration.behavior===""?[]:U0(JSON.parse(n.integration.behavior),t);r=`{ "model": "${n.integration.model}", "messages": [${n.integration.useBehavior?` { "role": "system", "content": "${l}" },`:""} { "role": "user", "content": "${a}" } ] }`}else n.method==="POST"&&n.body&&(r=U0(JSON.parse(n.body),t));let o=await fetch(i,{method:s?"GET":n.method,headers:s?void 0:EY(n),signal:e.signal,body:r});if(!o.ok)throw new Error("status:"+o.status+"_:_"+o.statusText);if(n.integration?.type==="OpenAI"){let a=await o.json();return s&&(a=a.response),{content:a.choices[0].message.content}}else{let a=await o.json();return s&&(a=a.response),a}}var oR=(n,t)=>{if(typeof n=="string"){let e=t.getVariable(n);if(e)return oR(e,t)}return Br.isBoolean(n)?Br.getDisplayedValue(n).toLowerCase():Br.getDisplayedValue(n)},U0=(n,t)=>n.map((e,r)=>{if("text"in e)return e.text;if("type"in e){if(e.type==="paragraph")return(r>0?` `:"")+U0(e.children,t);if(e.type==="variable"){let i=t.getVariable(e.variableId);if(i!==void 0)return oR(i,t)}}return""}).join("");var _Y=["+","-","*","/","(",")","==","!=",">","<",">=","<=","and","or","!","%","^",","],IY=["0","1","2","3","4","5","6","7","8","9","."],DY=["sin","cos","tan","asin","acos","atan","atan2","sqrt","abs","log","exp","floor","ceil","round","min","max","random"];function OY(n){return typeof n!="string"?!1:!isNaN(n)&&!isNaN(parseFloat(n))}jc.addBinaryOp("^",11,!0);function z0(n,t,e="number"){let r="";for(let o=0;o{let d=h.events?.find(f=>f.id===a.objId);d&&(c=d)}),c!==void 0&&c.data.type==="AIAssistantListener"){let u=l?.computeAnalysisForListenerEvent(c.data);if(u!==void 0){r+=u;continue}}}r+=l?.voice??0;continue}if("id"in a){let l=n[o-1];if(o>0&&"id"in l){console.error("Two variables in a row",n);return}let c=t.getVariable(a.id),u=Br.getDisplayedValue(c);e==="number"&&Br.isTextValue(c)&&Array.isArray(c.textValue)&&c.textValue.length===1?u=parseFloat(u).toString():e==="boolean"&&Br.isBoolean(c)?u=c?"true":"false":e==="boolean"&&Br.isTextValue(c)&&!Array.isArray(c.textValue)&&(u='"'+u+'"'),r+=u;continue}else if(e==="string"){a.name!=='"'&&(a.name!=="+"||a.escaped)&&(r+=a.name),a.name==="+"&&!a.escaped&&r[r.length-1]==="\\"&&(r=r.slice(0,-1)+a.name);continue}if(a.name==="and"){r+="&&";continue}if(a.name==="or"){r+="||";continue}if(a.name==="True"){r+="true";continue}if(a.name==="False"){r+="false";continue}if(e==="boolean"&&!OY(a.name)&&!IY.includes(a.name)&&!_Y.includes(a.name)&&!DY.includes(a.name.replace(/\($/g,""))){r+='"'+a.name+'"';continue}r+=a.name}if(e==="string")return r;if(n.length===0){if(e==="number")return 0;if(e==="boolean")return!1}let i;try{i=jc(r)}catch(o){console.error(r,o);return}let s;try{s=Wt(i)}catch(o){console.error(r,i,o)}return s}function Wt(n){switch(n.type){case"BinaryExpression":switch(n.operator){case"==":return Number(Wt(n.left)===Wt(n.right));case"!=":return Number(Wt(n.left)!==Wt(n.right));case">":return Number(Wt(n.left)>Wt(n.right));case">=":return Number(Wt(n.left)>=Wt(n.right));case"<":return Number(Wt(n.left)=1)try{t=Wt(n.arguments[0])}catch(r){console.warn(r)}if(n.arguments.length>=2)try{e=Wt(n.arguments[1])}catch(r){console.warn(r)}return t=Math.min(e,t),e=Math.max(e,t),t+Math.random()*(e-t)}return Math[n.callee.name].apply(null,n.arguments.map(Wt))}else throw new Error("Unknown node");default:throw new Error("Unknown node type: "+n.type)}}var RY=new ue,LY=new ue;function BY(n,t,e){let r=[new E,new E,new E],i=[new E,new E,new E];return n.extractBasis(r[0],r[1],r[2]),t.extractBasis(i[0],i[1],i[2]),r.forEach((s,o)=>{let a=i[o],l=we.lerp(s.length(),a.length(),e);s.lerp(a,e).setLength(l)}),new ue().makeBasis(r[0],r[1],r[2])}var aR=class{static create(n){return this.build(this.normalizeInputs(n))}static normalizeInputs(n,t){let e=Object.assign({},t?.parameters??{width:100,height:100,depth:1,subdivisions:12,roundness:0,extrudeBevelSize:0,extrudeBevelSegments:3},n.parameters),r=Math.abs(e.width),i=Math.abs(e.height??e.width),s=Math.abs(e.depth??0),o=t?.shapeData??Cd.create({parameters:jA}).userData.shape;return{path:n.path??Wh.defaultData(),parameters:Object.assign(e,{width:r,height:i,depth:s,extrusion:{...Kv,...e.extrusion}}),shapeData:o}}static build(n){if(n.path.points.length>=2){let e=new J1(n);return Object.assign(e,{userData:{...n,type:"PathGeometry"}})}else return Object.assign(new _e,{userData:{...n,type:"PathGeometry"}})}},J1=class extends _e{constructor(e){super();this.type="PathExtrusionGeometry",this.inputs=e,this.build()}_isGeometryClosed(){return this.inputs.path.isClosed&&this.inputs.parameters.extrusion.depth===1}_isOpenEnded(){let e=this.inputs.parameters.extrusion;return!(this.inputs.path.isClosed&&e.depth===1)||!nR(e.twist,0)||e.startScale!==e.endScale}build(){let e=this._extractPathPoints();if(e.length<2)return;let r=this._computeBasisMatrices(e),{depth:i,offset:s}=this.inputs.parameters.extrusion;i=Math.max(0,Math.min(i,1)),s=Math.max(0,Math.min(s,1));let o=this.inputs.path.isClosed?e.length:e.length-1,a=Math.floor(s*o),l=this.inputs.path.isClosed?Math.ceil((i+s)*o):Math.ceil(Math.min(1,i+s)*o),c=Math.min(Math.max(2,l-a+1),o+2),u=[],h=[];for(let W=0;W{u[W]=u[W].clone().lerp(u[q],Q),h[W]=BY(h[W],h[q],Q)},f=0,p=s*o%1;(!this.inputs.path.isClosed||i<=1)&&(p||s===0)&&(f=p,d(0,1,f));let m=0,g=(s+i)*o%1;if((this.inputs.path.isClosed&&i<=1||!this.inputs.path.isClosed&&s+i<1)&&g&&(m=g,d(u.length-1,u.length-2,1-m)),i===0){let W=u.length-1;u[W].copy(u[0]),h[W].copy(h[0])}this._applyPathModifiers(h,f,m);let{bevel:y,bevelSides:v}=this.inputs.parameters.extrusion,x=y>0?this.inputs.parameters.extrusion.capType:"flat",S=5;this.inputs.parameters.extrusion.shape.type==="Custom"&&(S=this.inputs.parameters.extrusion.shape.shapeQuality==="low"?5:12);let{regions:w,infos:A,vertices:T}=this._computeShapePoints(S),b=0,M;x==="round"&&(M=new Vl(this.inputs.shapeData,2*y,y,S,v,void 0,!0),b=M.getAttribute("position").count);let C=0,P=0;A.sort((W,q)=>W.start-q.start),A.forEach(W=>{W.verticesStart=C,W.verticesCount=W.continuous.reduce((q,Q,G)=>q+(G===0||!Q?2:1),0),P+=W.verticesCount,C=P});let I=P*c,_,D=0;if(this._isOpenEnded()&&x==="flat"){try{_=qs({windingRule:zt.ODD,elementType:jr.POLYGONS,polySize:3,vertexSize:2,strict:!0,contours:w})}catch{_=z1}D=_.vertexCount}let L=I+2*D+b*2,j=I+2*D,V={positions:new Float32Array(L*3),normals:new Float32Array(L*3),uvs:new Float32Array(L*2)},H=[];if(A.forEach(W=>{this._extrudeRegion(W,T,h,u,V,H,this._isGeometryClosed()&&!this._isOpenEnded())}),_&&(this._closeEnd(_,I,H,V,h[0],u[0],!1),this._closeEnd(_,I+D,H,V,h[h.length-1],u[u.length-1],!0)),M){V.positions.set(M.getAttribute("position").array,j*3),V.normals.set(M.getAttribute("normal").array,j*3),V.uvs.set(M.getAttribute("uv").array,j*2);for(let G=j;GG+j)),j+=b,V.positions.set(M.getAttribute("position").array,j*3),V.normals.set(M.getAttribute("normal").array,j*3),V.uvs.set(M.getAttribute("uv").array,j*2);let q=H.length;H.push(...M.getIndex().array.map(G=>G+j)),this.setAttribute("position",new Xe(V.positions,3)),this.setAttribute("normal",new Xe(V.normals,3)),this.setAttribute("uv",new Xe(V.uvs,2)),this.setIndex(H);let Q=RY;Q.copy(h[h.length-1]).setPosition(u[u.length-1]),this.applyMatrix4OnRange(Q,j,L),Q.copy(h[0]).setPosition(u[0]).multiply(LY.makeScale(1,1,-1)),this.applyMatrix4OnRange(Q,j-b,j),this.reverseIndicesOnRange(W,q)}else this.setAttribute("position",new Xe(V.positions,3)),this.setAttribute("normal",new Xe(V.normals,3)),this.setAttribute("uv",new Xe(V.uvs,2)),this.setIndex(H)}_extractPathPoints(){let r=M0(this.inputs.path).getPoints(this.inputs.path.subdivisions);if(r.length<2)return[];let i=[r[0]];return r.forEach(o=>{i[i.length-1].distanceToSquared(o)>.001&&i.push(o)}),this.inputs.path.isClosed&&i[i.length-1].distanceTo(i[0])<.001&&i.pop(),i}_computeBasisMatrices(e){let r=[],i=e.length,s=this.inputs.path.isClosed,o=new E,a=new E,l=new E,c=new E,u=new E(0,1,0);for(let g=0;g0&&(p*=-1);for(let g=1;g{let p=f===0?0:f===s-1?1:(f-r)/(s-(i===0?0:1)-(r+(1-i)));u.makeRotationZ(we.lerp(o,o+a,p)*we.DEG2RAD);let m=we.lerp(l,c,p);h.makeScale(m,m,m),d.multiply(u).multiply(h)}),e}_computeShapePoints(e=12,r=zt.ODD){let i=this.inputs.shapeData,s=i.extractShapePointsToFlatArray([],e),o=i.shapeHoles.map(m=>{let g=m.extractShapePointsToFlatArray([],e),y=[];for(let v=g.length-1;v>=1;v-=2){let x=g[v-1],S=g[v-0];y.push(x,S)}return y}),a;try{a=qs({windingRule:r,elementType:jr.BOUNDARY_CONTOURS,vertexSize:2,strict:!0,contours:[s]})}catch{a=dm}let l;try{l=qs({windingRule:zt.ODD,elementType:jr.BOUNDARY_CONTOURS,vertexSize:2,strict:!0,contours:[...o]})}catch{l=U1}if(!a)throw new Error("error generating geometry");let c=a.elementCount;if(l){a.elementCount+=l.elementCount;for(let m=0;mh&&(h=v),xf&&(f=x)}let p=[];for(let m=a.elementCount-1;m>=0;m--){let g=m>=c,y=m*2,v=a.elements[y+0],x=a.elements[y+1],S=v+x,w={start:v,count:x,normals:[],isHole:g,continuous:[],verticesStart:0,verticesCount:0};p.push(w);let A=v,T=S-1,b=v+1,M=i.roundedCurves.length;do{let C=A-v,P=a.vertices[T*2+0],I=a.vertices[T*2+1],_=a.vertices[A*2+0],D=a.vertices[A*2+1],L=a.vertices[b*2+0],j=a.vertices[b*2+1],V=_-P,H=D-I,W=Math.sqrt(V*V+H*H);V/=W,H/=W;let q=_-L,Q=D-j,G=Math.sqrt(q*q+Q*Q);q/=G,Q/=G,w.normals[C*2+0]=-Q,w.normals[C*2+1]=q;let Z=a.vertexIndices[A];if(Array.isArray(Z))w.continuous[C]=!1;else{let[te,$]=i.getCurveIndexFromVertexId(Z-1,!0);if($>0&&$<1)w.continuous[C]=!0;else{let Y=$===1?te+1:te-1;Y=(Y+M)%M;let oe=$===1?0:1,ie=i.roundedCurves[te].getTangent($),re=i.roundedCurves[Y].getTangent(oe);w.continuous[C]=ie.dot(re)>.95}}g&&(w.normals[C*2+0]*=-1,w.normals[C*2+1]*=-1),[T,A,b]=[A,b,b+1],b>=S&&(b-=x)}while(b!==v+1)}return{regions:[s,...o],infos:p,vertices:a.vertices}}_insertVertex(e,r,i,s,o){let a=r*2,l=r*3;e.positions[l+0]=i.x,e.positions[l+1]=i.y,e.positions[l+2]=i.z,e.normals[l+0]=s.x,e.normals[l+1]=s.y,e.normals[l+2]=s.z,e.uvs[a+0]=o.x,e.uvs[a+1]=o.y}_extrudeRegion(e,r,i,s,o,a,l){let c=new E,u=new E,h=new E,d=new E,f=new k;i.forEach((m,g)=>{let y=s[g],v=e.verticesStart*i.length+e.verticesCount*g;for(let x=0;x{this.update(e),r?.requestRender()})}async updateFont(e,r){let i=r.getFont(e);i&&(this.font=i,await i.loadingPromise)}update(e){let r=this.font;if(this.userData={parameters:e,type:"TextGeometry"},!r?.isLoaded){console.warn("Cannot update text because its font is not loaded");return}let{width:i,height:s,depth:o,extrudeBevelSize:a,extrudeBevelSegments:l,text:c,textTransform:u}=e,h=Br.getDisplayedValue(c),d=u===2?h.toUpperCase():u===3?h.toLowerCase():h,f=UY(e,r,d),{shapes:p,charWidths:m,charCoords:g}=r.generateShapes(f,e),y=(typeof i=="number"?i:1)*.5,v=(typeof s=="number"?s:1)*.5,x=p.map(A=>new Xt().fromShape(A,!0));this.vectorShapes=x;let S=x.map(A=>Rn.create({shape:A,parameters:{depth:o,extrudeBevelSegments:l,extrudeBevelSize:a,windingRule:o<=0?zt.NONZERO:zt.ODD,subdivisions:this.isLowResolution&&o>0?kY:VY}})),w=S.length?Gs(S):lR();w.translate(-y,v,0),this.dispose(),this.wrappedText=f,this.charCoords=g,this.charWidths=m,this.deleteAttribute("extrudeNormal"),Object.entries(w.attributes).forEach(([A,T])=>{this.setAttribute(A,T)}),this.setIndex(w.index),this.computeBoundingSphere()}clone(){let e=qi(new _e,Hc.prototype);return e.copy(this),console.log("CloneGeometry",this,e),e}copy(e){return Object.entries(e.attributes).forEach(([r,i])=>{this.setAttribute(r,i)}),this.setIndex(e.index),this.userData={parameters:{...e.userData.parameters},type:"TextGeometry"},this}async setText(e){this.font&&await this.font.loadingPromise,await this.update({...this.userData.parameters,text:{textValue:e}})}get text(){return this.userData.parameters.text??""}};function UY(n,t,e){let r=[""],i="";for(let s of e)i+=s,s===" "||s===` `?(r[r.length-1]+=i,i="",s===` `&&r.push("")):t.getTextWidth(r[r.length-1]+i,n)>n.width&&(r[r.length-1].length&&r.push(""),t.getTextWidth(r[r.length-1]+i,n)>n.width&&(i.length===1?(r[r.length-1]+=i,i=""):(r[r.length-1]+=i.slice(0,-1),i=i[i.length-1],r.push(""))));return r[r.length-1]+=i,r}var uR,j0=new Promise(n=>{uR=n}),cR=!1;var G0;function hR(){if(cR)return;if(G0)return G0;async function n(){let e="https://unpkg.com/@splinetool/modelling-wasm@1.9.35/build",i=(() => { var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; return ( function(moduleArg = {}) { var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();FS.ignorePermissions=false;TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}var wasmBinaryFile;wasmBinaryFile="process.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(binaryFile){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{if(!response["ok"]){throw"failed to load wasm binary file at '"+binaryFile+"'"}return response["arrayBuffer"]()}).catch(()=>getBinarySync(binaryFile))}}return Promise.resolve().then(()=>getBinarySync(binaryFile))}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(binary=>WebAssembly.instantiate(binary,imports)).then(instance=>instance).then(receiver,reason=>{err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})})}return instantiateArrayBuffer(binaryFile,imports,callback)}function createWasm(){var info={"a":wasmImports};function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["K"];updateMemoryViews();wasmTable=wasmExports["O"];addOnInit(wasmExports["L"]);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);readyPromiseReject(e)}}instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult).catch(readyPromiseReject);return{}}var tempDouble;var tempI64;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24;this.set_type=function(type){HEAPU32[this.ptr+4>>2]=type};this.get_type=function(){return HEAPU32[this.ptr+4>>2]};this.set_destructor=function(destructor){HEAPU32[this.ptr+8>>2]=destructor};this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+12>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+12>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+13>>0]!=0};this.init=function(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)};this.set_adjusted_ptr=function(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr};this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_type());if(isPointer){return HEAPU32[this.excPtr>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.excPtr}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var tupleRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAP32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError;var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_array=rawTupleType=>{var reg=tupleRegistrations[rawTupleType];delete tupleRegistrations[rawTupleType];var elements=reg.elements;var elementsLength=elements.length;var elementTypes=elements.map(elt=>elt.getterReturnType).concat(elements.map(elt=>elt.setterArgumentType));var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;whenDependentTypesAreResolved([rawTupleType],elementTypes,function(elementTypes){elements.forEach((elt,i)=>{var getterReturnType=elementTypes[i];var getter=elt.getter;var getterContext=elt.getterContext;var setterArgumentType=elementTypes[i+elementsLength];var setter=elt.setter;var setterContext=elt.setterContext;elt.read=ptr=>getterReturnType["fromWireType"](getter(getterContext,ptr));elt.write=(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}});return[{name:reg.name,"fromWireType":ptr=>{var rv=new Array(elementsLength);for(var i=0;i{if(elementsLength!==o.length){throw new TypeError(`Incorrect number of tuple elements for ${reg.name}: expected=${elementsLength}, actual=${o.length}`)}var ptr=rawConstructor();for(var i=0;i{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};fieldRecords.forEach((field,i)=>{var fieldName=field.fieldName;var getterReturnType=fieldTypes[i];var getter=field.getter;var getterContext=field.getterContext;var setterArgumentType=fieldTypes[i+fieldRecords.length];var setter=field.setter;var setterContext=field.setterContext;fields[fieldName]={read:ptr=>getterReturnType["fromWireType"](getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}}});return[{name:reg.name,"fromWireType":ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},"toWireType":(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:rawDestructor}]})};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{};var embind_init_charCodes=()=>{var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes};var embind_charCodes;var readLatin1String=ptr=>{var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret};var BindingError;var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){if(!("argPackAdvance"in registeredInstance)){throw new TypeError("registerType registeredInstance requires argPackAdvance")}return sharedRegisterType(rawType,registeredInstance,options)}var GenericWireTypeSize=8;var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(wt){return!!wt},"toWireType":function(destructors,o){return o?trueValue:falseValue},"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":function(pointer){return this["fromWireType"](HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredPointers={};var getInheritedInstanceCount=()=>Object.keys(registeredInstances).length;var getLiveInheritedInstances=()=>{var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var setDelayFunction=fn=>{delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}};var init_embind=()=>{Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var attachFinalizer=handle=>{if("undefined"===typeof FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$:$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var init_ClassHandle=()=>{Object.assign(ClassHandle.prototype,{"isAliasOf"(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},"clone"(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},"delete"(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},"isDeleted"(){return!this.$$.ptr},"deleteLater"(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}})};function ClassHandle(){}var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function createNamedFunction(name,body){name=makeLegalFunctionName(name);return{[name]:function(){return body.apply(this,arguments)}}[name]}var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${arguments.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function readPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}},"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":readPointer,"deleteObject"(handle){if(handle!==null){handle["delete"]()}},"fromWireType":RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var dynCallLegacy=(sig,ptr,args)=>{var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)};var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var dynCall=(sig,ptr,args)=>{if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr).apply(null,args);return rtn};var getDynCaller=(sig,ptr)=>{var argCache=[];return function(){argCache.length=0;Object.assign(argCache,arguments);return dynCall(sig,ptr,argCache)}};var embind__requireFunction=(signature,rawFunction)=>{signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};var extendError=(baseErrorType,errorName)=>{var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return`${this.name}: ${this.message}`}};return errorClass};var UnboundTypeError;var getTypeName=type=>{var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=readLatin1String(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);if(upcast){upcast=embind__requireFunction(upcastSignature,upcast)}if(downcast){downcast=embind__requireFunction(downcastSignature,downcast)}rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],function(base){base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(legalFunctionName,function(){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError("Use 'new' to construct "+name)}if(undefined===registeredClass.constructor_body){throw new BindingError(name+" has no accessible constructor")}var body=registeredClass.constructor_body[arguments.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,arguments)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){if(registeredClass.baseClass.__derivedClasses===undefined){registeredClass.baseClass.__derivedClasses=[]}registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i>2])}return array};function newFunc(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError(`new_ called with constructor type ${typeof constructor} which is not a function`)}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=false;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns||isAsync?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var validateThis=(this_,classType,humanName)=>{if(!(this_ instanceof Object)){throwBindingError(`${humanName} with invalid "this": ${this_}`)}if(!(this_ instanceof classType.registeredClass.constructor)){throwBindingError(`${humanName} incompatible with "this" of type ${this_.constructor.name}`)}if(!this_.$$.ptr){throwBindingError(`cannot call emscripten binding method ${humanName} on deleted object`)}return upcastPointer(this_.$$.ptr,this_.$$.ptrType.registeredClass,classType.registeredClass)};var __embind_register_class_property=(classType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{fieldName=readLatin1String(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[classType],function(classType){classType=classType[0];var humanName=`${classType.name}.${fieldName}`;var desc={get(){throwUnboundTypeError(`Cannot access ${humanName} due to unbound types`,[getterReturnType,setterArgumentType])},enumerable:true,configurable:true};if(setter){desc.set=()=>throwUnboundTypeError(`Cannot access ${humanName} due to unbound types`,[getterReturnType,setterArgumentType])}else{desc.set=v=>throwBindingError(humanName+" is a read-only property")}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);whenDependentTypesAreResolved([],setter?[getterReturnType,setterArgumentType]:[getterReturnType],function(types){var getterReturnType=types[0];var desc={get(){var ptr=validateThis(this,classType,humanName+" getter");return getterReturnType["fromWireType"](getter(getterContext,ptr))},enumerable:true};if(setter){setter=embind__requireFunction(setterSignature,setter);var setterArgumentType=types[1];desc.set=function(v){var ptr=validateThis(this,classType,humanName+" setter");var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,v));runDestructors(destructors)}}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);return[]});return[]})};function handleAllocatorInit(){Object.assign(HandleAllocator.prototype,{get(id){return this.allocated[id]},has(id){return this.allocated[id]!==undefined},allocate(handle){var id=this.freelist.pop()||this.allocated.length;this.allocated[id]=handle;return id},free(id){this.allocated[id]=undefined;this.freelist.push(id)}})}function HandleAllocator(){this.allocated=[undefined];this.freelist=[]}var emval_handles=new HandleAllocator;var __emval_decref=handle=>{if(handle>=emval_handles.reserved&&0===--emval_handles.get(handle).refcount){emval_handles.free(handle)}};var count_emval_handles=()=>{var count=0;for(var i=emval_handles.reserved;i{emval_handles.allocated.push({value:undefined},{value:null},{value:true},{value:false});emval_handles.reserved=emval_handles.allocated.length;Module["count_emval_handles"]=count_emval_handles};var Emval={toValue:handle=>{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handles.get(handle).value},toHandle:value=>{switch(value){case undefined:return 1;case null:return 2;case true:return 3;case false:return 4;default:{return emval_handles.allocate({refcount:1,value:value})}}}};var __embind_register_emval=(rawType,name)=>{name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},"toWireType":(destructors,value)=>Emval.toHandle(value),"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:null})};var enumReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?function(pointer){return this["fromWireType"](HEAP8[pointer>>0])}:function(pointer){return this["fromWireType"](HEAPU8[pointer>>0])};case 2:return signed?function(pointer){return this["fromWireType"](HEAP16[pointer>>1])}:function(pointer){return this["fromWireType"](HEAPU16[pointer>>1])};case 4:return signed?function(pointer){return this["fromWireType"](HEAP32[pointer>>2])}:function(pointer){return this["fromWireType"](HEAPU32[pointer>>2])};default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_enum=(rawType,name,size,isSigned)=>{name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":(destructors,c)=>c.value,"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl};var __embind_register_enum_value=(rawEnumType,name,enumValue)=>{var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(`${enumType.name}_${name}`,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 8:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":value=>value,"toWireType":(destructors,value)=>value,"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer>>0]:pointer=>HEAPU8[pointer>>0];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":toWireType,"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;var UTF8ArrayToString=(heapOrArray,idx,maxBytesToRead)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var __embind_register_std_string=(rawType,name)=>{name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType"(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i{var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder)return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr));var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead)=>{var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=readLatin1String(name);var decodeString,encodeString,getHeap,lengthBytesUTF,shift;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;getHeap=()=>HEAPU16;shift=1}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;getHeap=()=>HEAPU32;shift=2}registerType(rawType,{name:name,"fromWireType":value=>{var length=HEAPU32[value>>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":GenericWireTypeSize,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_array=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{tupleRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),elements:[]}};var __embind_register_value_array_element=(rawTupleType,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{tupleRegistrations[rawTupleType].elements.push({getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})};var __embind_register_void=(rawType,name)=>{name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":()=>undefined,"toWireType":(destructors,o)=>undefined})};var __emval_incref=handle=>{if(handle>4){emval_handles.get(handle).refcount+=1}};var __emval_take_value=(type,arg)=>{type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)};var _abort=()=>{abort("")};var _emscripten_memcpy_js=(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num);var getHeapMax=()=>2147483648;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}var alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i>0]=str.charCodeAt(i)}HEAP8[buffer>>0]=0};var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:path=>{if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},join:function(){var paths=Array.prototype.slice.call(arguments);return PATH.normalize(paths.join("/"))},join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(typeof crypto=="object"&&typeof crypto["getRandomValues"]=="function"){return view=>crypto.getRandomValues(view)}else abort("initRandomDevice")};var randomFill=view=>(randomFill=initRandomFill())(view);var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}if(!MEMFS.ops_table){MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}}}var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node;parent.timestamp=node.timestamp}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){throw FS.genericErrors[44]},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length{var dep=!noRunDep?getUniqueRunDependency(`al ${url}`):"";readAsync(url,arrayBuffer=>{assert(arrayBuffer,`Loading data file "${url}" failed (no arrayBuffer).`);onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},event=>{if(onerror){onerror()}else{throw`Loading data file "${url}" failed.`}});if(dep)addRunDependency(dep)};var FS_createDataFile=(parent,name,fileData,canRead,canWrite,canOwn)=>FS.createDataFile(parent,name,fileData,canRead,canWrite,canOwn);var preloadPlugins=Module["preloadPlugins"]||[];var FS_handledByPreloadPlugin=(byteArray,fullname,finish,onerror)=>{if(typeof Browser!="undefined")Browser.init();var handled=false;preloadPlugins.forEach(plugin=>{if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);function processData(byteArray){function finish(byteArray){if(preFinish)preFinish();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}if(onload)onload();removeRunDependency(dep)}if(FS_handledByPreloadPlugin(byteArray,fullname,finish,()=>{if(onerror)onerror();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url,byteArray=>processData(byteArray),onerror)}else{processData(url)}};var FS_modeStringToFlags=str=>{var flagModes={"r":0,"r+":2,"w":512|64|1,"w+":512|64|2,"a":1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(path,opts={}){path=PATH_FS.resolve(path);if(!path)return{path:"",node:null};var defaults={follow_mount:true,recurse_count:0};opts=Object.assign(defaults,opts);if(opts.recurse_count>8){throw new FS.ErrnoError(32)}var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){if(!FS.FSStream){FS.FSStream=function(){this.shared={}};FS.FSStream.prototype={};Object.defineProperties(FS.FSStream.prototype,{object:{get(){return this.node},set(val){this.node=val}},isRead:{get(){return(this.flags&2097155)!==1}},isWrite:{get(){return(this.flags&2097155)!==0}},isAppend:{get(){return this.flags&1024}},flags:{get(){return this.shared.flags},set(val){this.shared.flags=val}},position:{get(){return this.shared.position},set(val){this.shared.position=val}}})}stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){stream.stream_ops.open(stream)}},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push.apply(check,m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type:type,opts:opts,mountpoint:mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name||name==="."||name===".."){throw new FS.ErrnoError(28)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},create(path,mode){mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode){mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var i=0;i0,ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){throw new Error(`Invalid encoding type "${opts.encoding}"`)}var ret;var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){ret=UTF8ArrayToString(buf,0)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomLeft=randomFill(randomBuffer).byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16384|511,73);node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path}};ret.parent=ret;return ret}};return node}},{},"/proc/self/fd")},createStandardStreams(){if(Module["stdin"]){FS.createDevice("/dev","stdin",Module["stdin"])}else{FS.symlink("/dev/tty","/dev/stdin")}if(Module["stdout"]){FS.createDevice("/dev","stdout",null,Module["stdout"])}else{FS.symlink("/dev/tty","/dev/stdout")}if(Module["stderr"]){FS.createDevice("/dev","stderr",null,Module["stderr"])}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},ensureErrnoError(){if(FS.ErrnoError)return;FS.ErrnoError=function ErrnoError(errno,node){this.name="ErrnoError";this.node=node;this.setErrno=function(errno){this.errno=errno};this.setErrno(errno);this.message="FS error"};FS.ErrnoError.prototype=new Error;FS.ErrnoError.prototype.constructor=FS.ErrnoError;[44].forEach(code=>{FS.genericErrors[code]=new FS.ErrnoError(code);FS.genericErrors[code].stack=""})},staticInit(){FS.ensureErrnoError();FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={"MEMFS":MEMFS}},init(input,output,error){FS.init.initialized=true;FS.ensureErrnoError();Module["stdin"]=input||Module["stdin"];Module["stdout"]=output||Module["stdout"];Module["stderr"]=error||Module["stderr"];FS.createStandardStreams()},quit(){FS.init.initialized=false;for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true};if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url:url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr:ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return PATH.join2(dir,path)},doStat(func,path,buf){try{var stat=func(path)}catch(e){if(e&&e.node&&PATH.normalize(path)!==PATH.normalize(FS.getPath(e.node))){return-54}throw e}HEAP32[buf>>2]=stat.dev;HEAP32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAP32[buf+12>>2]=stat.uid;HEAP32[buf+16>>2]=stat.gid;HEAP32[buf+20>>2]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+24>>2]=tempI64[0],HEAP32[buf+28>>2]=tempI64[1];HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();tempI64=[Math.floor(atime/1e3)>>>0,(tempDouble=Math.floor(atime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAPU32[buf+48>>2]=atime%1e3*1e3;tempI64=[Math.floor(mtime/1e3)>>>0,(tempDouble=Math.floor(mtime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>2]=tempI64[0],HEAP32[buf+60>>2]=tempI64[1];HEAPU32[buf+64>>2]=mtime%1e3*1e3;tempI64=[Math.floor(ctime/1e3)>>>0,(tempDouble=Math.floor(ctime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>2]=tempI64[0],HEAP32[buf+76>>2]=tempI64[1];HEAPU32[buf+80>>2]=ctime%1e3*1e3;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>2]=tempI64[0],HEAP32[buf+92>>2]=tempI64[1];return 0},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},varargs:undefined,get(){var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret},getp(){return SYSCALLS.get()},getStr(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream}};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(typeof offset!=="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var arraySum=(array,index)=>{var sum=0;for(var i=0;i<=index;sum+=array[i++]){}return sum};var MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31];var MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31];var addDays=(date,days)=>{var newDate=new Date(date.getTime());while(days>0){var leap=isLeapYear(newDate.getFullYear());var currentMonth=newDate.getMonth();var daysInCurrentMonth=(leap?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[currentMonth];if(days>daysInCurrentMonth-newDate.getDate()){days-=daysInCurrentMonth-newDate.getDate()+1;newDate.setDate(1);if(currentMonth<11){newDate.setMonth(currentMonth+1)}else{newDate.setMonth(0);newDate.setFullYear(newDate.getFullYear()+1)}}else{newDate.setDate(newDate.getDate()+days);return newDate}}return newDate};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var _strftime=(s,maxsize,format,tm)=>{var tm_zone=HEAPU32[tm+40>>2];var date={tm_sec:HEAP32[tm>>2],tm_min:HEAP32[tm+4>>2],tm_hour:HEAP32[tm+8>>2],tm_mday:HEAP32[tm+12>>2],tm_mon:HEAP32[tm+16>>2],tm_year:HEAP32[tm+20>>2],tm_wday:HEAP32[tm+24>>2],tm_yday:HEAP32[tm+28>>2],tm_isdst:HEAP32[tm+32>>2],tm_gmtoff:HEAP32[tm+36>>2],tm_zone:tm_zone?UTF8ToString(tm_zone):""};var pattern=UTF8ToString(format);var EXPANSION_RULES_1={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var rule in EXPANSION_RULES_1){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_1[rule])}var WEEKDAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];function leadingSomething(value,digits,character){var str=typeof value=="number"?value.toString():value||"";while(str.length0?1:0}var compare;if((compare=sgn(date1.getFullYear()-date2.getFullYear()))===0){if((compare=sgn(date1.getMonth()-date2.getMonth()))===0){compare=sgn(date1.getDate()-date2.getDate())}}return compare}function getFirstWeekStartDate(janFourth){switch(janFourth.getDay()){case 0:return new Date(janFourth.getFullYear()-1,11,29);case 1:return janFourth;case 2:return new Date(janFourth.getFullYear(),0,3);case 3:return new Date(janFourth.getFullYear(),0,2);case 4:return new Date(janFourth.getFullYear(),0,1);case 5:return new Date(janFourth.getFullYear()-1,11,31);case 6:return new Date(janFourth.getFullYear()-1,11,30)}}function getWeekBasedYear(date){var thisDate=addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);var janFourthThisYear=new Date(thisDate.getFullYear(),0,4);var janFourthNextYear=new Date(thisDate.getFullYear()+1,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);if(compareByDay(firstWeekStartThisYear,thisDate)<=0){if(compareByDay(firstWeekStartNextYear,thisDate)<=0){return thisDate.getFullYear()+1}return thisDate.getFullYear()}return thisDate.getFullYear()-1}var EXPANSION_RULES_2={"%a":date=>WEEKDAYS[date.tm_wday].substring(0,3),"%A":date=>WEEKDAYS[date.tm_wday],"%b":date=>MONTHS[date.tm_mon].substring(0,3),"%B":date=>MONTHS[date.tm_mon],"%C":date=>{var year=date.tm_year+1900;return leadingNulls(year/100|0,2)},"%d":date=>leadingNulls(date.tm_mday,2),"%e":date=>leadingSomething(date.tm_mday,2," "),"%g":date=>getWeekBasedYear(date).toString().substring(2),"%G":date=>getWeekBasedYear(date),"%H":date=>leadingNulls(date.tm_hour,2),"%I":date=>{var twelveHour=date.tm_hour;if(twelveHour==0)twelveHour=12;else if(twelveHour>12)twelveHour-=12;return leadingNulls(twelveHour,2)},"%j":date=>leadingNulls(date.tm_mday+arraySum(isLeapYear(date.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,date.tm_mon-1),3),"%m":date=>leadingNulls(date.tm_mon+1,2),"%M":date=>leadingNulls(date.tm_min,2),"%n":()=>"\n","%p":date=>{if(date.tm_hour>=0&&date.tm_hour<12){return"AM"}return"PM"},"%S":date=>leadingNulls(date.tm_sec,2),"%t":()=>"\t","%u":date=>date.tm_wday||7,"%U":date=>{var days=date.tm_yday+7-date.tm_wday;return leadingNulls(Math.floor(days/7),2)},"%V":date=>{var val=Math.floor((date.tm_yday+7-(date.tm_wday+6)%7)/7);if((date.tm_wday+371-date.tm_yday-2)%7<=2){val++}if(!val){val=52;var dec31=(date.tm_wday+7-date.tm_yday-1)%7;if(dec31==4||dec31==5&&isLeapYear(date.tm_year%400-1)){val++}}else if(val==53){var jan1=(date.tm_wday+371-date.tm_yday)%7;if(jan1!=4&&(jan1!=3||!isLeapYear(date.tm_year)))val=1}return leadingNulls(val,2)},"%w":date=>date.tm_wday,"%W":date=>{var days=date.tm_yday+7-(date.tm_wday+6)%7;return leadingNulls(Math.floor(days/7),2)},"%y":date=>(date.tm_year+1900).toString().substring(2),"%Y":date=>date.tm_year+1900,"%z":date=>{var off=date.tm_gmtoff;var ahead=off>=0;off=Math.abs(off)/60;off=off/60*100+off%60;return(ahead?"+":"-")+String("0000"+off).slice(-4)},"%Z":date=>date.tm_zone,"%%":()=>"%"};pattern=pattern.replace(/%%/g,"\0\0");for(var rule in EXPANSION_RULES_2){if(pattern.includes(rule)){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_2[rule](date))}}pattern=pattern.replace(/\0\0/g,"%");var bytes=intArrayFromString(pattern,false);if(bytes.length>maxsize){return 0}writeArrayToMemory(bytes,s);return bytes.length-1};var _strftime_l=(s,maxsize,format,tm,loc)=>_strftime(s,maxsize,format,tm);var getCFunc=ident=>{var func=Module["_"+ident];return func};var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={"string":str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},"array":arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i(___wasm_call_ctors=wasmExports["L"])();var _malloc=Module["_malloc"]=a0=>(_malloc=Module["_malloc"]=wasmExports["M"])(a0);var _free=Module["_free"]=a0=>(_free=Module["_free"]=wasmExports["N"])(a0);var ___getTypeName=a0=>(___getTypeName=wasmExports["P"])(a0);var __embind_initialize_bindings=Module["__embind_initialize_bindings"]=()=>(__embind_initialize_bindings=Module["__embind_initialize_bindings"]=wasmExports["Q"])();var ___errno_location=()=>(___errno_location=wasmExports["__errno_location"])();var stackSave=()=>(stackSave=wasmExports["R"])();var stackRestore=a0=>(stackRestore=wasmExports["S"])(a0);var stackAlloc=a0=>(stackAlloc=wasmExports["T"])(a0);var ___cxa_increment_exception_refcount=a0=>(___cxa_increment_exception_refcount=wasmExports["__cxa_increment_exception_refcount"])(a0);var ___cxa_is_pointer_type=a0=>(___cxa_is_pointer_type=wasmExports["U"])(a0);var dynCall_jiji=Module["dynCall_jiji"]=(a0,a1,a2,a3,a4)=>(dynCall_jiji=Module["dynCall_jiji"]=wasmExports["V"])(a0,a1,a2,a3,a4);var dynCall_viijii=Module["dynCall_viijii"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_viijii=Module["dynCall_viijii"]=wasmExports["W"])(a0,a1,a2,a3,a4,a5,a6);var dynCall_iiiiij=Module["dynCall_iiiiij"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_iiiiij=Module["dynCall_iiiiij"]=wasmExports["X"])(a0,a1,a2,a3,a4,a5,a6);var dynCall_iiiiijj=Module["dynCall_iiiiijj"]=(a0,a1,a2,a3,a4,a5,a6,a7,a8)=>(dynCall_iiiiijj=Module["dynCall_iiiiijj"]=wasmExports["Y"])(a0,a1,a2,a3,a4,a5,a6,a7,a8);var dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9)=>(dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=wasmExports["Z"])(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9);Module["ccall"]=ccall;var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); return moduleArg.ready } ); })(),[s,o]=await Promise.all([i,fetch(`${e}/process.wasm`).then(c=>c.arrayBuffer())]),a=s.default}return G0=n(),G0}var zY=["font"];function Da(n,t,e,r){let i,s,o;n.type==="PathGeometry"?(s=JSON.parse(JSON.stringify(n)),o=[[],["extrusion"]]):(s={...n},o=[[]]);for(let c of o){let u=s;for(let h of c)u=u[h];for(i in u){let h=u[i];LA(h)&&!zY.includes(i)&&(u[i]=t.getVariable(h,[r.uuid,"geometry",...c,i]),LA(u[i])&&(u[i]=1))}}let a={parameters:s,type:s.type};if(s.type==="PathGeometry")a.path=s.path;else if(s.type==="VectorGeometry"){let c=Xt.createFromState(s.shape,s.width,s.height);a.shape=c}else if(s.type==="NonParametricGeometry"){if(s.data.groups&&s.data.groups?.forEach(c=>c.materialIndex=Math.max(c.materialIndex??0,0)),a.geometry=new Ju().parse(s),a.geometry.groups.length===0){let c=a.geometry;c.addGroup(0,Math.max(c.getIndex()?.count??0,c.getAttribute("position").count),0)}}else if(s.type==="SubdivGeometry"){let c=new ni(s,e);return c.data=n,c}else{if(s.type==="TextGeometry")return new Hc(s,t);if(s.type==="InputGeometry")return new Hc(s,t);if(s.type==="UIGeometry")return Id.create({parameters:{width:s.width,height:s.height,cornerRadius:s.cornerRadius,cornerType:s.cornerType}})}let l;try{l=$1(a)}catch(c){console.error(c)}if(!l){let c=Xt.createFromState(Hh.defaultData(),100,100);a.shape=c,l=$1(a)}return l}var GY=new ue;function gm(n,t,e,r){let i=n.position.array,s=n.normal.array,o=GY.makeScale(t,e,r).invert().elements,a,l,c;for(var u=0,h=i.length;u{lt=n});var dR=new Float32Array([10,10,0,-10,10,0,-10,-10,0,10,-10,0]),fR=new Uint32Array([0,1,2,3]),pR=new Uint8Array([4]),ni=class extends _e{constructor(e,r){super();this.data=e;this.flatShading=r;this.subdivPointer=0;this.rebuild(),this.freeSubdivPointer()}mutateDirectlyScaleBaked(e,r){this.freeSubdivPointer();let i=this.data.scaleBaked,s=Mo.div(r,i);this.subdividedGeometry&&gm(this.subdividedGeometry.attributes,...s),this.originalGeometry&&gm(this.originalGeometry.attributes,...s),this.data=e;let o=this.userData.parameters;this.userData.parameters={width:o.width*s[0],height:o.height*s[1],depth:o.depth*s[2]},this.originalGeometry.boundingSphere.center.multiply(Od.fromArray(s));let a=Od.set(o.width,o.height,o.depth).length();this.originalGeometry.boundingSphere.radius=a/2}ensureSubdivPointer(){return this.subdivPointer===0&&this.rebuild(),this.subdivPointer}rebuild(){let e,r,i;try{({originalGeometry:e,subdividedGeometry:r,subdivPointer:i}=ni.build(this.data,void 0,!this.flatShading,void 0))}catch{e=new mi(100,100,100),i=0}this.subdivPointer=i,this.originalGeometry=e,this.subdividedGeometry=r??void 0;let s=this.subdividedGeometry??this.originalGeometry;Object.assign(this,s),this.calcBoundingBox()}freeSubdivPointer(){this.subdivPointer&&(ni.freeSubdivPointer(this.subdivPointer),this.subdivPointer=0)}dispose(){super.dispose(),this.freeSubdivPointer()}calcBoundingBox(){let e=this.originalGeometry;e.boundingSphere===null&&(e.boundingSphere=new Rr,this.subdividedGeometry&&(this.subdividedGeometry.boundingSphere=e.boundingSphere));let r=e.attributes.position,i=e.boundingSphere.center;H0.setFromBufferAttribute(r),H0.getCenter(i),e.boundingSphere.radius=i.distanceTo(H0.max),isNaN(e.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this),H0.getSize(Od);let s={width:Od.x,height:Od.y,depth:Od.z};return this.userData.parameters=s,s}static build(e,r,i,s){let o,a,l,c=e?.phongAngle??35;i===!1&&(c=-1),r&&(lt.free_bvh(r),lt.free_subdivision_surface(r));try{o=ni.allocate(e,s)}catch(u){console.error(u,e),o=ni.allocate({positionWASM:dR,indexWASM:fR,verticesPerFaceWASM:pR},s)}if(lt.set_destination_refinement_level(o,0),a=ni.buildLevel(o,!0,c),e.subdivisions>0)try{lt.set_destination_refinement_level(o,e.subdivisions),l=ni.buildLevel(o,!1,c)}catch{try{lt.set_destination_refinement_level(o,e.subdivisions-1),l=ni.buildLevel(o,!1,c)}catch{l=null}}else l=null;return{subdivPointer:o,originalGeometry:a,subdividedGeometry:l}}static primitiveToQuads(e,r,i){e.widthSegments>16&&(e.widthSegments=16),e.heightSegments>16&&(e.heightSegments=16),e.depthSegments>16&&(e.depthSegments=16),e.radialSegments>16&&(e.radialSegments=16),e.type==="DodecahedronGeometry"&&(e.detail=0);let s=e.shape!==void 0||e.path!==void 0?r.geometry:Da(e,i,!1),o;e.type==="TorusGeometry"&&e.arc===Math.PI*2?o=s.getClosedTorusIndicesForBooleanOrSubdiv():o=s.getIndex();let a,l,c,u;({positions:a,triIndices:u}=Wc(s.getAttribute("position"),o));let h;if(e.type==="CylinderGeometry"&&e.cornerRadius===0&&e.hollow===0&&e.openEnded===!1){let d=e.radialSegments*e.heightSegments*3*2,f=d+e.radialSegments*3;h=[d,f]}return{indices:l,verticesPerFace:c}=iE(a,u,s,h),{positions:a,indices:l,verticesPerFace:c}}static allocate(e,r){let i,s,o,a=[],l=[];e.positionWASM&&e.positionWASM.length>0?(i=e.positionWASM,s=e.indexWASM,o=e.verticesPerFaceWASM):(i=dR,s=fR,o=pR);let c=i.length,u=s.length,h=o.length,d=i.length+a.length+l.length,f=s.length+o.length,p=d*Float32Array.BYTES_PER_ELEMENT+f*Uint32Array.BYTES_PER_ELEMENT,m=d*Float32Array.BYTES_PER_ELEMENT,g=f*Uint32Array.BYTES_PER_ELEMENT,y=lt._malloc(p),v=new Float32Array(lt.HEAPF32.buffer,y,d),x=new Uint32Array(lt.HEAPU32.buffer,y+m,f);v.set(i,0),v.set(a,i.length),v.set(l,i.length+a.length),x.set(s,0),x.set(o,s.length);let S;e?.scaleBaked?.some(A=>A!==1)&&(S=new ue().makeScale(...e.scaleBaked)),r&&(S?S.premultiply(r):S=r);let w=S?lt.alloc_subdivision_surface2(y,c,y+m,u,y+m+s.length*Uint32Array.BYTES_PER_ELEMENT,h,S.elements):lt.alloc_subdivision_surface(y,c,y+m,u,y+m+s.length*Uint32Array.BYTES_PER_ELEMENT,h);return lt._free(y),w}static buildLevel(e,r,i,s,o){let a=o?lt.get_mesh_data2(e,r?lt.Level.CONTROL:lt.Level.REFINED,i,o.elements):lt.get_mesh_data(e,r?lt.Level.CONTROL:lt.Level.REFINED,i),l=8,c=lt.HEAPU32.subarray(a>>2,(a>>2)+l),u=c.subarray(4,4+4),h=0,d=lt.HEAPU32[c[h]>>2],f=lt.HEAPF32.subarray(d>>2,(d>>2)+u[h]);h++;let p=lt.HEAPU32[c[h]>>2],m=lt.HEAPF32.subarray(p>>2,(p>>2)+u[h]);h++;let g=lt.HEAPU32[c[h]>>2],y=lt.HEAPU32.subarray(g>>2,(g>>2)+u[h]);h++;let v=lt.HEAPU32[c[h]>>2],x=lt.HEAPU32.subarray(v>>2,(v>>2)+u[h]);if(h++,s===void 0){let S=new _e;if(S.setIndex(new po(x,1)),S.setAttribute("position",new Te(f,3)),S.setAttribute("normal",new Te(m,3)),r){S.setAttribute("faceMap",new po(y,1));let w=new Float32Array(m.length/3*4).fill(0);S.setAttribute("color",new Xe(w,4))}return lt.free_mesh_data(a),S.userData.type="SubdivGeometry",S}s.getAttribute("position").copyArray(f),s.getAttribute("normal").copyArray(m),s.attributes.position.needsUpdate=!0,s.attributes.normal.needsUpdate=!0,lt.free_mesh_data(a)}static freeSubdivPointer(e){lt.free_bvh(e),lt.free_subdivision_surface(e)}static buildControlCageWireframe(e,r,i){let s=lt.get_wireframe_data_for_base_level(e),o=4,a=lt.HEAPU32.subarray(s>>2,(s>>2)+o),l=a.subarray(2,2+2),c=0,u=lt.HEAPU32[a[c]>>2],h=lt.HEAPF32.subarray(u>>2,(u>>2)+l[c]);c++;let d=lt.HEAPU32[a[c]>>2],f=lt.HEAPU32.subarray(d>>2,(d>>2)+l[c]);if(r===void 0){let p=new _e;p.setAttribute("position",new Te(h,3));let m=new Float32Array(h.length);for(let g=0,y=h.length;g>2,(o>>2)+a),c=l.subarray(3,3+3),u=0,h=lt.HEAPU32[l[u]>>2],d=new Float32Array(lt.HEAPF32.subarray(h>>2,(h>>2)+c[u]));u++;let f=lt.HEAPU32[l[u]>>2],p=new Uint32Array(lt.HEAPU32.subarray(f>>2,(f>>2)+c[u]));u++;let m=lt.HEAPU32[l[u]>>2],g=new Uint8Array(lt.HEAPU32.subarray(m>>2,(m>>2)+c[u]));return lt.free_topological_data(o),{positions:d,indices:p,verticesPerFace:g}}};var mR=["getX","getY","getZ"];function Wc(n,t){let e={},r=t?t.count:n.count,i=0,s=[],o=[],a=1e4;for(let c=0;c=360){let d=l.length/2/c;l=l.filter((f,p)=>Math.floor(p/2)%d===0)}let u=0;for(let d=0;d=0;d-=2)n.push(l[d],l[d+1],0),i.push(h++);return s.push(h),{indices:i,verticesPerFace:s}}let o=new Float32Array([e.userData.parameters.depth])[0],a=0;for(;a.005||r&&r.some((c,u)=>u%2===1?!1:a>=r[u]&&aWY,calcBooleanTopological:()=>HY,freeMeshSet:()=>KY,getMeshSet:()=>qY,hasOpenEdges:()=>YY,transformMeshSet:()=>XY});var gR,yR=new Promise(n=>{gR=n});var q0;function vR(){if(q0)return q0;async function n(){let e=!1?".":"https://unpkg.com/@splinetool/boolean-wasm@1.9.35/build",i=import("./boolean.js"),[s,o]=await Promise.all([i,fetch(`${e}/boolean.wasm`).then(c=>c.arrayBuffer())]),a=s.default,l=await a({wasmBinary:o});gR(l)}return q0=n(),q0}var Mt,Rd;yR.then(n=>Mt=n);function jY(n,t,e){let r,i;n.userData.parameters.type==="TorusGeometry"&&n.userData.parameters.arc===Math.PI*2?i=n.getClosedTorusIndicesForBooleanOrSubdiv():i=n.getIndex();let{positions:s,triIndices:o}=Wc(n.getAttribute("position"),i),a;if(t&&e){let{indices:l,verticesPerFace:c}=iE(s,o,n);a=c.length,r=[];for(let u=0,h=0;u>2,(r>>2)+i),o=s.subarray(3,3+3),a=0,l=Mt.HEAPU32[s[a]>>2],c=new Float32Array(Mt.HEAPF32.subarray(l>>2,(l>>2)+o[a]));a++;let u=Mt.HEAPU32[s[a]>>2],h=new Uint32Array(Mt.HEAPU32.subarray(u>>2,(u>>2)+o[a]));a++;let d=Mt.HEAPU32[s[a]>>2],f=new Uint8Array(Mt.HEAPU32.subarray(d>>2,(d>>2)+o[a]));return Mt.free_mesh_data(r),{positions:c,indices:h,verticesPerFace:f}}function WY(n,t,e,r){Rd===void 0&&(Rd=Mt.init_csg());let i=xR(n),s=Mt.csg_calc(Rd,i,n.length,r,bR(t));Mt._free(i);let o=5,a=Mt.HEAPU32.subarray(s>>2,(s>>2)+o),l=a.subarray(2,2+3),c=0,u=Mt.HEAPU32[a[c]>>2],h=Mt.HEAPF32.subarray(u>>2,(u>>2)+l[c]);c++;let d=Mt.HEAPU32[a[c]>>2],f=Mt.HEAPF32.subarray(d>>2,(d>>2)+l[c]);c++;let p=l[c];e.setAttribute("position",new Te(h,3)),e.setAttribute("normal",new Te(f,3));let m=Mt.HEAPF32.subarray((s>>2)+5,(s>>2)+5+6);return e.boundingSphere===null&&(e.boundingSphere=new Rr),e.boundingSphere.center.set(m[0],m[1],m[2]),e.boundingSphere.radius=(m[3]**2+m[4]**2+m[5]**2)**.5,e.userData.parameters={width:m[3]*2,height:m[4]*2,depth:m[5]*2},Mt.free_mesh_data(s),p}function qY(n,t,e){if(Mt===void 0)return-1;let r,i,s;if(t&&n.userData.positions!==void 0){let y=n.userData;s=y.verticesPerFace.length,r=y.positions,i=Array(y.verticesPerFace.reduce((v,x)=>v+x,0)+s);for(let v=0,x=0,S=0;vQY[n.type].create(n);function Ld(n){return n!==null&&"booleanOp"in n}var Bd=class extends xd(Ut){constructor(){super(...arguments);this.booleanMeshSetAddress=-1;this.booleanWasTransformed=!1;this.booleanMatrixInvOld=new ue}updateVisible(e){super.updateVisible(e),this.visible=!Ld(this.parent)&&this.visible,Ld(this.parent)&&this.parent.invalidateDownstreamBooleanData()}freeBooleanPointer(){this.booleanMeshSetAddress!==-1&&(ms.freeMeshSet(this.booleanMeshSetAddress),this.booleanMeshSetAddress=-1)}invalidateDownstreamBooleanData(e=!1){return e?this.booleanWasTransformed=!0:this.freeBooleanPointer(),Ld(this.parent)?this.parent.invalidateDownstreamBooleanData():this}invalidateUpstreamBooleanData(){this.freeBooleanPointer();for(let e of this.children)e instanceof Bd&&(e.freeBooleanPointer(),Ld(e)&&e.invalidateUpstreamBooleanData())}updateTransformState(e,r){let i=super.updateTransformState(e,r);return i&&Ld(this.parent)&&this.invalidateDownstreamBooleanData(!0),i}onVariableUpdate(e=!1){super.onVariableUpdate(e),Ld(this.parent)&&this.invalidateDownstreamBooleanData(!0)}};var Y0=new Ht;function ym(n,t=0,e=n.count,r,i){let s=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,u=-1/0;for(let h=t;hl&&(l=d),f>c&&(c=f),p>u&&(u=p)}Y0.min.set(s,o,a),Y0.max.set(l,c,u),Y0.getCenter(r),Y0.getSize(i).multiplyScalar(.5)}var ZY=new _e,JY=new on,mr=class extends Bd{constructor(t,e){super(ZY,JY),this.super_Entity(t,e)}updateState(t,e){this.updateState_Entity(t,e)}updateEntityBoxSize(t,e){let r=this.geometry.getAttribute("position");r!==void 0?ym(r,this.geometry.drawRange.start,this.geometry.drawRange.count<1/0?this.geometry.drawRange.count:r.count,t,e):super.updateEntityBoxSize(t,e)}};var Oa=class{constructor(t){this.hashProperties=void 0;this.isNode=!0;this.shortcuts={};if(Oa.uuidContext===null)throw new Error("plz startContext");Oa.uuidContext===Oa.globalContext?this.uuid="_gid"+Oa.uuidContext.nodeContextUuid++:this.uuid="_uid"+Oa.uuidContext.nodeContextUuid++,this.type=t,this.name=""}static startContext(t){this.uuidContext===null||this.uuidContext===Oa.globalContext?this.uuidContext=t:console.error("Can't start context twice")}static endContext(t){this.uuidContext!==t&&console.error("Can't end context twice"),this.uuidContext=null}analyze(t,e){e=e??{},t.analyzing=!0,this.build(t.addFlow(e.slot,e.cache,e.context),"v4"),t.clearVertexNodeCode(),t.clearFragmentNodeCode(),t.removeFlow(),t.analyzing=!1}analyzeAndFlow(t,e,r){return r=r??{},this.analyze(t,r),this.flow(t,e,r)}flow(t,e,r){r=r??{},t.addFlow(r.slot,r.cache,r.context);let i={result:this.build(t,e),code:t.clearNodeCode(),extra:t.context.extra};return t.removeFlow(),i}build(t,e,r){e=e??this.getType(t,e);let i=t.getNodeData(r??this);return t.analyzing&&this.appendDepsNode(t,i,e),t.nodes.indexOf(this)===-1&&t.nodes.push(this),this.updateFrame!==void 0&&t.updaters.indexOf(this)===-1&&t.updaters.push(this),this.generate(t,e,r)}updateFrame(t){}generateReadonly(t,e,r,i,s,o){return""}generate(t,e,r,i,s){return""}parse(t,e,r,i){}appendDepsNode(t,e,r){e.deps=(e.deps||0)+1;let i=t.getTypeLength(r);(i>(e.outputMax||0)||this.getType(t,r))&&(e.outputMax=i,e.output=r)}setName(t){this.name=t}getName(){return this.name}getType(t,e){return e==="sampler2D"||e==="samplerCube"?e:this.type}},or=Oa;or.globalContext={nodeContextUuid:0},or.uuidContext=Oa.globalContext;var vm=class{constructor(t){t=t??{},this.name=t.name,this.type=t.type,this.node=t.node,this.size=t.size,this.needsUpdate=t.needsUpdate}get value(){return this.node.value}set value(t){this.node.value=t}};var nE=class{constructor(){this.nodes={};this.keywords={}}add(t){this.nodes[t.name]=t}addKeyword(t,e,r){r=r!==void 0?r:!0,this.keywords[t]={callback:e,cache:r}}remove(t){delete this.nodes[t.name]}removeKeyword(t){delete this.keywords[t]}get(t){return this.nodes[t]}getKeyword(t,e){return this.keywords[t].callback(e)}getKeywordData(t){return this.keywords[t]}contains(t){return this.nodes[t]!==void 0}containsKeyword(t){return this.keywords[t]!==void 0}},_i=new nE;var tt=class extends or{constructor(e,r){super(e);this.scope="";r=r??{},this.shared=r.shared!==void 0?r.shared:!0,this.unique=r.unique!==void 0?r.unique:!1}build(e,r,i,s){if(r=r??this.getType(e),this.getShared(e,r)){let o=this.getUnique(e,r);o&&this.uuid===void 0&&(this.uuid=we.generateUUID()),i=e.getUUID(i??this.getUUID(),!o);let a=e.getNodeData(i),l=a.output||this.getType(e);if(e.analyzing)return(a.deps||0)>0||this.getLabel()?(this.appendDepsNode(e,a,r),this.generate(e,r,i)):super.build(e,r,i);if(o)return a.name=a.name||super.build(e,r,i),a.name;if(!this.getLabel()&&(!this.getShared(e,l)||e.context.ignoreCache||a.deps===1))return super.build(e,r,i);i=this.getUUID(!1);let c=this.getTemp(e,i);if(c)return e.format(c,l,r);{c=super.generate(e,r,i,a.output,s);let u=this.generate(e,l,i);return e.addNodeCode(c+" = "+u+";"),e.format(c,l,r)}}return super.build(e,r,i)}getShared(e,r){return r!=="sampler2D"&&r!=="samplerCube"&&this.shared}getUnique(e,r){return this.unique}setLabel(e){return this.label=e,this}getLabel(){return this.label}getUUID(e){let r=this.uuid;return typeof this.scope=="string"&&(r=this.scope+"-"+r),r}getTemp(e,r){r=r||this.uuid;let i=e.getVars()[r];return i?i.name:void 0}generate(e,r,i,s,o){return this.getShared(e,r)||console.error("TempNode is not shared"),i=i??this.uuid,e.getTempVar(i,s??this.getType(e),o,this.getLabel()).name}};var ar=class extends tt{constructor(e,r){r=r??{},r.shared=r.shared!==void 0?r.shared:!1;super(e,r);this.readonly=!1}setReadonly(e){return this.readonly=e,this.hashProperties=this.readonly?["value"]:void 0,this}getReadonly(){return this.readonly}generate(e,r,i,s,o,a){i=e.getUUID(i??this.getUUID()),s=s??this.getType(e);let l=e.getNodeData(i);return this.getReadonly()&&this.generateReadonly!==void 0?this.generateReadonly(e,r,i,s,o,a):e.isShader("vertex")?(l.vertex||(l.vertex=e.createVertexUniform(s,this,o,a,this.getLabel())),e.format(l.vertex.name,s,r)):(l.fragment||(l.fragment=e.createFragmentUniform(s,this,o,a,this.getLabel())),e.format(l.fragment.name,s,r))}};var Hr=class extends ar{constructor(e=0,r){super("v2");this.nodeType="Vector2";this.value=e instanceof k?e:new k(e,r)}get x(){return this.value.x}set x(e){this.value.x=e}get y(){return this.value.y}set y(e){this.value.y=e}generateReadonly(e,r,i,s,o,a){return e.format("vec2("+this.value.x+", "+this.value.y+")",s,r)}};var Xi=class extends ar{constructor(e=0,r,i){super("v3");this.nodeType="Vector3";this.value=e instanceof E?e:new E(e,r,i)}get x(){return this.value.x}set x(e){this.value.x=e}get y(){return this.value.y}set y(e){this.value.y=e}get z(){return this.value.z}set z(e){this.value.z=e}generateReadonly(e,r,i,s,o,a){return e.format("vec3("+this.value.x+", "+this.value.y+", "+this.value.z+")",s,r)}};var vr=class extends We{constructor(e,r,i,s){super(e,r,i);this.isColorA=!0;this.a=s}setRGBA(e,r,i,s){super.setRGB(e,r,i),this.a=s}copy(e){return super.copy(e),this.a="a"in e?e.a:1,this}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}equals(e){return super.equals(e)&&this.a===e.a}setStyle(e,r="srgb"){let i;if(e==="transparent")return this.setRGBA(0,0,0,0),this;if(i=/^((?:rgb|hsl)a?)\(([^)]*)\)/.exec(e)){let s,o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return this.a=o==="rgba"?parseFloat(s[4]):1,super.setStyle(e,r);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)%\s*,\s*(\d*\.?\d+)%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return this.a=o==="hsla"?parseFloat(s[4]):1,super.setStyle(e,r);break}}return super.setStyle(e,r)}get x(){return this.r}get y(){return this.g}get z(){return this.b}get w(){return this.a}set x(e){this.r=e}set y(e){this.g=e}set z(e){this.b=e}set w(e){this.a=e}};var Ln=class extends ar{constructor(e){super("v4");this.nodeType="Vector4";this.value=e instanceof vr?e:new vr(e.r,e.g,e.b,e.a)}generateReadonly(e,r,i,s,o,a){return e.format("vec4("+this.value.r+", "+this.value.g+", "+this.value.b+", "+this.value.a+")",s,r)}};var $Y=/^\s*([a-z_0-9]+)\s([a-z_0-9]+)\s*\((.*?)\)/i,SR=/[a-z_0-9]+/gi,Ee=class extends tt{constructor(e,r,i,s,o){super(o);this.src="";this.nodeType="Function";this.useKeywords=!0;this.includes=[];this.extensions={};this.keywords={};this.isMethod=o===void 0,this.isInterface=!1,this.parse(e,r,i,s)}getShared(e,r){return!this.isMethod}getType(e){return e.getTypeByFormat(this.type)}getInputByName(e){if(this.inputs){let r=this.inputs.length;for(;r--;)if(this.inputs[r].name===e)return this.inputs[r]}}getIncludeByName(e){if(this.includes){let r=this.includes.length;for(;r--;)if(this.includes[r].name===e)return this.includes[r]}}generate(e,r,i,s,o){let a,l=0,c=this.src;if(this.includes)for(let h=0;h1?(l=u[1],a=u[2],c=u[3]):(a=this.src,l="f"),this.name=a,this.type=l,this.value=c}build(e,r){if(r==="source"){if(this.value)return this.useDefine?"#define "+this.name+" "+this.value:"const "+this.type+" "+this.name+" = "+this.value+";";if(this.useDefine)return this.src}return e.include(this),e.format(this.name,this.getType(e),r)}generate(e,r,i,s,o){return e.format(this.name,this.getType(e),r)}},qt=sE;qt.PI="PI",qt.PI2="PI2",qt.RECIPROCAL_PI="RECIPROCAL_PI",qt.RECIPROCAL_PI2="RECIPROCAL_PI2",qt.LOG2="LOG2",qt.EPSILON="EPSILON";var tX=new RegExp(`^structs*([a-z_0-9]+)s*{s*((.| )*?)}`,"gim"),rX=new RegExp("s*(w*?)s*(w*?)(=|;)","gim"),Nd=class extends tt{constructor(e=""){super();this.inputs=[];this.src="";this.nodeType="Struct";this.parse(e)}getType(e){return e.getTypeByFormat(this.name)}getInputByName(e){let r=this.inputs.length;for(;r--;)if(this.inputs[r].name===e)return this.inputs[r]}generate(e,r,i,s,o){return r==="source"?this.src+";":e.format("( "+this.src+" )",this.getType(e),r)}parse(e=""){this.src=e,this.inputs=[];let r=tX.exec(e);if(r){let i=r[2],s;for(;s=rX.exec(i);)this.inputs.push({type:s[1],name:s[2]});this.name=r[1]}else this.name="";this.type=this.name}};var Fd=class extends tt{constructor(e){super("v2",{shared:!1});this.nodeType="UV";this.index=e??0}generate(e,r){e.requires.uv[this.index]=!0;let i=this.index>0?this.index+1:"",s=e.isShader("vertex")?"uv"+i:"vUv"+i;return e.format(s,this.getType(e),r)}};_i.addKeyword("uv",function(){return new Fd});_i.addKeyword("uv2",function(){return new Fd(1)});var qc=class extends tt{constructor(e,r){super("v4");this.nodeType="ColorSpace";this.input=e,this.method=r??qc.LINEAR_TO_LINEAR,this.hashProperties=["method"]}static getEncodingComponents(e){switch(e){case mn:return["Linear"];case at:return["sRGB"];default:return[]}}generate(e,r){let i=this.input.build(e,"v4"),s=this.getType(e),o=qc.Nodes[this.method],a=e.include(o);if(a===qc.LINEAR_TO_LINEAR)return e.format(i,s,r);if(o.inputs?.length===2){let l=this.factor.build(e,"f");return e.format(a+"( "+i+", "+l+" )",s,r)}else return e.format(a+"( "+i+" )",s,r)}fromEncoding(e){let r=qc.getEncodingComponents(e);this.method="LinearTo"+r[0],this.factor=r[1]}fromDecoding(e){let r=qc.getEncodingComponents(e);this.method=r[0]+"ToLinear",this.factor=r[1]}},xn=qc;xn.Nodes={LinearToLinear:new Ee(["vec4 LinearToLinear( in vec4 value ) {"," return value;","}"].join(` `)),sRGBToLinear:new Ee(["vec4 sRGBToLinear( in vec4 value ) {"," return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );","}"].join(` `)),LinearTosRGB:new Ee(["vec4 LinearTosRGB( in vec4 value ) {"," return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );","}"].join(` `))},xn.LINEAR_TO_LINEAR="LinearToLinear",xn.SRGB_TO_LINEAR="sRGBToLinear",xn.LINEAR_TO_SRGB="LinearTosRGB";var Kt=class extends Ee{constructor(e="",r,i,s,o){super(e,o,s,i,r);this.nodeType="Expression"}};var bn=class extends ar{constructor(e=new er,r,i,s){super("v4",{shared:!0});this.nodeType="Texture";this.value=e,this.uv=r??new Fd,this.bias=i,this.project=s!==void 0?s:!1}getTexture(e,r){return super.generate(e,r,this.value.uuid,"t")}generate(e,r){if(r==="sampler2D")return this.getTexture(e,r);let i=this.getTexture(e,r),s=this.uv.build(e,this.project?"v4":"v2"),o=this.bias?this.bias.build(e,"f"):void 0;o===void 0&&e.context.bias&&(o=e.context.bias.setTexture(this).build(e,"f"));let a,l;this.project?a="texture2DProj":a=o?"tex2DBias":"tex2D",o?l=a+"( "+i+", "+s+", "+o+" )":l=a+"( "+i+", "+s+" )";let c={include:e.isShader("vertex"),ignoreCache:!0},u=this.getType(e);return e.addContext(c),this.colorSpace=this.colorSpace??new xn(new Kt("",u)),this.colorSpace.fromDecoding(e.getTextureEncodingFromMap(this.value)),this.colorSpace.input.parse(l),l=this.colorSpace.build(e,u),e.removeContext(),e.format(l,u,r)}};var Fe=class extends ar{constructor(e){super("f");this.nodeType="Float";this.value=e??0}generateReadonly(e,r,i,s,o,a){return e.format(this.value+(this.value%1?"":".0"),s,r)}};var xm=class extends tt{constructor(e,r){super();this.inputs=[];this.nodeType="FunctionCall";this.value=e,this.inputs=r??[]}getFunction(){return this.value}getType(e){return this.value.getType(e)}generate(e,r,i,s,o){s=this.getType(e);let a=this.value,l=a.build(e,r)+"( ",c=[];if(a.inputs){for(let u=0;ue.getTypeLength(r)?i:r}generate(e,r){let i=this.getType(e);this.type=i;let s=this.a.build(e,i),o=this.b.build(e,i);return e.format("( "+s+" "+this.op+" "+o+" )",i,r)}},ki=oE;ki.ADD="+",ki.SUB="-",ki.MUL="*",ki.DIV="/";var lr=class extends tt{constructor(e,r=lr.ABS,i,s){super();this.nodeType="Math";this.a=e,typeof r!="string"?this.b=r:s=r,typeof i!="string"?this.c=i:s=i,this.method=s,this.hashProperties=["method"]}getNumInputs(e){switch(this.method){case lr.MIX:case lr.CLAMP:case lr.REFRACT:case lr.SMOOTHSTEP:case lr.FACEFORWARD:return 3;case lr.MIN:case lr.MAX:case lr.MOD:case lr.STEP:case lr.REFLECT:case lr.DISTANCE:case lr.DOT:case lr.CROSS:case lr.POW:return 2;default:return 1}}getInputType(e){let r=e.getTypeLength(this.a.getType(e)),i=this.b?e.getTypeLength(this.b.getType(e)):0,s=this.c?e.getTypeLength(this.c.getType(e)):0;return r>i&&r>s?this.a.getType(e):i>s?this.b.getType(e):this.c.getType(e)}getType(e){switch(this.method){case lr.LENGTH:case lr.DISTANCE:case lr.DOT:return"f";case lr.CROSS:return"v3"}return this.getInputType(e)}generate(e,r){let i,s,o,a=this.a?e.getTypeLength(this.a.getType(e)):0,l=this.b?e.getTypeLength(this.b.getType(e)):0,c=this.c?e.getTypeLength(this.c.getType(e)):0,u=this.getInputType(e),h=this.getType(e);switch(this.type=h,this.method){case lr.NEGATE:return e.format("( -"+this.a.build(e,u)+" )",u,r);case lr.INVERT:return e.format("( 1.0 - "+this.a.build(e,u)+" )",u,r);case lr.CROSS:i=this.a.build(e,"v3"),s=this.b.build(e,"v3");break;case lr.STEP:i=this.a.build(e,a===1?"f":u),s=this.b.build(e,u);break;case lr.MIN:case lr.MAX:case lr.MOD:i=this.a.build(e,u),s=this.b.build(e,l===1?"f":u);break;case lr.REFRACT:i=this.a.build(e,u),s=this.b.build(e,u),o=this.c.build(e,"f");break;case lr.MIX:i=this.a.build(e,u),s=this.b.build(e,u),o=this.c.build(e,c===1?"f":u);break;default:i=this.a.build(e,u),this.b&&(s=this.b.build(e,u)),this.c&&(o=this.c.build(e,u));break}let d=[];d.push(i),s&&d.push(s),o&&d.push(o);let f=this.getNumInputs(e);if(d.length!==f)throw Error(`Arguments not match used in "${this.method}". Require ${f}, currently ${d.length}.`);return e.format(this.method+"( "+d.join(", ")+" )",h,r)}},ft=lr;ft.RAD="radians",ft.DEG="degrees",ft.EXP="exp",ft.EXP2="exp2",ft.LOG="log",ft.LOG2="log2",ft.SQRT="sqrt",ft.INV_SQRT="inversesqrt",ft.FLOOR="floor",ft.CEIL="ceil",ft.NORMALIZE="normalize",ft.FRACT="fract",ft.SATURATE="saturate",ft.SIN="sin",ft.COS="cos",ft.TAN="tan",ft.ASIN="asin",ft.ACOS="acos",ft.ARCTAN="atan",ft.ABS="abs",ft.SIGN="sign",ft.LENGTH="length",ft.NEGATE="negate",ft.INVERT="invert",ft.MIN="min",ft.MAX="max",ft.MOD="mod",ft.STEP="step",ft.REFLECT="reflect",ft.DISTANCE="distance",ft.DOT="dot",ft.CROSS="cross",ft.POW="pow",ft.MIX="mix",ft.CLAMP="clamp",ft.REFRACT="refract",ft.SMOOTHSTEP="smoothstep",ft.FACEFORWARD="faceforward";var Vd=class extends tt{constructor(e,r,i){super("v4");this.nodeType="TextureCubeUV";this.value=e,this.uv=r,this.bias=i}bilinearCubeUV(e,r,i,s){let o=new xm(Vd.Nodes.bilinearCubeUV,[r,i,s]);this.colorSpaceTL=this.colorSpaceTL??new xn(new Kt("","v4")),this.colorSpaceTL.fromDecoding(e.getTextureEncodingFromMap(this.value.value)),this.colorSpaceTL.input.parse(o.build(e)+".tl"),this.colorSpaceTR=this.colorSpaceTR??new xn(new Kt("","v4")),this.colorSpaceTR.fromDecoding(e.getTextureEncodingFromMap(this.value.value)),this.colorSpaceTR.input.parse(o.build(e)+".tr"),this.colorSpaceBL=this.colorSpaceBL??new xn(new Kt("","v4")),this.colorSpaceBL.fromDecoding(e.getTextureEncodingFromMap(this.value.value)),this.colorSpaceBL.input.parse(o.build(e)+".bl"),this.colorSpaceBR=this.colorSpaceBR??new xn(new Kt("","v4")),this.colorSpaceBR.fromDecoding(e.getTextureEncodingFromMap(this.value.value)),this.colorSpaceBR.input.parse(o.build(e)+".br");let a={include:e.isShader("vertex"),ignoreCache:!0};e.addContext(a),this.colorSpaceTLExp=new Kt(this.colorSpaceTL.build(e,"v4"),"v4"),this.colorSpaceTRExp=new Kt(this.colorSpaceTR.build(e,"v4"),"v4"),this.colorSpaceBLExp=new Kt(this.colorSpaceBL.build(e,"v4"),"v4"),this.colorSpaceBRExp=new Kt(this.colorSpaceBR.build(e,"v4"),"v4"),e.removeContext();let l=new Kt("mix( mix( cubeUV_TL, cubeUV_TR, cubeUV.f.x ), mix( cubeUV_BL, cubeUV_BR, cubeUV.f.x ), cubeUV.f.y )","v4");return l.keywords.cubeUV_TL=this.colorSpaceTLExp,l.keywords.cubeUV_TR=this.colorSpaceTRExp,l.keywords.cubeUV_BL=this.colorSpaceBLExp,l.keywords.cubeUV_BR=this.colorSpaceBRExp,l.keywords.cubeUV=o,l}generate(e,r){if(e.isShader("fragment")){let i=this.uv,s=this.bias||e.context.roughness,o=new xm(Vd.Nodes.roughnessToMip,[s]),a=new ft(o,Vd.Nodes.m0,Vd.Nodes.cubeUV_maxMipLevel,ft.CLAMP),l=new ft(a,ft.FLOOR),c=new ft(a,ft.FRACT),u=this.bilinearCubeUV(e,this.value,i,l),h=this.bilinearCubeUV(e,this.value,i,new ki(l,new Fe(1).setReadonly(!0),ki.ADD)),d=new ft(u,h,c,ft.MIX);return e.format(d.build(e),"v4",r)}else return console.warn("TextureCubeUVNode is not compatible with "+e.shader+" shader."),e.format("vec4( 0.0 )",this.getType(e),r)}},kd=Vd;kd.Nodes=function(){let e=new Nd(`struct TextureCubeUVData { vec4 tl; vec4 tr; vec4 br; vec4 bl; vec2 f; }`),r=new qt("float cubeUV_maxMipLevel 8.0",!0),i=new qt("float cubeUV_minMipLevel 4.0",!0),s=new qt("float cubeUV_maxTileSize 256.0",!0),o=new qt("float cubeUV_minTileSize 16.0",!0),a=new Ee(`float getFace(vec3 direction) { vec3 absDirection = abs(direction); float face = -1.0; if (absDirection.x > absDirection.z) { if (absDirection.x > absDirection.y) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if (absDirection.z > absDirection.y) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; }`);a.useKeywords=!1;let l=new Ee(`vec2 getUV(vec3 direction, float face) { vec2 uv; if (face == 0.0) { uv = vec2(direction.z, direction.y) / abs(direction.x); // pos x } else if (face == 1.0) { uv = vec2(-direction.x, -direction.z) / abs(direction.y); // pos y } else if (face == 2.0) { uv = vec2(-direction.x, direction.y) / abs(direction.z); // pos z } else if (face == 3.0) { uv = vec2(-direction.z, direction.y) / abs(direction.x); // neg x } else if (face == 4.0) { uv = vec2(-direction.x, direction.z) / abs(direction.y); // neg y } else { uv = vec2(direction.x, direction.y) / abs(direction.z); // neg z } return 0.5 * (uv + 1.0); }`);l.useKeywords=!1;let c=new Ee(`TextureCubeUVData bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) { float face = getFace(direction); float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0); mipInt = max(mipInt, cubeUV_minMipLevel); float faceSize = exp2(mipInt); float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize); vec2 uv = getUV(direction, face) * (faceSize - 1.0); vec2 f = fract(uv); uv += 0.5 - f; if (face > 2.0) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; if(mipInt < cubeUV_maxMipLevel){ uv.y += 2.0 * cubeUV_maxTileSize; } uv.y += filterInt * 2.0 * cubeUV_minTileSize; uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize); uv *= texelSize; vec4 tl = texture2D(envMap, uv); uv.x += texelSize; vec4 tr = texture2D(envMap, uv); uv.y += texelSize; vec4 br = texture2D(envMap, uv); uv.x -= texelSize; vec4 bl = texture2D(envMap, uv); return TextureCubeUVData( tl, tr, br, bl, f ); }`,[e,a,l,r,i,s,o]);c.useKeywords=!1;let u=new qt("float r0 1.0",!0),h=new qt("float v0 0.339",!0),d=new qt("float m0 -2.0",!0),f=new qt("float r1 0.8",!0),p=new qt("float v1 0.276",!0),m=new qt("float m1 -1.0",!0),g=new qt("float r4 0.4",!0),y=new qt("float v4 0.046",!0),v=new qt("float m4 2.0",!0),x=new qt("float r5 0.305",!0),S=new qt("float v5 0.016",!0),w=new qt("float m5 3.0",!0),A=new qt("float r6 0.21",!0),T=new qt("float v6 0.0038",!0),b=new qt("float m6 4.0",!0),M=[u,h,d,f,p,m,g,y,v,x,S,w,A,T,b],C=new Ee(`float roughnessToMip(float roughness) { float mip = 0.0; if (roughness >= r1) { mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0; } else if (roughness >= r4) { mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1; } else if (roughness >= r5) { mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4; } else if (roughness >= r6) { mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5; } else { mip = -2.0 * log2(1.16 * roughness);// 1.16 = 1.79^0.25 } return mip; }`,M);return{bilinearCubeUV:c,roughnessToMip:C,m0:d,cubeUV_maxMipLevel:r}}();var Yc=class extends tt{constructor(e){super("v3");this.nodeType="Normal";this.scope=e??Yc.VIEW}getShared(){return this.scope===Yc.WORLD}build(e,r,i,s){let o=e.context[this.scope+"Normal"];return o?o.build(e,r,i,s):super.build(e,r,i)}generate(e,r,i,s,o){let a;switch(this.scope){case Yc.VIEW:e.isShader("vertex")?a="transformedNormal":a="geometryNormal";break;case Yc.LOCAL:e.isShader("vertex")?a="objectNormal":(e.requires.normal=!0,a="vObjectNormal");break;case Yc.WORLD:e.isShader("vertex")?a="inverseTransformDirection( transformedNormal, viewMatrix ).xyz":(e.requires.worldNormal=!0,a="vWNormal");break}return e.format(a,this.getType(e),r)}},Ui=Yc;Ui.LOCAL="local",Ui.WORLD="world",Ui.VIEW="view",Ui.NORMAL="normal";_i.addKeyword("viewNormal",function(){return new Ui(Ui.VIEW)});_i.addKeyword("localNormal",function(){return new Ui(Ui.NORMAL)});_i.addKeyword("worldNormal",function(){return new Ui(Ui.WORLD)});var Bo=class extends tt{constructor(e){super("v3");this.nodeType="Position";this.scope=e??Bo.LOCAL}getType(){switch(this.scope){case Bo.PROJECTION:return"v4"}return this.type}getShader(){switch(this.scope){case Bo.LOCAL:case Bo.WORLD:return!1}return!0}generate(e,r,i,s,o){let a;switch(this.scope){case Bo.LOCAL:e.isShader("vertex")?a="transformed":(e.requires.position=!0,a="vPosition");break;case Bo.WORLD:if(e.isShader("vertex"))return"( modelMatrix * vec4( transformed, 1.0 ) ).xyz";e.requires.worldPosition=!0,a="vWPosition";break;case Bo.VIEW:a=e.isShader("vertex")?"-mvPosition.xyz":"vViewPosition";break;case Bo.PROJECTION:a=e.isShader("vertex")?"( projectionMatrix * modelViewMatrix * vec4( position, 1.0 ) )":"vec4( 0.0 )";break}return e.format(a,this.getType(),r)}},Bn=Bo;Bn.LOCAL="local",Bn.WORLD="world",Bn.VIEW="view",Bn.PROJECTION="projection";_i.addKeyword("position",function(){return new Bn});_i.addKeyword("worldPosition",function(){return new Bn(Bn.WORLD)});_i.addKeyword("viewPosition",function(){return new Bn(Bn.VIEW)});var Ys=class extends tt{constructor(e){super("v3");this.nodeType="Reflect";this.scope=e??Ys.CUBE}getUnique(e){return!e.context.viewNormal}getType(){switch(this.scope){case Ys.SPHERE:return"v2"}return this.type}generate(e,r){let i=this.getUnique(e);if(e.isShader("fragment")){let s;switch(this.scope){case Ys.VECTOR:{let o=new Ui(Ui.VIEW),a=e.context.roughness,l=o.build(e,"v3"),c=new Bn(Bn.VIEW).build(e,"v3"),u=a?a.build(e,"f"):void 0,h=`reflect( -normalize( ${c} ), ${l} )`;u&&(h=`normalize( mix( ${h}, ${l}, ${u} * ${u} ) )`);let d=`inverseTransformDirection( ${h}, viewMatrix )`;i?(e.addNodeCode(`vec3 reflectVec = ${d};`),s="reflectVec"):s=d;break}case Ys.CUBE:{let o=new Ys(Ys.VECTOR).build(e,"v3"),a="vec3( -"+o+".x, "+o+".yz )";i?(e.addNodeCode(`vec3 reflectCubeVec = ${a};`),s="reflectCubeVec"):s=a;break}case Ys.SPHERE:{let a="normalize( ( viewMatrix * vec4( "+new Ys(Ys.VECTOR).build(e,"v3")+", 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) ).xy * 0.5 + 0.5";i?(e.addNodeCode(`vec2 reflectSphereVec = ${a};`),s="reflectSphereVec"):s=a;break}}return e.format(s,this.getType(),r)}else return console.warn("ReflectNode is not compatible with "+e.shader+" shader."),e.format("vec3( 0.0 )",this.type,r)}},No=Ys;No.CUBE="cube",No.SPHERE="sphere",No.VECTOR="vector";var X0=class extends tt{constructor(e=new bn,r,i){super("v4");this.nodeType="TextureCube";this.value=e,this.radianceNode=new kd(this.value,r??new No(No.VECTOR),i),this.irradianceNode=new kd(this.value,new Ui(Ui.WORLD),new Fe(1).setReadonly(!0))}generate(e,r){return e.isShader("fragment")?(e.require("irradiance"),e.context.bias&&e.context.bias.setTexture(this.value),(e.slot==="irradiance"?this.irradianceNode:this.radianceNode).build(e,r)):(console.warn("TextureCubeNode is not compatible with "+e.shader+" shader."),e.format("vec4( 0.0 )",this.getType(e),r))}};var K0=class extends ar{constructor(e=new Fu,r,i){super("v4",{shared:!0});this.nodeType="CubeTexture";this.value=e,this.uv=r??new No,this.bias=i}getTexture(e,r){return super.generate(e,r,this.value.uuid,"tc")}generate(e,r){if(r==="samplerCube")return this.getTexture(e,r);let i=this.getTexture(e,r),s=this.uv?.build(e,"v3"),o=this.bias?this.bias.build(e,"f"):void 0;o===void 0&&e.context.bias&&(o=e.context.bias.setTexture(this).build(e,"f"));let a;o?a="texCubeBias( "+i+", "+s+", "+o+" )":a="texCube( "+i+", "+s+" )";let l={include:e.isShader("vertex"),ignoreCache:!0},c=this.getType(e);return e.addContext(l),this.colorSpace=this.colorSpace??new xn(new Kt("",c)),this.colorSpace.fromDecoding(e.getTextureEncodingFromMap(this.value)),this.colorSpace.input.parse(a),a=this.colorSpace.build(e,c),e.removeContext(),e.format(a,c,r)}};var wR=` uniform int frameIndex; uniform vec2 resolution; uniform mat4 previousModelViewMatrix; uniform mat4 previousProjectionMatrix; varying vec4 vCurrentPosition; varying vec4 vPreviousPosition; `,AR=` layout(location = 1) out vec4 gVelocity; uniform int frameIndex; uniform vec2 resolution; varying vec4 vCurrentPosition; varying vec4 vPreviousPosition; const vec2 haltonSequence[16] = vec2[16]( vec2( 0.000000,-0.333334), vec2(-0.500000, 0.333334), vec2( 0.500000,-0.777778), vec2(-0.750000,-0.111112), vec2( 0.250000, 0.555556), vec2(-0.250000,-0.555556), vec2( 0.750000, 0.111112), vec2(-0.875000, 0.777778), vec2(0.125000, -0.925926), vec2(-0.375000, -0.259260), vec2(0.625000, 0.407408), vec2(-0.625000, -0.703704), vec2(0.375000, -0.037038), vec2(-0.125000, 0.629630), vec2(0.875000, -0.481482), vec2(-0.937500, 0.185186)); vec2 vogelDiskSample(int sampleIndex, int sampleCount, float angle) { const float goldenAngle = 2.399963f; // radians float r = sqrt(float(sampleIndex) + 0.5f) / sqrt(float(sampleCount)); float theta = float(sampleIndex) * goldenAngle + angle; float sine = sin(theta); float cosine = cos(theta); return vec2(cosine, sine) * r; } // Derived from the interleaved gradient function from Jimenez 2014 http:goo.gl/eomGso float getNoiseInterleavedGradient(vec2 screenPos) { vec3 magic = vec3(0.06711056f, 0.00583715f, 52.9829189f); return fract(magic.z * fract(dot(screenPos, magic.xy))); } `,ER=` // TODO: This could be generated CPU side and passed to the shader every frame const vec2 haltonSequence[16] = vec2[16]( vec2( 0.000000,-0.333334), vec2(-0.500000, 0.333334), vec2( 0.500000,-0.777778), vec2(-0.750000,-0.111112), vec2( 0.250000, 0.555556), vec2(-0.250000,-0.555556), vec2( 0.750000, 0.111112), vec2(-0.875000, 0.777778), vec2(0.125000, -0.925926), vec2(-0.375000, -0.259260), vec2(0.625000, 0.407408), vec2(-0.625000, -0.703704), vec2(0.375000, -0.037038), vec2(-0.125000, 0.629630), vec2(0.875000, -0.481482), vec2(-0.937500, 0.185186)); // TODO: Pass correct view size vec2 offset = haltonSequence[frameIndex]; offset.x /= resolution.x; offset.y /= resolution.y; vec4 currentPosition = gl_Position; vec4 currentPositionJittered = currentPosition + (vec4(offset.x, offset.y, 0.0, 0.0) * currentPosition.w); // We want to calculate the velocity with unjittered positions // so that things that are not moving get a velocity = 0 vCurrentPosition = currentPosition; vPreviousPosition = previousProjectionMatrix * previousModelViewMatrix * vec4(transformed, 1.0); #ifdef OUTLINE_COMPENSATION vPreviousPosition.xy += OUTLINE_COMPENSATION; #endif gl_Position = currentPositionJittered; `,TR=` vec2 oldPos = vPreviousPosition.xy; oldPos /= vPreviousPosition.w; oldPos.xy = (oldPos.xy+1.)/2.0; vec2 newPos = vCurrentPosition.xy; newPos /= vCurrentPosition.w; newPos.xy = (newPos.xy+1.)/2.0; vec2 velocity = (newPos - oldPos); // Discard fully transparent pixels if (gl_FragColor.a <= 0.0) discard; gVelocity = vec4(velocity, 0.0, 1.0); `,MR=` layout(location = 1) out vec4 gVelocity; `,CR=` // Discard fully transparent pixels if (gl_FragColor.a <= 0.0) discard; gVelocity = vec4(0.0, 0.0, 0.0, 1.0); `;var PR=["x","y","z","w"],iX=["float","vec2","vec3","vec4"],nX={float:"f",vec2:"v2",vec3:"v3",vec4:"v4",mat4:"v4",int:"i",bool:"b","float[]":"f[]","vec4[]":"v4[]"},sX={t:"sampler2D",tc:"samplerCube",b:"bool",i:"int",f:"float",c:"vec3",v2:"vec2",v3:"vec3",v4:"vec4",m3:"mat3",m4:"mat4","f[]":"float[]","v4[]":"vec4[]"},Ud=class{constructor(){this.includes={consts:{},functions:{},structs:{}};this.cache="";this.slot="";this.shader="";this.context={};this.needsJitter=!0;this.getIncludesCode=function(){function t(e,r){return e.deps.length-r.deps.length}return function(r,i){let s=this.getIncludes(r,i);if(!s)return"";let o="";s=s.sort(t);for(let a=0;a","#include "].join(` `),this.parsCode={vertex:["float neighbor_offset = 0.0001;",""].join(` `),fragment:["float accumAlpha = 0.0;",`void accumulateAlpha(float alpha) { accumAlpha += (1.0 - accumAlpha) * alpha; }`,""].join(` `)},this.code={vertex:"",fragment:""},this.nodeCode={vertex:"",fragment:""},this.resultCode={vertex:"",fragment:""},this.finalCode={vertex:"",fragment:""},this.inputs={uniforms:{list:[],vertex:[],fragment:[]},arrayUniforms:{list:[],vertex:[],fragment:[]},vars:{varying:[],vertex:[],fragment:[]}},this.defines={},this.uniforms={},this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},this.updaters=[],this.nodes=[],this.analyzing=!1}build(t,e){this.addVertexParsCode(wR),this.addFragmentParsCode(AR),this.buildShader("vertex",t),this.buildShader("fragment",e);for(let r=0;r0?r+1:"";this.addVaryCode("varying vec2 vUv"+i+";"),r>0&&this.addVertexParsCode("attribute vec2 uv"+i+";"),this.addVertexFinalCode("vUv"+i+" = uv"+i+";")}return this.requires.color[0]&&(this.addVaryCode("varying vec4 vColor;"),this.addVertexParsCode("attribute vec4 color;"),this.addVertexFinalCode("vColor = color;")),this.requires.color[1]&&(this.addVaryCode("varying vec4 vColor2;"),this.addVertexParsCode("attribute vec4 color2;"),this.addVertexFinalCode("vColor2 = color2;")),this.requires.position&&(this.addVaryCode("varying vec3 vPosition;"),this.addVertexFinalCode("vPosition = transformed;")),this.requires.worldPosition,this.requires.normal&&(this.addVaryCode("varying vec3 vObjectNormal;"),this.addVertexFinalCode("vObjectNormal = normal;")),this.requires.modelMatrix&&this.addFragmentParsCode("uniform mat4 modelMatrix;"),this.requires.viewMatrix&&this.addFragmentParsCode("uniform mat4 viewMatrix;"),this.requires.projectionMatrix&&this.addFragmentParsCode("uniform mat4 projectionMatrix;"),this.requires.worldNormal&&(this.addVaryCode("varying vec3 vWNormal;"),this.addVertexFinalCode("vWNormal = inverseTransformDirection( transformedNormal, viewMatrix ).xyz;")),this.requires.vWorldViewDir&&(this.addVaryCode("varying vec3 vWorldViewDir;"),this.addVertexFinalCode("vWorldViewDir = isPerspectiveMatrix( projectionMatrix ) ? ( (modelMatrix * vec4(position, 1.0)).xyz - cameraPosition ) : vec3( -viewMatrix[0][2], -viewMatrix[1][2], -viewMatrix[2][2] );")),this.needsJitter&&(this.addVertexFinalCode(ER),this.addFragmentFinalCode(TR)),this}buildShader(t,e){this.resultCode[t]=e.build(this.setShader(t),"v4")}setMaterial(t,e){return this.defines={},this}addFlow(t,e,r){return this.addSlot(t).addCache(e).addContext(r)}removeFlow(){return this.removeSlot().removeCache().removeContext()}addCache(t){return this.cache=t??"",this.caches.push(this.cache),this}removeCache(){return this.caches.pop(),this.cache=this.caches[this.caches.length-1]||"",this}addContext(t){return this.context=Object.assign({},this.context,t),this.context.extra=this.context.extra||{},this.contexts.push(this.context),this}removeContext(){return this.contexts.pop(),this.context=this.contexts[this.contexts.length-1]||{},this}addSlot(t){return this.slot=t||"",this.slots.push(this.slot),this}removeSlot(){return this.slots.pop(),this.slot=this.slots[this.slots.length-1]||"",this}addFragmentVariable(t,e){this.fragmentVariables[t]===void 0&&(this.addFragmentCode(`${e} ${t};`),this.fragmentVariables[t]="")}addFragmentParsVariable(t,e){this.fragmentParsVariables[t]===void 0&&(this.addFragmentParsCode(`${e} ${t};`),this.fragmentParsVariables[t]="")}addVertexParsVariable(t,e){this.vertexParsVariables[t]===void 0&&(this.addVertexParsCode(`${e} ${t};`),this.vertexParsVariables[t]="")}addVertexCode(t){this.addCode(t,"vertex")}addFragmentCode(t){this.addCode(t,"fragment")}addCode(t,e){this.code[e??this.shader]+=t+` `}addVertexNodeCode(t){this.addNodeCode(t,"vertex")}addFragmentNodeCode(t){this.addNodeCode(t,"fragment")}addNodeCode(t,e){this.nodeCode[e??this.shader]+=t+` `}clearNodeCode(t){t=t??this.shader;let e=this.nodeCode[t];return this.nodeCode[t]="",e}clearVertexNodeCode(){return this.clearNodeCode("vertex")}clearFragmentNodeCode(){return this.clearNodeCode("fragment")}addVertexFinalCode(t){this.addFinalCode(t,"vertex")}addFragmentFinalCode(t){this.addFinalCode(t,"fragment")}addFinalCode(t,e){this.finalCode[e??this.shader]+=t+` `}addVertexParsCode(t){this.addParsCode(t,"vertex")}addFragmentParsCode(t){this.addParsCode(t,"fragment")}addParsCode(t,e){this.parsCode[e??this.shader]+=t+` `}addVaryCode(t){this.addVertexParsCode(t),this.addFragmentParsCode(t)}isCache(t){return this.caches.indexOf(t)!==-1}isSlot(t){return this.slots.indexOf(t)!==-1}define(t,e){this.defines[t]=e===void 0?1:e}require(t){this.requires[t]=!0}isDefined(t){return this.defines[t]!==void 0}getVar(t,e,r,i="varying",s="V",o=""){let a=this.getVars(i),l=a[t];if(!l){let c=a.length;l={name:r||"node"+s+c+(o?"_"+o:""),type:e},a.push(l),a[t]=l}return l}getTempVar(t,e,r,i){return this.getVar(t,e,r,this.shader,"T",i)}getAttribute(t,e){if(!this.attributes[t]){let r=this.getVar(t,e);this.addVertexParsCode("attribute "+e+" "+t+";"),this.addVertexFinalCode(r.name+" = "+t+";"),this.attributes[t]={varying:r,name:t,type:e}}return this.attributes[t]}getCode(t){return[this.prefixCode,this.parsCode[t],this.getVarListCode(this.getVars("varying"),"varying"),this.getVarListCode(this.inputs.uniforms[t],"uniform"),this.getVarListCode(this.inputs.arrayUniforms[t],"uniform"),this.getIncludesCode("consts",t),this.getIncludesCode("structs",t),this.getIncludesCode("functions",t),"void main() {",this.getVarListCode(this.getVars(t)),this.code[t],this.resultCode[t],this.finalCode[t],"}"].join(` `)}getVarListCode(t,e){e=e??"";let r="";for(let i=0,s=t.length;i